Skip to content

Core Classes

Core classes for HEC-RAS project management and execution.

Important Notes

Most operation classes are static namespaces: call RasCmdr.compute_plan() or RasPlan methods directly. RasPrj project objects, workers, result records, and configuration types are instances. Construct those as documented.

RASMapper Flag Inversion

When using RasPlan.update_run_flags(), note that RASMapper flags have inverted logic:

  • Standard flags: True = -1, False = 0
  • RASMapper flag: True = 0, False = -1

This is a HEC-RAS quirk, not a library bug.

Input Flexibility

Decorated HDF readers accept the input forms documented for each method. Project selectors require initialization; direct paths are also supported:

Python
# Accepted by this reader:
HdfResultsMesh.get_mesh_max_ws("01")           # Plan number
HdfResultsMesh.get_mesh_max_ws(1)              # Integer
HdfResultsMesh.get_mesh_max_ws(Path("x.hdf")) # Path object

Project Management

init_ras_project

init_ras_project

Python
init_ras_project(ras_project_folder, ras_version=None, ras_object=None, load_results_summary=True, hide_intro=False, accept_tcu=False, load_hdf_metadata=True) -> RasPrj

Initialize a RAS project for use with the ras-commander library.

This is the primary function for setting up a HEC-RAS project. It: 1. Finds the project file (.prj) in the specified folder OR uses the provided .prj file 2. Validates .prj files by checking for "Proj Title=" marker 3. Identifies the appropriate HEC-RAS executable 4. Loads project data (plans, geometries, flows) 5. Creates dataframes containing project components 6. Loads HDF results summaries (if load_results_summary=True)

Parameters:

Name Type Description Default
ras_project_folder str or Path

Path to the RAS project folder OR direct path to a .prj file. If a .prj file is provided: - File is validated to have .prj extension - File content is checked for "Proj Title=" marker - Parent folder is used as the project folder

required
ras_version str

The version of RAS to use (e.g., "7.0") OR a full path to the Ras.exe file (e.g., "D:/Programs/HEC/HEC-RAS/6.6/Ras.exe"). If None, will attempt to detect from plan files.

None
ras_object RasPrj

If None, updates the global 'ras' object. If a RasPrj instance, updates that instance. If any other value, creates and returns a new RasPrj instance.

None
load_results_summary bool, default=True

If True, populate results_df with lightweight HDF results summaries at initialization. This enables quick queries of execution status and basic results via ras.results_df without needing to re-scan HDF files. Set to False for faster initialization when results are not needed.

True
hide_intro bool, default=False

If True, suppress the agent intro banner that is printed after initialization. The banner provides API guidance for AI agents using the library.

False
accept_tcu bool, default=False

HEC-RAS shows a modal "Terms and Conditions for Use" dialog the first time it runs for a Windows user+version, which blocks headless/COM launches. When False (default), init only WARNS if the TCU has not been accepted. When True, ras-commander explicitly attempts to seed an accepted registry subtree and verifies the release-specific sentinel. If verification fails, interactive acceptance is still required. See ras_commander.RasTcu.

False
load_hdf_metadata bool, default=True

If False, initialize project tables without opening HDF or raster datasets for geometry metadata or CRS discovery.

True

Returns:

Type Description
RasPrj

An initialized RasPrj instance.

Raises:

Type Description
FileNotFoundError

If the specified project folder or .prj file doesn't exist.

ValueError

If the provided file is not a .prj file, does not contain "Proj Title=", or if no HEC-RAS project file is found in the folder.

Example
Python
>>> # Initialize using project folder (existing behavior)
>>> init_ras_project("/path/to/project", "7.0")
>>> print(f"Initialized project: {ras.project_name}")
>>>
>>> # Initialize using direct .prj file path (new feature)
>>> init_ras_project("/path/to/project/MyModel.prj", "7.0")
>>> print(f"Initialized project: {ras.project_name}")
>>>
>>> # Create a new RasPrj instance with .prj file
>>> my_project = init_ras_project("/path/to/project/MyModel.prj", "7.0", "new")
>>> print(f"Created project instance: {my_project.project_name}")
>>>
>>> # Skip results loading for faster initialization
>>> init_ras_project("/path/to/project", "7.0", load_results_summary=False)
Source code in ras_commander/RasPrj.py
Python
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
@log_call
def init_ras_project(
    ras_project_folder,
    ras_version=None,
    ras_object=None,
    load_results_summary=True,
    hide_intro=False,
    accept_tcu=False,
    load_hdf_metadata=True,
) -> 'RasPrj':
    """
    Initialize a RAS project for use with the ras-commander library.

    This is the primary function for setting up a HEC-RAS project. It:
    1. Finds the project file (.prj) in the specified folder OR uses the provided .prj file
    2. Validates .prj files by checking for "Proj Title=" marker
    3. Identifies the appropriate HEC-RAS executable
    4. Loads project data (plans, geometries, flows)
    5. Creates dataframes containing project components
    6. Loads HDF results summaries (if load_results_summary=True)

    Args:
        ras_project_folder (str or Path): Path to the RAS project folder OR direct path to a .prj file.
                                          If a .prj file is provided:
                                          - File is validated to have .prj extension
                                          - File content is checked for "Proj Title=" marker
                                          - Parent folder is used as the project folder
        ras_version (str, optional): The version of RAS to use (e.g., "7.0") OR
                                     a full path to the Ras.exe file (e.g., "D:/Programs/HEC/HEC-RAS/6.6/Ras.exe").
                                     If None, will attempt to detect from plan files.
        ras_object (RasPrj, optional): If None, updates the global 'ras' object.
                                       If a RasPrj instance, updates that instance.
                                       If any other value, creates and returns a new RasPrj instance.
        load_results_summary (bool, default=True): If True, populate results_df with lightweight
                                                    HDF results summaries at initialization. This
                                                    enables quick queries of execution status and
                                                    basic results via ras.results_df without needing
                                                    to re-scan HDF files. Set to False for faster
                                                    initialization when results are not needed.
        hide_intro (bool, default=False): If True, suppress the agent intro banner that is
                                          printed after initialization. The banner provides
                                          API guidance for AI agents using the library.
        accept_tcu (bool, default=False): HEC-RAS shows a modal "Terms and Conditions for
                                          Use" dialog the first time it runs for a Windows
                                          user+version, which blocks headless/COM launches.
                                          When False (default), init only WARNS if the TCU
                                          has not been accepted. When True, ras-commander
                                          explicitly attempts to seed an accepted registry
                                          subtree and verifies the release-specific sentinel.
                                          If verification fails, interactive acceptance is
                                          still required. See ras_commander.RasTcu.
        load_hdf_metadata (bool, default=True): If False, initialize project
                                                tables without opening HDF or
                                                raster datasets for geometry
                                                metadata or CRS discovery.

    Returns:
        RasPrj: An initialized RasPrj instance.

    Raises:
        FileNotFoundError: If the specified project folder or .prj file doesn't exist.
        ValueError: If the provided file is not a .prj file, does not contain "Proj Title=",
                    or if no HEC-RAS project file is found in the folder.

    Example:
        ```python
        >>> # Initialize using project folder (existing behavior)
        >>> init_ras_project("/path/to/project", "7.0")
        >>> print(f"Initialized project: {ras.project_name}")
        >>>
        >>> # Initialize using direct .prj file path (new feature)
        >>> init_ras_project("/path/to/project/MyModel.prj", "7.0")
        >>> print(f"Initialized project: {ras.project_name}")
        >>>
        >>> # Create a new RasPrj instance with .prj file
        >>> my_project = init_ras_project("/path/to/project/MyModel.prj", "7.0", "new")
        >>> print(f"Created project instance: {my_project.project_name}")
        >>>
        >>> # Skip results loading for faster initialization
        >>> init_ras_project("/path/to/project", "7.0", load_results_summary=False)
        ```
    """
    # Convert to Path object for consistent handling
    # Use safe_resolve to preserve drive letters on Windows mapped network drives
    from .RasUtils import RasUtils
    input_path = RasUtils.safe_resolve(Path(ras_project_folder))

    # Detect if input is a file or folder
    if input_path.is_file():
        # User provided a .prj file path
        if input_path.suffix.lower() != '.prj':
            error_msg = f"The provided file is not a HEC-RAS project file (.prj): {input_path}"
            logger.error(error_msg)
            raise ValueError(f"{error_msg}. Please provide either a project folder or a .prj file.")

        # Enhanced validation: Check if file contains "Proj Title=" to verify it's a HEC-RAS project file
        try:
            content, encoding = read_file_with_fallback_encoding(input_path)
            if content is None or "Proj Title=" not in content:
                error_msg = f"The file does not appear to be a valid HEC-RAS project file (missing 'Proj Title='): {input_path}"
                logger.error(error_msg)
                raise ValueError(f"{error_msg}. Please provide a valid HEC-RAS .prj file.")
            logger.debug("Validated .prj file contains 'Proj Title=' marker")
        except Exception as e:
            error_msg = f"Error validating .prj file: {e}"
            logger.error(error_msg)
            raise ValueError(f"{error_msg}. Please ensure the file is a valid HEC-RAS project file.")

        # Extract the parent folder to use as project_folder
        project_folder = input_path.parent
        specified_prj_file = input_path  # Store for optimization
        logger.debug(f"User provided .prj file: {input_path}")
        logger.debug(f"Using parent folder as project_folder: {project_folder}")

    elif input_path.is_dir():
        # User provided a folder path (existing behavior)
        project_folder = input_path
        specified_prj_file = None
        logger.debug(f"User provided folder path: {project_folder}")

    else:
        # Path doesn't exist
        if input_path.suffix.lower() == '.prj':
            error_msg = f"The specified .prj file does not exist: {input_path}"
            logger.error(error_msg)
            raise FileNotFoundError(
                f"{error_msg}. Please check the path and try again. "
                f"See: https://rascommander.info/ras/getting-started/project-initialization/"
            )
        else:
            error_msg = f"The specified RAS project folder does not exist: {input_path}"
            logger.error(error_msg)
            raise FileNotFoundError(
                f"{error_msg}. Please check the path and try again. "
                f"See: https://rascommander.info/ras/getting-started/project-initialization/"
            )

    # Determine which RasPrj instance to use
    if ras_object is None:
        # Use the global 'ras' object
        logger.debug("Initializing global 'ras' object via init_ras_project function.")
        ras_object = ras
    elif not isinstance(ras_object, RasPrj):
        # Create a new RasPrj instance
        logger.debug("Creating a new RasPrj instance.")
        ras_object = RasPrj()

    ras_exe_path = None
    detected_version = None
    detected_version_source = None
    explicit_ras_exe_path = _is_explicit_ras_exe_path(ras_version)

    # Use version specified by user if provided
    if ras_version is not None:
        ras_exe_path = get_ras_exe(ras_version)
        if ras_exe_path == "Ras.exe" and ras_version != "Ras.exe":
            logger.warning(
                f"HEC-RAS Version {ras_version} was not found. Running HEC-RAS will fail. "
                f"See: https://rascommander.info/ras/getting-started/installation/"
            )
    else:
        # No version specified, try to detect from plan files
        logger.debug("No HEC-RAS version specified. Detecting from plan files.")

        # Look for .pXX files in project folder
        logger.debug(f"Searching for plan files in {project_folder}")
        # Search for any file with .p01 through .p99 extension, regardless of base name
        plan_files = list(project_folder.glob("*.p[0-9][0-9]"))

        if not plan_files:
            logger.debug(f"No plan files found in {project_folder}")

        for plan_file in plan_files:
            logger.debug(f"Found plan file: {plan_file.name}")
            content, encoding = read_file_with_fallback_encoding(plan_file)

            if not content:
                logger.debug(f"Could not read content from {plan_file.name}")
                continue

            logger.debug(f"Successfully read plan file with {encoding} encoding")

            # Look for Program Version in plan file
            for line in content.splitlines():
                if line.startswith("Program Version="):
                    version = line.split("=")[1].strip()
                    logger.debug(f"Found Program Version={version} in {plan_file.name}")

                    # Replace 00 in version string if present
                    if "00" in version:
                        version = version.replace("00", "0")

                    # Try to get RAS executable for this version
                    test_exe_path = get_ras_exe(version)
                    logger.debug(f"Checking RAS executable path: {test_exe_path}")

                    if test_exe_path != "Ras.exe":
                        detected_version = version
                        detected_version_source = plan_file.name
                        ras_exe_path = test_exe_path
                        logger.debug(f"Detected HEC-RAS version {version} from {plan_file.name}")
                        break
                    else:
                        logger.debug(f"Version {version} not found in default installation path")

            if detected_version:
                break

        if not detected_version:
            ras_exe_path = "Ras.exe"
            if _ras_unavailable_on_platform():
                logger.warning(_RAS_UNAVAILABLE_ON_PLATFORM_MESSAGE)
            else:
                logger.error("No valid HEC-RAS version found in any plan files.")
                logger.warning(
                    "No valid HEC-RAS version was detected. Running HEC-RAS will fail. "
                    "See: https://rascommander.info/ras/getting-started/installation/"
                )

    # Initialize or re-initialize with the determined executable path
    # Pass specified_prj_file to avoid re-searching when user provided .prj file directly
    if specified_prj_file is not None:
        ras_object.initialize(
            project_folder,
            ras_exe_path,
            prj_file=specified_prj_file,
            load_results_summary=load_results_summary,
            load_hdf_metadata=load_hdf_metadata,
        )
    else:
        ras_object.initialize(
            project_folder,
            ras_exe_path,
            load_results_summary=load_results_summary,
            load_hdf_metadata=load_hdf_metadata,
        )

    # Store version for RasControl (legacy COM interface support)
    ras_object.ras_version = ras_version if ras_version else detected_version

    # NOTE: Removed automatic global ras update for thread-safety
    # When ras_object is explicitly passed, we should NOT modify the global ras object
    # This allows multiple threads to use separate RasPrj instances without conflicts
    #
    # Previous behavior (removed):
    #   if ras_object is not ras:
    #       ras.initialize(project_folder, ras_exe_path, ...)  # This was NOT thread-safe
    #
    # If you need to update the global ras object, call init_ras_project without ras_object:
    #   init_ras_project(path, version)  # Updates global ras
    # Or explicitly pass ras_object=None (default behavior)

    # Log CLB Engineering branding banner with version and docs links
    from . import __version__
    _init_log = logger.debug if hide_intro else logger.info
    _init_log(
        f"ras-commander v{__version__} | "
        f"An open-source project of CLB Engineering Corporation (https://clbengineering.com/) | "
        f"Docs: https://rascommander.info | "
        f"GitHub: https://github.com/gpt-cmdr/ras-commander"
    )
    _init_log("Project initialized: %s", ras_object.project_name)
    logger.debug(f"Project initialized folder: {ras_object.project_folder}")
    if explicit_ras_exe_path and ras_exe_path != "Ras.exe":
        _init_log("Using HEC-RAS executable from explicit path")
    elif detected_version:
        _init_log(
            "Using HEC-RAS version %s (autodetected from %s)",
            detected_version,
            detected_version_source,
        )
    elif ras_exe_path == "Ras.exe":
        _init_log("Using HEC-RAS executable: Ras.exe (not resolved)")
    else:
        _init_log("Using HEC-RAS version %s", _ras_version_label(ras_version, ras_exe_path))
    logger.debug(f"Using HEC-RAS executable path: {ras_exe_path}")

    # HEC-RAS Terms & Conditions for Use (TCU) check. By default this is read-only:
    # it warns (once) when the TCU has not been accepted for this Windows user+version,
    # because the first headless/COM launch would otherwise block on a modal VB6 dialog.
    # When accept_tcu=True, registry seeding is attempted (opt-in write) and then
    # revalidated for the exact release. Never raises; never writes unless asked.
    try:
        from .RasTcu import RasTcu
        _tcu = RasTcu.status(ras_object=ras_object)
        if _tcu.accepted is False:
            if accept_tcu:
                _tcu = RasTcu.accept(ras_object=ras_object)
            if _tcu.accepted is not True:
                logger.warning(
                    "HEC-RAS %s Terms & Conditions for Use have NOT been accepted for the "
                    "current Windows user. The first headless/COM launch will block on a modal "
                    "\"Terms and Conditions for Use\" dialog. Open HEC-RAS %s in the GUI "
                    "and click \"I Agree\" for that exact installed release. "
                    "Terms: https://www.hec.usace.army.mil/software/hec-ras/",
                    _tcu.version or "", _tcu.version or "",
                )
    except Exception as _tcu_exc:  # never let the check break init
        logger.debug("TCU acceptance check skipped: %s", _tcu_exc)

    if not hide_intro:
        _obj = "ras" if ras_object is ras else "ras_object"
        logger.info(
            "\n"
            "═══════════════════════════════════════════════════════════════════════\n"
            "ras-commander | HEC-RAS Automation Library\n"
            "Docs: https://rascommander.info/ras/\n"
            "Repo: https://github.com/gpt-cmdr/ras-commander\n"
            "LLM agents: https://rascommander.info/ras/llms.txt\n"
            "═══════════════════════════════════════════════════════════════════════\n"
            "\n"
            "SUPPORT OPEN-SOURCE DEVELOPMENT:\n"
            "  Using RAS Commander? Please consider citing the library in published work\n"
            "  or mentioning it when sharing results on social media.\n"
            f"  Agents are encouraged to suggest a RAS Commander v{__version__} software\n"
            "  citation when helping prepare reports, publications, and other shared work.\n"
            "  Citations recognize RAS Commander and its contributors and help sustain\n"
            "  continued open-source development.\n"
            "  Citation and sharing guidance: https://rascommander.info/ras/cite/\n"
            "\n"
            "PROJECT DATAFRAMES (single source of truth — use these, not file globbing):\n"
            f"  {_obj}.plan_df        Plans, HDF paths, geometry/flow associations\n"
            f"  {_obj}.geom_df        Geometry files and HDF preprocessor paths\n"
            f"  {_obj}.flow_df        Steady flow files\n"
            f"  {_obj}.unsteady_df    Unsteady flow files and configurations\n"
            f"  {_obj}.boundaries_df  Boundary conditions (type, name, location)\n"
            f"  {_obj}.results_df     Lightweight HDF results summaries\n"
            f"  {_obj}.rasmap_df      RASMapper layers, terrain, land cover paths\n"
            "\n"
            "KEY APIS (static classes — call directly, never instantiate):\n"
            "  Execution:    RasCmdr.compute_plan() / compute_parallel() / compute_test_mode()\n"
            "  Plan Files:   RasPlan.clone_plan() / clone_geom() / set_geom()\n"
            "  Unsteady:     RasUnsteady — IC/BC management, gate openings, precipitation\n"
            "  Geometry:     GeomCrossSection, GeomBridge, GeomStorage, GeomLateral, GeomMesh\n"
            "  HDF Results:  HdfResultsPlan.get_wse() / get_compute_messages()\n"
            "                HdfResultsMesh.get_mesh_max_ws() / get_mesh_cells_timeseries()\n"
            "                HdfMesh.get_mesh_cell_points()\n"
            "  QA/QC:        RasCheck.run_check() / RasFixit (geometry repair)\n"
            "  DSS:          RasDss.get_timeseries() / check_pathname()\n"
            "  USGS:         UsgsGaugeSpatial, GaugeMatcher, RasUsgsBoundaryGeneration\n"
            "  Precipitation: StormGenerator, Atlas14Storm, PrecipAorc, Atlas14Variance\n"
            "  Terrain:      RasTerrain.create_terrain_hdf() / RasTerrainMod\n"
            "\n"
            "MULTI-PROJECT: Pass ras_object= to all API calls when using local RasPrj instances.\n"
            "\n"
            "EXAMPLES: 100+ notebooks in examples/ (100s=execution, 200s=geometry, 300s=unsteady,\n"
            "  400s=HDF results, 500s=remote, 800s=QA/QC, 900s=data integration).\n"
            "  Review relevant notebooks before assembling new workflows.\n"
            "\n"
            "PLATFORM: Most HEC-RAS operations require Windows. Linux/Wine support for\n"
            "  headless execution, data access, geometry modification, and preprocessing\n"
            "  is available via RasProcess (HEC-RAS 6.6+). See ras_commander/RasProcess.py.\n"
            "  Remote distributed execution: ras_commander/remote/ (PsExec, Docker, SSH, cloud).\n"
            "═══════════════════════════════════════════════════════════════════════"
        )

    return ras_object

RasPrj

Project initialization populates paths and metadata tables on a RasPrj instance. See the DataFrame reference for those instance attributes; the operations below are the source-derived methods.

check_initialized

Python
check_initialized()

Ensure that the RasPrj instance has been initialized before operations.

Raises:

Type Description
RuntimeError

If the project has not been initialized with init_ras_project().

Note

This method is called by other methods to validate the project state before performing operations. Users typically don't need to call this directly.

find_ras_prj staticmethod

Python
find_ras_prj(folder_path)

Find the appropriate HEC-RAS project file (.prj) in the given folder.

This method uses several strategies to locate the correct project file: 1. If only one .prj file exists, it is selected 2. If multiple .prj files exist, it tries to match with .rasmap file names 3. As a last resort, it scans files for "Proj Title=" content

Parameters:

Name Type Description Default
folder_path str or Path

Path to the folder containing HEC-RAS files.

required

Returns:

Type Description
Path

The full path of the selected .prj file or None if no suitable file is found.

Example
Python
>>> project_file = RasPrj.find_ras_prj("/path/to/ras_project")
>>> if project_file:
...     print(f"Found project file: {project_file}")
... else:
...     print("No project file found")

get_boundary_conditions

Python
get_boundary_conditions() -> pd.DataFrame

Extract boundary conditions from unsteady flow files into a structured DataFrame.

This method: 1. Parses all unsteady flow files to extract boundary condition information 2. Creates a structured DataFrame with boundary locations, types and parameters 3. Links boundary conditions to their respective unsteady flow files

Supported boundary condition types include: - Flow Hydrograph - Stage Hydrograph - Precipitation Hydrograph - Rating Curve - Normal Depth - Lateral Inflow Hydrograph - Uniform Lateral Inflow Hydrograph - Gate Opening

Returns:

Type Description
DataFrame

A DataFrame containing detailed boundary condition information. Returns an empty DataFrame if no unsteady flow files are present.

Example
Python
>>> boundaries = ras.get_boundary_conditions()
>>> if not boundaries.empty:
...     print(f"Found {len(boundaries)} boundary conditions")
...     # Show flow hydrographs only
...     flow_hydrographs = boundaries[boundaries['bc_type'] == 'Flow Hydrograph']
...     print(f"Project has {len(flow_hydrographs)} flow hydrographs")

Note: To see unparsed boundary condition lines for debugging, set logging to DEBUG: import logging logging.getLogger().setLevel(logging.DEBUG)

get_flow_entries

Python
get_flow_entries()

Get all flow entries from the HEC-RAS project.

Returns a DataFrame containing all flow files (.f*) in the project with their associated properties and paths.

Returns:

Type Description
DataFrame

A DataFrame with columns including 'flow_number', 'full_path', etc.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> flow_entries = ras.get_flow_entries()
>>> print(f"Project contains {len(flow_entries)} flow files")
>>> # Display the first flow file's properties
>>> if not flow_entries.empty:
...     print(flow_entries.iloc[0])

get_geom_entries

Python
get_geom_entries()

Get all geometry entries from the HEC-RAS project.

Returns a DataFrame containing all geometry files (.g*) in the project with their associated properties, paths, HDF links, and geometry metadata.

Returns:

Type Description
DataFrame

A DataFrame with the following columns: - geom_file (str): Geometry file identifier (e.g., 'g01') - geom_number (str): Geometry number extracted from identifier - full_path (str): Full path to plain text geometry file - hdf_path (str): Path to geometry HDF file (.g##.hdf) - geom_title (str): Geometry title from 'Geom Title=' line - description (str): Description from BEGIN/END DESCRIPTION block - has_1d_xs (bool): True if geometry has 1D cross sections - has_2d_mesh (bool): True if geometry text declares a 2D flow area or HDF metadata identifies a mesh area - num_cross_sections (int): Count of 1D cross sections - num_inline_structures (int): Total count of bridges + culverts + weirs - num_bridges (int): Count of bridge structures - num_culverts (int): Count of culvert structures - num_weirs (int): Count of inline weir structures - num_gates (int): Count of gate structures - num_lateral_structures (int): Count of lateral structures - num_sa_2d_connections (int): Count of SA to 2D connections - mesh_cell_count (int): Total 2D mesh cells across all areas - mesh_area_names (list[str]): Names of 2D flow areas

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Note

Geometry metadata is extracted using GeomMetadata, which prefers HDF-based extraction (fast) when .g##.hdf files exist, with plain text fallback. If metadata extraction fails for any geometry, default values are used (0 for counts, False for booleans, empty list for mesh_area_names).

Example
Python
>>> geom_entries = ras.get_geom_entries()
>>> print(f"Project contains {len(geom_entries)} geometry files")
>>> # Display the first geometry file's properties
>>> if not geom_entries.empty:
...     print(geom_entries.iloc[0])
>>> # Filter to geometries with 2D mesh
>>> mesh_geoms = geom_entries[geom_entries['has_2d_mesh']]
>>> print(f"Found {len(mesh_geoms)} geometries with 2D mesh")

get_hdf_entries

Python
get_hdf_entries()

Get all plan entries that have associated HDF results files.

This method identifies which plans have been successfully computed and have HDF results available for further analysis.

Returns:

Type Description
DataFrame

A DataFrame containing plan entries with HDF results. Returns an empty DataFrame if no results are found.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> hdf_entries = ras.get_hdf_entries()
>>> if hdf_entries.empty:
...     print("No computed results found. Run simulations first.")
... else:
...     print(f"Found results for {len(hdf_entries)} plans")

Note: This is useful for identifying which plans have been successfully computed and can be used for further results analysis.

get_hdf_paths

Python
get_hdf_paths(plan_number: str) -> Dict[str, Optional[Path]]

Get HDF file paths for a specific plan.

This is a convenience method to quickly access both the results HDF and geometry HDF paths for a plan, avoiding repeated DataFrame lookups.

Parameters:

Name Type Description Default
plan_number str

Plan number string (e.g., '01', '02')

required

Returns:

Type Description
Dict with keys
-results

Path to results HDF file (or None if not computed)

-geometry

Path to geometry HDF file (or None)

Example
Python
>>> paths = ras.get_hdf_paths('01')
>>> if paths['results']:
...     data = HdfResultsPlan.get_runtime_data(paths['results'])

get_plan_entries

Python
get_plan_entries()

Get all plan entries from the HEC-RAS project.

Returns a DataFrame containing all plan files (.p*) in the project with their associated properties, paths and settings.

Returns:

Type Description
DataFrame

A DataFrame with columns including 'plan_number', 'full_path', 'unsteady_number', 'geometry_number', etc.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> plan_entries = ras.get_plan_entries()
>>> print(f"Project contains {len(plan_entries)} plan files")
>>> # Display the first plan's properties
>>> if not plan_entries.empty:
...     print(plan_entries.iloc[0])

get_plan_info

Python
get_plan_info(plan_number: str) -> Dict

Get key attributes for a specific plan.

Parameters:

Name Type Description Default
plan_number str

Plan number string (e.g., '01', '02')

required

Returns:

Type Description
Dict with keys
-plan_number

The plan number

-title

Plan title

-shortid

Short identifier

-has_results

Whether HDF results exist

-results_path

Path to HDF results file (or None)

-geom_path

Path to geometry file

-flow_path

Path to flow file

Example
Python
>>> info = ras.get_plan_info('01')
>>> print(f"Plan: {info['title']}, Has Results: {info['has_results']}")

get_plan_value staticmethod

Python
get_plan_value(plan_number_or_path: Union[str, Path], key: str, ras_object=None) -> Any

Retrieve a specific value from a HEC-RAS plan file.

Parameters: plan_number_or_path (Union[str, Path]): The plan number (1 to 99) or full path to the plan file key (str): The key to retrieve from the plan file ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: Any: The value associated with the specified key

Raises: ValueError: If the plan file is not found IOError: If there's an error reading the plan file

get_plans_with_results

Python
get_plans_with_results() -> List[str]

Get list of plan numbers that have HDF results files.

Returns:

Type Description
List[str]

List of plan number strings (e.g., ['01', '02'])

Example
Python
>>> ras = init_ras_project('/path/to/project', '6.6')
>>> plans = ras.get_plans_with_results()
>>> print(f"Plans with results: {plans}")

get_plans_without_results

Python
get_plans_without_results() -> List[str]

Get list of plan numbers that do not have HDF results files.

Returns:

Type Description
List[str]

List of plan number strings

Example
Python
>>> plans_pending = ras.get_plans_without_results()
>>> print(f"Plans needing execution: {plans_pending}")

get_prj_entries

Python
get_prj_entries(entry_type)

Get entries of a specific type from the HEC-RAS project.

This method extracts files of the specified type from the project file, parses their content, and returns a structured DataFrame.

Parameters:

Name Type Description Default
entry_type str

The type of entry to retrieve ('Plan', 'Flow', 'Unsteady', or 'Geom').

required

Returns:

Type Description
DataFrame

A DataFrame containing the requested entries with appropriate columns.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> # Get all geometry files in the project
>>> geom_entries = ras.get_prj_entries('Geom')
>>> print(f"Project contains {len(geom_entries)} geometry files")

Note: This is a generic method. For specific file types, use the dedicated methods: get_plan_entries(), get_flow_entries(), get_unsteady_entries(), get_geom_entries()

get_project_name

Python
get_project_name()

Get the name of the HEC-RAS project (without file extension).

Returns:

Type Description
str

The name of the project.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> project_name = ras.get_project_name()
>>> print(f"Working with project: {project_name}")

get_project_units staticmethod

Python
get_project_units(project_file: Union[str, Path]) -> Optional[str]

Return the HEC-RAS project length units as "ft" or "m".

HEC-RAS project files normally use a bare English Units or SI Units marker. Some generated projects instead use the legacy boolean form SI Units=<bool>. Both representations are parsed case-insensitively; unreadable files or unknown values return None.

get_results_entries

Python
get_results_entries() -> pd.DataFrame

Build complete results_df from scratch.

Generates results summaries for all plans in the project. This is equivalent to calling update_results_df(None).

Returns:

Type Description
DataFrame

Results summary for all plans

Note

This method regenerates results_df completely, replacing any existing cached results.

get_unsteady_entries

Python
get_unsteady_entries()

Get all unsteady flow entries from the HEC-RAS project.

Returns a DataFrame containing all unsteady flow files (.u*) in the project with their associated properties and paths.

Returns:

Type Description
DataFrame

A DataFrame with columns including 'unsteady_number', 'full_path', etc.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> unsteady_entries = ras.get_unsteady_entries()
>>> print(f"Project contains {len(unsteady_entries)} unsteady flow files")
>>> # Display the first unsteady file's properties
>>> if not unsteady_entries.empty:
...     print(unsteady_entries.iloc[0])

initialize

Python
initialize(project_folder, ras_exe_path, suppress_logging=True, prj_file=None, load_results_summary=True, load_hdf_metadata=True)

Initialize a RasPrj instance with project folder and RAS executable path.

IMPORTANT: External users should use init_ras_project() function instead of this method. This method is intended for internal use only.

Parameters:

Name Type Description Default
project_folder str or Path

Path to the HEC-RAS project folder.

required
ras_exe_path str or Path

Path to the HEC-RAS executable.

required
suppress_logging bool, default=True

If True, suppresses initialization logging messages.

True
prj_file str or Path

If provided, use this specific .prj file instead of searching. This is used when user specifies a .prj file directly.

None
load_results_summary bool, default=True

If True, populate results_df with lightweight HDF results summaries at initialization. This enables quick queries of execution status and basic results without re-scanning HDF files.

True
load_hdf_metadata bool, default=True

If False, do not open HDF or raster datasets while initializing geometry metadata and project CRS.

True

Raises:

Type Description
ValueError

If no HEC-RAS project file is found in the specified folder, or if the specified prj_file doesn't exist or is invalid.

Note

This method sets up the RasPrj instance by: 1. Finding the project file (.prj) or using the provided prj_file 2. Loading project data (plans, geometries, flows) 3. Extracting boundary conditions 4. Setting the initialization flag 5. Loading RASMapper data (.rasmap) 6. Loading results summaries (if load_results_summary=True)

print_data

Python
print_data()

Print a comprehensive summary of all RAS Object data for this instance.

This method outputs: - Project information (name, folder, file paths) - Summary of plans, flows, geometries, and unsteady files - HDF results availability - Boundary conditions

Useful for debugging, validation, and exploring project structure.

Raises:

Type Description
RuntimeError

If the project has not been initialized.

Example
Python
>>> ras.print_data()  # Displays complete project overview

refresh_project_crs

Python
refresh_project_crs() -> Optional[str]

Recompute the resolved project CRS and cache the result on the object.

The CRS uses the same evidence rule and string form as HdfBase.get_projection: "EPSG:n" when an EPSG definition is strictly equivalent, otherwise WKT. Conflicting evidence across the project's geometry HDFs, plan HDFs, .rasmap projection file and terrain HDFs yields None and project_crs_status == "conflict" (ras-commander <= 0.106.1 returned the first CRS found).

Returns:

Type Description
Optional[str]

CRS as an EPSG string, WKT string, or None if not

Optional[str]

resolvable (missing) or ambiguous (conflict) from project files.

set_current_plan

Python
set_current_plan(plan_number: Union[str, int])

Set the current plan in the HEC-RAS project file (.prj).

This ensures that when HEC-RAS opens, it opens with the specified plan active.

Parameters:

Name Type Description Default
plan_number Union[str, int]

The plan number to set as current (e.g., "01" or 1)

required

Raises:

Type Description
RuntimeError

If the project has not been initialized

ValueError

If the plan number is invalid or not found

IOError

If there's an error reading or writing the project file

Example
Python
>>> ras.set_current_plan("01")
>>> # HEC-RAS will now open with plan 01 active

update_results_df

Python
update_results_df(plan_numbers: List[str] = None) -> pd.DataFrame

Update results_df with HDF-based summaries for specified plans.

Extracts lightweight summary data from HDF files including compute messages, runtime data, and volume accounting.

Parameters:

Name Type Description Default
plan_numbers List[str]

List of plan numbers to update (e.g., ["01", "02"]). If None, updates all plans in plan_df.

None

Returns:

Type Description
DataFrame

Updated results_df

Example
Python
>>> init_ras_project("path/to/project", "7.0")
>>> ras.update_results_df(["01"])  # Update specific plan
>>> ras.update_results_df()  # Update all plans
>>> print(ras.results_df[['plan_number', 'completed', 'has_errors']])

Project asset inspection

inspect_project_assets() builds a read-only, PyArrow-backed inventory of a project's declared components, plan dependency closure, HDF sidecars, RASMapper references, DSS links, restart/prior-water-surface inputs, and gridded precipitation inputs. Use an explicit inspection depth rather than assuming every file beside a project is required by the current plan. The shallow project depth initializes project tables without opening HDF or raster datasets for geometry metadata or CRS discovery.

Relative references accept both slash styles, with paired quotes removed. Native absolute paths resolve on their host; Windows drive/UNC anchors cannot be mapped on POSIX. Unresolved Windows anchors retain raw-reference inventory evidence with null local paths and file facts. The shared RASMapper resolver preserves foreign references as lexical paths without a project-folder prefix; these are not native host resolutions. Inventory diagnoses both structured and raw references before reading file facts. Resolved %NAME% and host $NAME/${NAME} variables expand from the current environment. Unresolved environment-variable handling retains legacy lexical behavior and is outside this host-anchor contract. See the inventory reason codes. Finding a terrain file leaves its readiness unknown until its plan dependency is established; path resolution alone does not establish hydraulic acceptance.

Python
from ras_commander import inspect_project_assets

assets = inspect_project_assets(
    r"C:\Models\Source\Model.prj",
    depth="current_plan",
    hash_files=True,
    dss_inspection="none",
)

not_ready = assets.loc[
    (assets["required"] == True) & (assets["readiness"] == "not_ready")
]

inspect_project_assets

Python
inspect_project_assets(project: Union[str, Path], *, ras_object: Optional[RasPrj] = None, depth: InspectionDepth = 'all_plans', hash_files: bool = False, dss_inspection: DssInspection = 'none') -> pd.DataFrame

Return a read-only, DataFrame-first inventory of linked project assets.

DSS file references are inventoried, but DSS containers are not opened by this implementation. Requests for catalog or coverage therefore remain explicit not_inspected dataset rows until the underlying reader has a proven source-immutable open contract.

Source code in ras_commander/RasProject.py
Python
@log_call
def inspect_project_assets(
    project: Union[str, Path],
    *,
    ras_object: Optional[RasPrj] = None,
    depth: InspectionDepth = "all_plans",
    hash_files: bool = False,
    dss_inspection: DssInspection = "none",
) -> pd.DataFrame:
    """Return a read-only, DataFrame-first inventory of linked project assets.

    DSS file references are inventoried, but DSS containers are not opened by
    this implementation. Requests for ``catalog`` or ``coverage`` therefore
    remain explicit ``not_inspected`` dataset rows until the underlying reader
    has a proven source-immutable open contract.
    """
    cache = _InventoryHashCache() if hash_files else None
    token = _ACTIVE_INVENTORY_HASH_CACHE.set(cache)
    try:
        frame = _inspect_project_assets_impl(
            project,
            ras_object=ras_object,
            depth=depth,
            hash_files=hash_files,
            dss_inspection=dss_inspection,
        )
        if cache is not None:
            cache.verify()
        return frame
    finally:
        _ACTIVE_INVENTORY_HASH_CACHE.reset(token)

Atomic project staging

stage_project() copies a complete project tree into a unique temporary sibling, verifies every source and copied file with streaming SHA-256, creates an explicit RasPrj, inventories the staged dependencies, writes a stage manifest, and publishes with one final directory rename. It never runs or preprocesses HEC-RAS.

The destination's parent must already exist and the destination itself must not exist. The operation fails closed on overlap, reparse/symlink ambiguity, lock artifacts, source or copy drift, an invalid project population, and destination races. Failures use typed ProjectStageError subclasses with a machine-readable reason_code; an initially existing destination retains the standard FileExistsError. Existing RasCmdr copy behavior is unchanged.

Python
from ras_commander import stage_project

staged = stage_project(
    r"C:\Models\Source\Model.prj",
    r"D:\Runs\model-2026-08-23",
)

print(staged.destination_project_file)
print(staged.execution_readiness)
print(staged.fingerprint_algorithm)

The four StageProjectResult fingerprint fields share the explicitly versioned ras_commander.stage_project.framed_tree.v1 algorithm. That digest covers the staged tree's directory population and framed file records. It is deliberately not interchangeable with a qualification-harness source snapshot, whose canonical-JSON digest has a separate algorithm identifier. Consumers should compare fingerprints only when their algorithm identifiers also match. The same stage algorithm identifier is persisted in .ras-commander/stage.json.

stage_project

Python
stage_project(source: Union[str, Path], destination: Union[str, Path], *, ras_object: Optional[RasPrj] = None) -> StageProjectResult

Copy, verify, initialize, and atomically publish a HEC-RAS project tree.

destination is a new project directory. Existing destinations, overlapping paths, reparse points, lock artifacts, source drift, copy drift, and publication races fail without replacing an existing tree.

Source code in ras_commander/RasProject.py
Python
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
@log_call
def stage_project(
    source: Union[str, Path],
    destination: Union[str, Path],
    *,
    ras_object: Optional[RasPrj] = None,
) -> StageProjectResult:
    """Copy, verify, initialize, and atomically publish a HEC-RAS project tree.

    ``destination`` is a new project directory.  Existing destinations,
    overlapping paths, reparse points, lock artifacts, source drift, copy
    drift, and publication races fail without replacing an existing tree.
    """
    operation_id = str(uuid.uuid4())
    source_input = Path(source).absolute()
    _assert_no_reparse_ancestry(source_input)
    try:
        source_project = _resolve_project_file(source)
    except ProjectStageError:
        raise
    except (FileNotFoundError, OSError, TypeError, ValueError) as exc:
        raise ProjectPopulationError("invalid_source_project", str(exc)) from exc
    source_root = source_project.parent
    _assert_no_reparse_ancestry(source_root)
    if ras_object is not None:
        try:
            _explicit_ras(source_project, ras_object)
        except (OSError, TypeError, ValueError) as exc:
            raise ProjectPopulationError("ras_object_mismatch", str(exc)) from exc

    destination_root = Path(destination).absolute()
    if _path_lexists(destination_root):
        raise FileExistsError(f"Destination already exists: {destination_root}")
    destination_parent = destination_root.parent
    if not _path_exists(destination_parent):
        raise ProjectPathAmbiguityError(
            "destination_parent_missing",
            f"Destination parent must already exist: {destination_parent}",
        )
    _assert_no_reparse_ancestry(destination_parent)
    try:
        _assert_regular_path(destination_parent, expected_directory=True)
    except (OSError, ValueError) as exc:
        raise ProjectPathAmbiguityError(
            "destination_parent_invalid",
            f"Destination parent is not an ordinary directory: {destination_parent}",
        ) from exc

    source_real = os.path.normcase(os.path.realpath(_io_path(source_root)))
    destination_real = os.path.normcase(os.path.realpath(_io_path(destination_root)))
    try:
        overlap = os.path.commonpath([source_real, destination_real]) in {
            source_real,
            destination_real,
        }
    except ValueError:
        overlap = False
    try:
        identity_overlap = _source_contains_destination(
            source_root,
            destination_parent,
        )
    except OSError as exc:
        raise ProjectPathAmbiguityError(
            "path_identity_unavailable",
            "Could not prove source/destination physical separation",
        ) from exc
    if overlap or identity_overlap:
        raise ProjectPathAmbiguityError(
            "path_overlap",
            "Source and destination project trees must not overlap",
        )
    if _path_lexists(source_root / _STAGE_METADATA_DIR):
        raise ProjectPopulationError(
            "reserved_metadata_present",
            f"Source contains reserved staging metadata directory: {_STAGE_METADATA_DIR}",
        )

    lock_path = destination_parent / f".{destination_root.name}.rascommander-stage.lock"
    lock_handle: Optional[int] = None
    lock_identity: Optional[tuple[int, int]] = None
    lock_token = f"pid={os.getpid()};token={uuid.uuid4()}".encode("ascii")
    temp_root: Optional[Path] = None
    published = False
    try:
        try:
            lock_handle = os.open(
                _io_path(lock_path),
                os.O_CREAT | os.O_EXCL | os.O_WRONLY,
            )
        except FileExistsError as exc:
            raise ProjectLockedError(
                "staging_lock_exists",
                f"Another staging operation owns the destination lock: {lock_path.name}",
            ) from exc
        lock_info = os.fstat(lock_handle)
        lock_identity = lock_info.st_dev, lock_info.st_ino
        if os.write(lock_handle, lock_token) != len(lock_token):
            raise ProjectLockedError(
                "staging_lock_write_failed",
                "Could not write the complete staging lock identity",
            )

        source_files_before, source_before, copied_bytes = _tree_snapshot(source_root)
        source_directories_before = _directory_population(source_root)
        temp_root = _public_path(
            os.path.realpath(
                _io_path(
                    tempfile.mkdtemp(
                        prefix=f".{destination_root.name}.ras-stage-",
                        dir=_io_path(destination_parent),
                    )
                )
            )
        )
        sentinel = temp_root / _TEMP_SENTINEL
        _io_path(sentinel).write_text(operation_id, encoding="ascii")
        _copy_snapshot(
            source_root,
            temp_root,
            source_files_before,
            source_directories_before,
        )

        _io_path(sentinel).unlink()
        try:
            copied_files, copied_fingerprint, copied_total = _tree_snapshot(temp_root)
            copied_directories = _directory_population(temp_root)
        finally:
            if _path_exists(temp_root) and not _path_lexists(sentinel):
                _io_path(sentinel).write_text(operation_id, encoding="ascii")
        _assert_copy_equal(source_files_before, copied_files)
        if copied_directories != source_directories_before:
            raise ProjectCopyVerificationError(
                "copy_directory_population_mismatch",
                "Copied directory population differs from source snapshot",
            )
        if copied_total != copied_bytes:
            raise ProjectCopyVerificationError(
                "copy_size_mismatch",
                "Copied byte count differs from source snapshot",
            )
        temp_project = temp_root / source_project.relative_to(source_root)
        try:
            staged_ras = init_ras_project(
                _io_path(temp_project),
                ras_version=_declared_current_plan_version(temp_project),
                ras_object=RasPrj(),
                load_results_summary=False,
                hide_intro=True,
            )
            _validate_current_plan(temp_project, staged_ras)
            assets = inspect_project_assets(
                temp_project,
                ras_object=staged_ras,
                depth="all_plans",
                hash_files=True,
                dss_inspection="none",
            )
        except ProjectStageError:
            raise
        except Exception as exc:
            raise ProjectPopulationError(
                "staged_initialization_failed",
                "The verified copy could not be initialized and inventoried",
            ) from exc
        _validate_project_population(assets)
        readiness = _stage_readiness(assets)

        _io_path(sentinel).unlink()
        try:
            verified_files, verified_fingerprint, verified_total = _tree_snapshot(
                temp_root
            )
            verified_directories = _directory_population(temp_root)
        finally:
            if _path_exists(temp_root) and not _path_lexists(sentinel):
                _io_path(sentinel).write_text(operation_id, encoding="ascii")
        _assert_copy_equal(source_files_before, verified_files)
        if verified_fingerprint != copied_fingerprint:
            raise ProjectCopyVerificationError(
                "copy_fingerprint_drift",
                "Verified copied-tree fingerprint changed during staged inspection",
            )
        if verified_directories != source_directories_before:
            raise ProjectCopyVerificationError(
                "copy_directory_drift",
                "Copied directory population changed during staged inspection",
            )
        if verified_total != copied_bytes:
            raise ProjectCopyVerificationError(
                "copy_size_drift",
                "Copied byte count changed during staged inspection",
            )

        source_files_after, source_after, _ = _tree_snapshot(source_root)
        source_directories_after = _directory_population(source_root)
        if (
            source_files_after != source_files_before
            or source_directories_after != source_directories_before
            or source_after != source_before
        ):
            raise ProjectDriftError(
                "source_changed",
                "Source project changed while staging",
            )

        destination_project = destination_root / source_project.name
        final_assets = _rebase_frame(assets, temp_root, destination_root)
        final_ras = _rebase_ras_object(staged_ras, temp_root, destination_root)
        state_counts = final_assets["inspection_state"].value_counts().to_dict()

        metadata_dir = temp_root / _STAGE_METADATA_DIR
        _io_path(metadata_dir).mkdir(exist_ok=False)
        manifest_path = metadata_dir / _STAGE_MANIFEST
        manifest = {
            "schema_version": 1,
            "operation_id": operation_id,
            "fingerprint_algorithm": STAGE_PROJECT_TREE_FINGERPRINT_ALGORITHM,
            "source_project_file": str(source_project),
            "destination_project_file": str(destination_root / source_project.name),
            "source_fingerprint_before": source_before,
            "source_fingerprint_after": source_after,
            "copied_fingerprint": copied_fingerprint,
            "copied_file_count": len(source_files_before),
            "copied_bytes": copied_bytes,
            "execution_readiness": readiness,
            "created_at": datetime.now(timezone.utc).isoformat(),
            "artifacts": [
                {
                    "relative_path": item.relative_path,
                    "provenance": "copied_source",
                    "size_bytes": item.size_bytes,
                    "sha256": item.sha256,
                }
                for _, item in sorted(
                    source_files_before.items(),
                    key=lambda pair: pair[0].casefold(),
                )
            ]
            + [
                {
                    "relative_path": f"{_STAGE_METADATA_DIR}/{_STAGE_MANIFEST}",
                    "provenance": "generated_stage_metadata",
                }
            ],
        }
        with _io_path(manifest_path).open(
            "x",
            encoding="utf-8",
            newline="\n",
        ) as stream:
            json.dump(manifest, stream, indent=2, sort_keys=True)
            stream.write("\n")

        _io_path(sentinel).unlink()
        _fsync_tree(temp_root)
        _fsync_path(destination_parent, directory=True)

        source_files_final, source_after, _ = _tree_snapshot(source_root)
        source_directories_final = _directory_population(source_root)
        if (
            source_files_final != source_files_before
            or source_directories_final != source_directories_before
            or source_after != source_before
        ):
            raise ProjectDriftError(
                "source_changed_before_publish",
                "Source project changed before publication",
            )

        final_files, prepared_fingerprint, prepared_total = _tree_snapshot(temp_root)
        final_directories = _directory_population(temp_root)
        metadata_prefix = f"{_STAGE_METADATA_DIR}/"
        final_copied_files = {
            relative: snapshot
            for relative, snapshot in final_files.items()
            if not relative.startswith(metadata_prefix)
        }
        metadata_files = {
            relative
            for relative in final_files
            if relative.startswith(metadata_prefix)
        }
        expected_metadata_files = {
            f"{_STAGE_METADATA_DIR}/{_STAGE_MANIFEST}",
        }
        if metadata_files != expected_metadata_files:
            raise ProjectCopyVerificationError(
                "generated_metadata_population_drift",
                "Generated staging metadata population changed before publication",
            )
        final_copied_directories = {
            relative
            for relative in final_directories
            if relative != _STAGE_METADATA_DIR
            and not relative.startswith(metadata_prefix)
        }
        metadata_directories = {
            relative
            for relative in final_directories
            if relative == _STAGE_METADATA_DIR
            or relative.startswith(metadata_prefix)
        }
        if metadata_directories != {_STAGE_METADATA_DIR}:
            raise ProjectCopyVerificationError(
                "generated_metadata_directory_drift",
                "Generated staging metadata directories changed before publication",
            )
        _assert_copy_equal(source_files_before, final_copied_files)
        if final_copied_directories != source_directories_before:
            raise ProjectCopyVerificationError(
                "copy_directory_drift_before_publish",
                "Copied directory population changed before publication",
            )

        if _path_lexists(destination_root):
            raise ProjectPublicationError(
                "destination_race",
                f"Destination appeared during staging: {destination_root}",
            )
        _publish_directory_noreplace(temp_root, destination_root)
        published = True
        temp_root = None
        try:
            published_files, published_fingerprint, published_total = _tree_snapshot(
                destination_root
            )
            published_directories = _directory_population(destination_root)
            if (
                published_files != final_files
                or published_fingerprint != prepared_fingerprint
                or published_total != prepared_total
                or published_directories != final_directories
            ):
                raise ProjectPublicationError(
                    "published_fingerprint_mismatch",
                    "Published project differs from the verified pre-publication tree",
                    publication_outcome="committed",
                )
        except ProjectPublicationError:
            raise
        except Exception as exc:
            raise ProjectPublicationError(
                "published_verification_failed",
                "Project publication committed but post-publication verification failed",
                publication_outcome="committed",
            ) from exc
        try:
            _fsync_path(
                destination_parent,
                directory=True,
                raise_on_error=False,
            )
            logger.info(
                "Project stage %s published %s: files=%d bytes=%d source=%s copy=%s "
                "readiness=%s states=%s",
                operation_id,
                source_project.name,
                len(source_files_before),
                copied_bytes,
                source_before[:12],
                copied_fingerprint[:12],
                readiness,
                state_counts,
            )
        except Exception:
            logger.exception(
                "Project stage %s published but post-publication logging failed",
                operation_id,
            )
        return StageProjectResult(
            source_project_file=source_project,
            destination_project_file=destination_project,
            destination_root=destination_root,
            source_fingerprint_before=source_before,
            source_fingerprint_after=source_after,
            copied_fingerprint=copied_fingerprint,
            published_fingerprint=published_fingerprint,
            copied_file_count=len(source_files_before),
            copied_bytes=copied_bytes,
            publication_state="published",
            execution_readiness=readiness,
            assets=final_assets,
            ras_object=final_ras,
            fingerprint_algorithm=STAGE_PROJECT_TREE_FINGERPRINT_ALGORITHM,
        )
    except Exception as stage_error:
        publication_outcome = getattr(
            stage_error,
            "publication_outcome",
            "not_committed",
        )
        if not published and publication_outcome != "unknown":
            try:
                removed = _safe_remove_owned_temp(
                    temp_root,
                    destination_parent,
                    operation_id,
                )
            except Exception as cleanup_error:
                raise ProjectStageError(
                    "owned_temp_cleanup_failed",
                    f"Staging failed and cleanup could not remove: {temp_root}",
                ) from cleanup_error
            if not removed:
                raise ProjectStageError(
                    "owned_temp_cleanup_refused",
                    f"Staging failed and the unverified temporary path was retained: {temp_root}",
                ) from stage_error
        if isinstance(stage_error, ProjectStageError):
            raise
        if isinstance(stage_error, OSError):
            if published:
                raise ProjectPublicationError(
                    "published_filesystem_error",
                    "Project publication committed before a filesystem operation failed",
                    publication_outcome="committed",
                ) from stage_error
            raise ProjectStageError(
                "staging_filesystem_error",
                "A filesystem operation failed before project publication",
            ) from stage_error
        raise
    finally:
        if lock_handle is not None:
            try:
                os.close(lock_handle)
            except OSError:
                logger.exception("Could not close staging lock handle")
        _safe_remove_owned_lock(lock_path, lock_identity, lock_token)

StageProjectResult dataclass

Evidence returned after a project tree is atomically published.

fingerprint_algorithm identifies the namespace shared by source_fingerprint_before, source_fingerprint_after, copied_fingerprint, and published_fingerprint. These framed tree digests are not qualification snapshot content fingerprints.

Source code in ras_commander/RasProject.py
Python
@dataclass(frozen=True)
class StageProjectResult:
    """Evidence returned after a project tree is atomically published.

    ``fingerprint_algorithm`` identifies the namespace shared by
    ``source_fingerprint_before``, ``source_fingerprint_after``,
    ``copied_fingerprint``, and ``published_fingerprint``. These framed tree
    digests are not qualification snapshot content fingerprints.
    """

    source_project_file: Path
    destination_project_file: Path
    destination_root: Path
    source_fingerprint_before: str
    source_fingerprint_after: str
    copied_fingerprint: str
    published_fingerprint: str
    copied_file_count: int
    copied_bytes: int
    publication_state: Literal["published"]
    execution_readiness: Literal["ready", "not_ready", "unknown"]
    assets: pd.DataFrame
    ras_object: RasPrj
    fingerprint_algorithm: str = STAGE_PROJECT_TREE_FINGERPRINT_ALGORITHM

    def __post_init__(self) -> None:
        if self.fingerprint_algorithm != STAGE_PROJECT_TREE_FINGERPRINT_ALGORITHM:
            raise ValueError(
                "fingerprint_algorithm must identify the stage_project framed "
                f"tree contract: {STAGE_PROJECT_TREE_FINGERPRINT_ALGORITHM!r}"
            )

Exact boundary-block deletion

RasUnsteady.delete_boundary() intentionally requires an atomically staged project. First inspect the staged unsteady file, select one unique row, and pass back all of its exact evidence. Preview is the default and does not write.

Python
from ras_commander import RasUnsteady, stage_project

staged = stage_project(
    r"C:\Models\Source\Model.prj",
    r"D:\Runs\model-boundary-edit",
)
blocks = RasUnsteady.inspect_boundary_blocks(staged, unsteady_number="01")

candidate = blocks.loc[
    (blocks["bc_type"] == "Lateral Inflow Hydrograph")
    & (blocks["river"] == "River A")
    & (blocks["reach"] == "Reach 1")
    & (blocks["river_station"] == "1200")
]
if len(candidate) != 1:
    raise RuntimeError(f"Expected one exact boundary, found {len(candidate)}")
row = candidate.iloc[0]

evidence = {
    "unsteady_number": str(row["unsteady_number"]),
    "boundary_id": str(row["boundary_id"]),
    "expected_source_sha256": str(row["owner_sha256"]),
    "expected_block_sha256": str(row["block_sha256"]),
    "expected_bc_type": str(row["bc_type"]),
    "expected_location_raw": str(row["boundary_location_raw"]),
}
preview = RasUnsteady.delete_boundary(staged, **evidence)
assert preview.state == "previewed"

applied = RasUnsteady.delete_boundary(staged, **evidence, dry_run=False)
assert applied.state == "applied"

The operation is generic across recognized 1D and 2D boundary types; it does not encode a protected-type policy. It rejects direct paths, partial or index-only selectors, ambiguous encodings/types, reparse points, stale file or block evidence, and non-local apply targets. Apply performs one verified byte splice, CRLF newline serialization, and atomic replacement without creating a .bak file. Retained content and encoding are preserved apart from newline normalization; source selectors remain bound to the original bytes. Any mutation invalidates the stage snapshot, so another edit requires a fresh stage and inventory. If an exception exposes mutation_applied=True, the replacement committed before a later verification/refresh failure and the stage must be treated as requiring manual review.

Plan Execution

RasCmdr

Static class for HEC-RAS plan execution operations.

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

Methods:

Name Description
compute_plan

Execute a single HEC-RAS plan

compute_parallel

Execute multiple plans in parallel using worker folders

compute_test_mode

Execute multiple plans sequentially in a test folder

cancel_plan staticmethod

Python
cancel_plan(plan_number: Union[str, Number], ras_object=None, timeout_seconds: float = 10.0) -> bool

Stop only the active Windows process tree for one project plan.

Process matching is deliberately strict: a Ras.exe launcher must contain both the initialized project path and resolved plan path, or the exact project-only project.prj -c signature with an unambiguous matching Current Plan declaration. A steady solver must contain the exact project .rNN file. An unsteady solver must contain either the exact plan .tmp.hdf path or the jointly exact project directory, .cNN computation file, and complete bNN plan marker used by native launches. Unrelated RAS sessions are never selected by executable name alone.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

Plan number to cancel (for example, "01").

required
ras_object RasPrj

Initialized :class:RasPrj object. Uses the global project when omitted.

None
timeout_seconds float

Grace period before force-killing only the already matched processes.

10.0

Returns:

Type Description
bool

True when a matching process tree was found and stopped;

bool

False when no matching active process existed.

cancel_plan_exact staticmethod

Python
cancel_plan_exact(plan_number: Union[str, Number], ras_object=None, timeout_seconds: float = 10.0) -> PlanCancellationResult

Stop only one exact plan process tree and prove final quiescence.

The result is deliberately tri-state: quiescence_confirmed=True proves all matched identities stopped and a complete final scan found no exact plan process; False reports a known survivor; None reports query uncertainty. The structured result cannot be coerced to bool. cancellation_attempted records whether a terminate or kill method was invoked; matched_count records initial exact matches.

compute_parallel staticmethod

Python
compute_parallel(plan_number: Union[str, Number, List[Union[str, Number]], None] = None, max_workers: int = 2, num_cores: int = 2, clear_geompre: bool = False, force_geompre: bool = False, force_rerun: bool = False, ras_object: Optional[RasPrj] = None, dest_folder: Union[str, Path, None] = None, overwrite_dest: bool = False, skip_existing: bool = False, verify: bool = False, max_runtime: Optional[float] = None) -> ComputeParallelResult

Execute multiple HEC-RAS plans in parallel using multiple worker instances.

This method creates separate worker folders for each parallel process, runs plans in those folders, and then consolidates results to a final destination folder. It's ideal for running independent plans simultaneously to make better use of system resources.

Destination publication is fail closed. A cooperative destination lock and complete, globally empty HEC-RAS process inventory are required for the whole promotion batch. Each successful plan is then published as a recoverable transaction: every source is first copied and verified under a hidden destination stage, existing recognized result/message/geometry artifacts are quarantined, and the same-run set is committed before finalization. A provable failure restores the exact prior destination state; otherwise the transaction backups and worker folder are retained and later publication is refused. The corresponding paths and failure evidence are available in execution_details_by_plan.

Parameters:

Name Type Description Default
plan_number Union[str, List[str], None]

Plan number(s) to compute. If None, all plans in the project are computed. If string, only that plan will be computed. If list, all specified plans will be computed. Recommended to use two-digit strings for plan numbers for consistency (e.g., "01" instead of 1).

None
max_workers int

Maximum number of parallel workers (separate HEC-RAS instances). Each worker gets a separate folder with a copy of the project. Optimal value depends on CPU cores and memory available. A good starting point is: max_workers = floor(physical_cores / num_cores).

2
num_cores int

Number of cores to use per plan computation. Controls computational resources allocated to each individual HEC-RAS instance. For parallel execution, 2-4 cores per worker often provides the best balance.

2
clear_geompre bool

Whether to clear geometry preprocessor files (.c## files) before computation. Set to True when geometry has been modified to force recomputation.

False
force_geompre bool

Force full geometry reprocessing. Defaults to False. Clears the cached preprocessor tables inside each plan's .g##.hdf (in place, preserving the land cover / terrain association) and the .c## files, then rebuilds the tables via RasProcess.exe. Best effort: if RasProcess.exe is unavailable the cleared tables are re-derived by the solver during the run. Implies force_rerun for each plan, since the currency check cannot detect changes to the cached .g##.hdf or to the land cover sidecars that feed it.

False
force_rerun bool

Force execution even if results are current. Defaults to False. When False (default), checks file modification times and skips if results are current.

False
ras_object Optional[RasPrj]

RAS project object. If None, uses global 'ras' instance. Useful when working with multiple projects simultaneously.

None
dest_folder Union[str, Path, None]

Destination folder for computed results. If None, results are consolidated back to the original project folder. If string, creates folder in the project's parent directory. If Path, uses the exact path provided. Worker folders and the destination are re-initialized against the source project's .prj file name, so multi-project folders stay on the same project.

None
overwrite_dest bool

Whether to overwrite existing destination folder. Set to True to replace an existing destination folder with the same name.

False
skip_existing bool

If True, skip computation for plans whose selected engine result family already verifies. Defaults to False. Skipped plans are marked as successful (True) in results. Checked on source folder.

False
verify bool

If True, verify each selected result family after execution. Defaults to False. Plans that fail verification are marked False in results.

False

Returns:

Type Description
ComputeParallelResult

Result object backward compatible with Dict[str, bool]. execution_results: Dict of plan numbers to success booleans. results_df: DataFrame with results_df rows for executed plans. execution_details_by_plan: JSON-safe execution details keyed by plan number, or an empty object when unavailable. Existing code like for plan, ok in results.items(): still works. When skip_existing=True, skipped plans return True. When verify=True, plans failing verification return False.

Raises:

Type Description
ValueError

If the destination folder already exists, is not empty, and overwrite_dest is False.

FileNotFoundError

If project files cannot be found.

PermissionError

If there are issues accessing or writing to folders.

RuntimeError

If worker initialization fails.

Examples:

Run all plans in parallel with default settings

RasCmdr.compute_parallel()

Run all plans with 4 workers, 2 cores per worker

RasCmdr.compute_parallel(max_workers=4, num_cores=2)

Run specific plans in parallel

RasCmdr.compute_parallel(plan_number=["01", "03"], max_workers=2)

Resume interrupted parallel run - skip already completed plans

RasCmdr.compute_parallel(skip_existing=True)

Run with verification of successful completion

RasCmdr.compute_parallel(verify=True)

Run all plans with dynamic worker allocation based on system resources

import psutil physical_cores = psutil.cpu_count(logical=False) cores_per_worker = 2 max_workers = max(1, physical_cores // cores_per_worker) RasCmdr.compute_parallel(max_workers=max_workers, num_cores=cores_per_worker)

Run all plans in a specific destination folder

RasCmdr.compute_parallel(dest_folder="parallel_results", overwrite_dest=True)

Notes
  • Worker Assignment: Plans are assigned to workers in a round-robin fashion. For example, with 3 workers and 5 plans, assignment would be: Worker 1: Plans 1 & 4, Worker 2: Plans 2 & 5, Worker 3: Plan 3.

  • Resource Management: Each HEC-RAS instance (worker) typically requires:

    • 2-4 GB of RAM
    • 2-4 cores for optimal performance
  • When to use parallel vs. sequential:

    • Parallel: For independent plans, faster overall completion
    • Sequential: For dependent plans, consistent resource usage, easier debugging
  • The function creates worker folders during execution and consolidates results to the destination folder upon completion.

  • Promotion is an all-or-none safety gate for the successful candidate plans. Before copying any plan or shared geometry artifact, ras-commander holds a cooperative destination lock and requires a complete, globally empty strict HEC-RAS process inventory. A refusal marks every candidate unsuccessful and retains each computed worker folder; its exact recovery path and gate evidence are recorded in execution_details_by_plan. The lock coordinates ras-commander promotions, but an external GUI or process can still start after the inventory snapshot. Do not run HEC-RAS manually against the destination during promotion.

  • Missing worker results, rejected/failed artifact copies, and finalization errors also retain the affected worker folder and mark unpromoted plans unsuccessful with exact failure evidence. Supporting artifacts are copied before the primary result. If a later step fails, promotion_failure records whether partial promotion is possible and lists every copied destination path.

  • This function updates the RAS object's dataframes (plan_df, geom_df, etc.) after execution.

  • skip_existing checks the SOURCE folder before creating workers. Plans with existing results are not assigned to workers at all.

  • verify is passed through to compute_plan() for each worker execution.

  • max_runtime bounds each plan's engine execution in seconds using compute_plan's monotonic deadline and exact cancellation. It starts when the engine launches, excluding worker setup and preprocessing. None preserves existing execution limits. Each worker executes its assigned plans sequentially. Uncertain cancellation blocks reuse and retains that worker's artifacts instead of publishing them.

compute_plan staticmethod

Python
compute_plan(plan_number: Union[str, Number, Path], dest_folder=None, ras_object=None, clear_geompre=False, force_geompre: bool = False, force_rerun: bool = False, num_cores=None, overwrite_dest=False, skip_existing: bool = False, verify: bool = False, stream_callback: Optional[Callable] = None, use_optimal_hdf_settings: bool = False, hdf_settings_profile: str = 'balanced', hdf_additional_variables: Optional[List[str]] = None, hdf_output_variables: Optional[List[str]] = None, hdf_output_options: Optional[Dict[str, Any]] = None, hdf_output_profile: Optional[str] = None, dialog_watchdog: bool = True, max_runtime: Optional[float] = None, disable_omp_affinity: bool = False) -> ComputeResult

Execute a single HEC-RAS plan in a specified location.

This function runs a HEC-RAS plan by launching the HEC-RAS executable through command line, allowing for destination folder specification, core count control, and geometry preprocessor management.

Parameters:

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

The plan number to execute (e.g., "01", 1, 1.0) or the full path to the plan file. Recommended to use two-digit strings for plan numbers for consistency (e.g., "01" instead of 1).

required
dest_folder (str, Path)

Name of the folder or full path for computation. If a string is provided, it will be created in the same parent directory as the project folder. If a full path is provided, it will be used as is. If None, computation occurs in the original project folder, modifying the original project. The copy is re-initialized against the same .prj file name as the source project, so a project folder holding several projects (several .prj files) computes the project that ras_object points to rather than the first .prj found.

None
ras_object RasPrj

Specific RAS object to use. If None, uses the global ras instance. Useful when working with multiple projects simultaneously.

None
clear_geompre bool

Whether to clear geometry preprocessor files (.c## files). Defaults to False. Set to True when geometry has been modified to force recomputation of preprocessor files.

False
force_geompre bool

Force full geometry reprocessing. Defaults to False. Clears .c## files and requests native complete-geometry processing via RasProcess.exe before running the plan. The geometry HDF is preserved: ras-commander does not selectively delete solver-owned datasets, and the land-cover and terrain associations remain intact. Implies force_rerun: the currency check compares only .p##/.g##/.u## mtimes against the results HDF, so it cannot detect changes to land-cover sidecars. Skipping would silently drop the reprocessing request. The RasProcess.exe request is best effort; if unavailable, the plan still runs after .c## clearing.

False
force_rerun bool

Force execution even if results are current. Defaults to False. When False (default), checks file modification times and skips if results are current. When True, always executes regardless of result currency.

False
num_cores int

Number of cores to use for the plan execution. If None, the current setting in the plan file is not changed. Generally, 2-4 cores provides good performance for most models.

None
overwrite_dest bool

If True, overwrite the destination folder if it exists. Defaults to False. Set to True to replace an existing destination folder with the same name.

False
skip_existing bool

If True, skip computation when the selected engine's sole result family already verifies. Modern HDF uses Complete Process; legacy execution requires its .O## output and checks available messages for errors. Defaults to False. Useful for resuming interrupted batch runs or incremental workflows.

False
verify bool

If True, verify the selected result family after execution. Defaults to False. Returns False if verification fails even if subprocess returned success.

False
stream_callback Callable

Callback object for real-time execution progress monitoring. Must implement ExecutionCallback protocol methods (all methods optional): - on_prep_start(plan_number): Called before geometry preprocessing - on_prep_complete(plan_number): Called after preprocessing - on_exec_start(plan_number, command): Called when HEC-RAS subprocess starts - on_exec_launched(plan_number, launch_details): Optional duck-typed hook called after exact launcher identity and executable provenance are captured. This additive hook is intentionally not part of the exported callback protocol. - on_exec_message(plan_number, message): Called for each .bco file message (real-time) - on_exec_complete(plan_number, success, duration): Called when execution finishes - on_verify_result(plan_number, verified): Called after verification (if verify=True) IMPORTANT: Must be thread-safe when used with compute_parallel(). See ras_commander.callbacks for example implementations.

None
use_optimal_hdf_settings bool

If True, apply ras-commander's recommended HDF write settings to the plan before currency checks and execution. Defaults to False.

False
hdf_settings_profile str

HDF settings profile to apply when use_optimal_hdf_settings=True. Options are "balanced", "speed", "size", and "nas". Defaults to "balanced".

'balanced'
hdf_additional_variables List[str]

Additional HDF output variables to enable when use_optimal_hdf_settings=True. Baseline 2D result names "Water Surface" and "Face Velocity" are accepted no-ops: they are always written for computed 2D results and add no plan line.

None
hdf_output_variables List[str]

Additional HDF output variables to enable before execution. The same baseline-name no-op policy applies; existing baseline-name lines are preserved. Unknown labels raise. Version-limited labels (HEC-RAS 7.0 secondary-flow outputs) are gated on the executing HEC-RAS version when it is newer than the plan's declared Program Version (for example a 6.x-declared plan run with 7.0.1); otherwise the declared-version gate applies. Same for hdf_additional_variables.

None
hdf_output_options Dict[str, Any]

Explicit HDF output options passed to RasPlan.set_hdf_output_options() before execution.

None
hdf_output_profile str

Named HDF output profile to apply before execution. Equivalent to use_optimal_hdf_settings=True with a profile.

None
max_runtime float

Maximum elapsed execution time in seconds, measured against one monotonic deadline spanning the direct launcher wait, callback monitoring, and asynchronous solver completion. Values above 4,294,967.294 seconds are rejected because the Windows subprocess wait cannot represent them. None adds no caller-wide deadline and preserves the historical launcher/callback behavior plus the existing 7,200-second asynchronous-solver bound. A timeout uses exact-plan structured cancellation.

None
disable_omp_affinity bool

Set Intel KMP_AFFINITY=disabled only in the launched engine environment. Defaults to False. Useful when Wine lacks NUMA/affinity APIs used by Intel OpenMP. This preserves the scheduler CPU allocation and plan core count.

False

Returns: ComputeResult: Result object with success bool and results_df_row (pd.Series or None). Backward compatible with bool: if RasCmdr.compute_plan("01"): still works. Access execution metrics via result.results_df_row (e.g., runtime, volume accounting). results_df_row is None when dest_folder is used, execution fails, or extraction errors. When skip_existing=True and results exist, returns ComputeResult(success=True). completion_verified is None unless verify=True. execution_details is always JSON-safe and distinguishes selected executable identity, calculation attempts, launcher PID/create-time identity, solver quiescence, and result-family finalization, including exact preparation and finalization cleanup records. In those records, result_format names the family targeted for deletion. Calculated success requires every terminal gate.

Raises:

Type Description
TypeError

If disable_omp_affinity is not a bool.

ValueError

If max_runtime is not a positive finite number within the Windows subprocess-wait range, or None.

Setup, launch, verification, and filesystem failures that occur after runtime validation are represented by ComputeResult(success=False) and its structured execution_details rather than propagated.

Examples:

Run a plan in the original project folder

RasCmdr.compute_plan("01")

Run a plan in a separate folder

RasCmdr.compute_plan("01", dest_folder="computation_folder")

Run a plan with a specific number of cores

RasCmdr.compute_plan("01", num_cores=4)

Run a plan in a specific folder, overwriting if it exists

RasCmdr.compute_plan("01", dest_folder="computation_folder", overwrite_dest=True)

Skip computation if results already exist

RasCmdr.compute_plan("01", skip_existing=True)

Run with verification of successful completion

RasCmdr.compute_plan("01", verify=True)

Run with real-time progress monitoring

from ras_commander.callbacks import ConsoleCallback callback = ConsoleCallback() RasCmdr.compute_plan("01", stream_callback=callback)

RasCmdr.compute_plan("01", use_optimal_hdf_settings=True)

Run a plan in a specific folder with multiple options

RasCmdr.compute_plan( "01", dest_folder="computation_folder", num_cores=2, clear_geompre=True, overwrite_dest=True, verify=True )

Notes
  • For executing multiple plans, consider using compute_parallel() or compute_test_mode().
  • Setting num_cores appropriately is important for performance:
    • 1-2 cores: Highest efficiency per core, good for small models
    • 3-8 cores: Good balance for most models
    • 8 cores: May have diminishing returns due to overhead

  • This function updates the RAS object's dataframes (plan_df, geom_df, etc.) after execution.
  • When skip_existing=True with dest_folder, the check happens AFTER copying to destination.
  • Verification is version-aware: modern plans inspect HDF completion; legacy plans require a fresh .O## and inspect available stored messages for errors.
  • Execution failures are returned as ComputeResult(success=False) with structured failure evidence.
  • Actual runs permanently remove the opposing result family and stale compute-message sidecars before launch, then remove any opposing result recreated by HEC-RAS after completion. Skipped runs do not mutate execution artifacts.
  • Exact-plan cancellation and final evidence collection happen after the engine deadline when necessary, so wall-clock return time can exceed max_runtime while ras-commander proves a safe terminal state.
  • Unpatched HEC-RAS 7.0.2 temporarily receives a project declaration containing only this plan because its launcher runs every listed plan. The original project is restored after owned processes stop. An unproved stop retains the single-plan file and original backup; inspect execution_details["single_plan_project"]. An exact recognized local CLI patch bypasses this transaction; see the single-plan execution guide for its SHA-256 and scope.

compute_plan_linux staticmethod

Python
compute_plan_linux(plan_number: Union[str, Number], ras_exe_dir: Union[str, Path], ras_object=None, timeout_sec: int = 14400, dos2unix: bool = True, num_cores: int = None, retry: bool = True, retry_delay_sec: int = 30) -> ComputeResult

Execute a HEC-RAS plan using the native Linux RasUnsteady binary.

Attribution: Execution pattern derived from ras-agent (https://github.com/gheistand/ras-agent) by Glenn Heistand / CHAMP — Illinois State Water Survey. See runner.py:run_job() for the original Linux RasUnsteady invocation pattern (subprocess, LD_LIBRARY_PATH, .tmp.hdf preparation, retry logic).

This is Phase 2 of a two-phase Linux execution workflow:

Phase 1 (Windows): Preprocess the plan on Windows to generate .tmp.hdf, .b##, and .x## files. Use RasPreprocess.preprocess_plan() to automate this step, or manually run HEC-RAS on Windows and kill after "Starting Unsteady Flow Computations" appears in the .bco log.

Phase 2 (Linux — this method): Execute the preprocessed plan using the native RasUnsteady binary.

Prerequisites (must exist in project folder before calling): - {project}.p{plan_num}.tmp.hdf — preprocessed plan HDF - {project}.b{plan_num} — boundary conditions file - {project}.x{geom_num} — cross-section preprocessor file - {project}.c{geom_num} — non-empty computed-geometry file (releases before 6.3.1 only; see "Solver argument convention")

Supported native Linux install (library) layouts, auto-detected from ras_exe_dir:

  • canonical (6.1, 6.3.1-7.x) — RasUnsteady in ras_exe_dir with a libs/ tree (libs/, libs/mkl/, libs/rhel_8/) beside it, in its parent, or — for HEC's 6.1 RAS_Linux_test_setup/Ras_v61/Release layout — two levels up. When both libs/rhel_8 and libs/centos_7 exist only rhel_8 is used, matching HEC's run_unsteady.sh.
  • bin_ras (5.0.7) — bin_ras/rasUnsteady64 with libraries colocated in bin_ras/ (no libs/ tree). (CLB-886)

Solver argument convention (independent of the library layout), selected from the plan *.tmp.hdf root File Version attribute (e.g. 'HEC-RAS 6.1 ...'), falling back to the install layout (bin_ras → cfile, otherwise tmphdf) when the attribute is absent or unreadable:

  • cfile — releases before 6.3.1 (5.0.7, 6.1; 6.2/6.3 are treated the same): <engine> {proj}.c{geom} b{plan} with cwd = project folder. The non-empty .c{geom} file is required, and the compiled-HDF core attributes are not rewritten (OMP_NUM_THREADS/MKL_NUM_THREADS still carry num_cores).
  • tmphdf — 6.3.1 and later: RasUnsteady {proj}.p{plan}.tmp.hdf x{geom}.

A bin_ras (5.0.7) engine refuses a tmp.hdf whose File Version is 6.3.1 or later. Both conventions write results into the tmp.hdf, which is then promoted to {proj}.p{plan}.hdf.

Detection and binary resolution mirror :meth:RasUtils._scan_native_linux_ras (root RasUnsteady → bin_ras/{rasUnsteady64,RasUnsteady,rasUnsteady}).

The Linux RasUnsteady binary uses Fortran I/O conventions that require files to be accessible with a base name of "io" (e.g., io.b, io.X). This method creates temporary symlinks to satisfy this requirement.

On a Windows host, the WSL adapter fails before solver launch unless Bash, setsid --wait, /proc identity, durable sync, and process- group signalling are available. It atomically acquires a per-plan lease, launches the solver as a session/process-group leader, and publishes the lease token, its Linux PID, /proc start time, and process-group ID before exec. Timeout or Python interruption starts a separate WSL recovery command that revalidates that exact identity before TERM/KILL and then proves the group empty. Opposing result families are deliberately not precleaned or finalized until quiescence is positive. Uncertain recovery preserves all outputs and the lease so a duplicate execution fails closed.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

Plan number to execute (e.g., "01").

required
ras_exe_dir Union[str, Path]

HEC-RAS Linux install directory. For the canonical layout this holds RasUnsteady (with libs/ beside it, in its parent, or two levels up for HEC's 6.1 distribution); for the 5.0.7 layout it holds bin_ras/rasUnsteady64 + its libraries.

required
ras_object RasPrj

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

None
timeout_sec int

Maximum execution time in seconds (default 14400 = 4 hours).

14400
dos2unix bool

Convert CRLF→LF in text files before execution (default True).

True
num_cores int

Number of cores. If specified, updates the plan file, sets OMP/MKL threads and, for 6.3.1+ (tmphdf) releases, the compiled *.tmp.hdf core attributes.

None
retry bool

Retry once on failure after retry_delay_sec (default True).

True
retry_delay_sec int

Seconds to wait before retry (default 30).

30

Returns:

Type Description
ComputeResult

Result object with success bool and results_df_row.

Raises:

Type Description
FileNotFoundError

If the RasUnsteady binary, .tmp.hdf, .b, or .x files are missing, or (pre-6.3.1 releases) the .c file is missing or empty.

ValueError

If a bin_ras (5.0.7) engine is given a 6.3.1+ tmp.hdf.

Example

Phase 1: Preprocess on Windows (generates .tmp.hdf, .b, .x)

Phase 2: Execute on Linux

from ras_commander import init_ras_project, RasCmdr init_ras_project("/home/user/model") result = RasCmdr.compute_plan_linux( ... "01", ras_exe_dir="/opt/hecras/6.7-beta5" ... )

compute_test_mode staticmethod

Python
compute_test_mode(plan_number: Union[str, Number, List[Union[str, Number]], None] = None, dest_folder_suffix='[Test]', clear_geompre=False, force_geompre: bool = False, force_rerun: bool = False, num_cores=None, ras_object=None, overwrite_dest=False, skip_existing: bool = False, verify: bool = False) -> ComputeParallelResult

Execute HEC-RAS plans sequentially in a separate test folder.

This function creates a separate test folder, copies the project there, and executes the specified plans in sequential order. It's useful for batch processing plans that need to be run in a specific order or when you want to ensure consistent resource usage.

Result publication uses the same fail-closed global process gate, cooperative destination lock, and per-plan staged transaction as compute_parallel. On refusal or failure, the fresh test folder is retained and its exact recovery path is recorded in execution_details_by_plan. If exact destination rollback cannot be proved, later plan publication is refused and the hidden transaction backups remain available for recovery.

Parameters:

Name Type Description Default
plan_number Union[str, Number, List[Union[str, Number]], None]

Plan number or list of plan numbers to execute (e.g., "01", 1, 1.0, or ["01", 2]). If None, all plans will be executed. Default is None. Recommended to use two-digit strings for plan numbers for consistency (e.g., "01" instead of 1).

None
dest_folder_suffix str

Suffix to append to the test folder name. Defaults to "[Test]". The test folder is always created in the project folder's parent directory.

'[Test]'
clear_geompre bool

Whether to clear geometry preprocessor files (.c## files). Defaults to False. Set to True when geometry has been modified to force recomputation.

False
force_geompre bool

Force full geometry reprocessing. Defaults to False. Clears the cached preprocessor tables inside each plan's .g##.hdf (in place, preserving the land cover / terrain association) and the .c## files, then rebuilds the tables via RasProcess.exe. Best effort: if RasProcess.exe is unavailable the cleared tables are re-derived by the solver during the run. Implies force_rerun for each plan, since the currency check cannot detect changes to the cached .g##.hdf or to the land cover sidecars that feed it.

False
force_rerun bool

Force execution even if results are current. Defaults to False. When False (default), checks file modification times and skips if results are current.

False
num_cores int

Number of cores to use for each plan. If None, the current setting in the plan file is not changed. Default is None. For sequential execution, 4-8 cores often provides good performance.

None
ras_object RasPrj

Specific RAS object to use. If None, uses the global ras instance. Useful when working with multiple projects simultaneously.

None
overwrite_dest bool

If True, overwrite the destination folder if it exists. Defaults to False. Set to True to replace an existing test folder with the same name.

False
skip_existing bool

If True, skip plans whose selected engine result family already verifies. Defaults to False. Skipped plans are marked as successful (True) in results. Check happens in test folder.

False
verify bool

If True, verify each selected result family after execution. Defaults to False. Plans that fail verification are marked False in results.

False

Returns:

Type Description
ComputeParallelResult

Result object backward compatible with Dict[str, bool]. execution_results: Dict of plan numbers to success booleans. results_df: DataFrame with results_df rows for executed plans. execution_details_by_plan: JSON-safe execution details keyed by plan number, or an empty object when unavailable. Existing code like for plan, ok in results.items(): still works. When skip_existing=True, skipped plans return True. When verify=True, plans failing verification return False.

Raises:

Type Description
ValueError

If the destination folder already exists, is not empty, and overwrite_dest is False.

FileNotFoundError

If project files cannot be found.

PermissionError

If there are issues accessing or writing to folders.

Examples:

Run all plans sequentially

RasCmdr.compute_test_mode()

Run a specific plan

RasCmdr.compute_test_mode(plan_number="01")

Run multiple specific plans

RasCmdr.compute_test_mode(plan_number=["01", "03", "05"])

Run plans with a custom folder suffix

RasCmdr.compute_test_mode(dest_folder_suffix="[SequentialRun]")

Run plans with a specific number of cores

RasCmdr.compute_test_mode(num_cores=4)

Resume interrupted test run - skip completed plans

RasCmdr.compute_test_mode(skip_existing=True)

Run with verification of successful completion

RasCmdr.compute_test_mode(verify=True)

Run specific plans with multiple options

RasCmdr.compute_test_mode( plan_number=["01", "02"], dest_folder_suffix="[SpecificSequential]", clear_geompre=True, num_cores=6, overwrite_dest=True, verify=True )

Notes
  • This function was created to replicate the original HEC-RAS command line -test flag, which does not work in recent versions of HEC-RAS.

  • Key differences from other compute functions:

    • compute_plan: Runs a single plan, with option for destination folder
    • compute_parallel: Runs multiple plans simultaneously in worker folders
    • compute_test_mode: Runs multiple plans sequentially in a single test folder
  • Use cases:

    • Running plans in a specific order
    • Ensuring consistent resource usage
    • Easier debugging (one plan at a time)
    • Isolated test environment
  • Performance considerations:

    • Sequential execution is generally slower overall than parallel execution
    • Each plan gets consistent resource usage
    • Execution time scales linearly with the number of plans
  • Promotion is all-or-none for the successful candidate plans. Before copying any plan or shared geometry artifact, ras-commander holds a cooperative destination lock and requires a complete, globally empty strict HEC-RAS process inventory. A refusal marks every candidate unsuccessful and retains the test folder; its exact recovery path and gate evidence are recorded in execution_details_by_plan. The lock coordinates ras-commander promotions, but cannot close the race with a manually launched HEC-RAS GUI/process after the process scan.

  • Missing results, rejected/failed copies, and finalization errors retain the test folder and record its exact path plus structured failure evidence. Supporting artifacts are copied before the primary result; any already copied paths are reported when a later failure makes partial promotion possible.

  • This function updates the RAS object's dataframes (plan_df, geom_df, etc.) after execution.

  • skip_existing checks the TEST folder after copying. This allows resuming interrupted test runs.

  • verify is passed through to compute_plan() for each plan execution.

inspect_execution_evidence staticmethod

Python
inspect_execution_evidence(plan_number: Union[str, Number, Path], *, ras_object=None, result_modified_after: Optional[datetime] = None, hash_files: bool = False) -> ExecutionEvidence

Inspect existing execution evidence without running HEC-RAS or COM.

The returned record keeps filesystem, HDF, stored-message, process, and COM observations distinct. It derives mechanical completion only; parsed errors and warnings remain independent health observations and hydraulic acceptance is deliberately outside this contract.

Parameters:

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

Plan number or an existing .p## plan path.

required
ras_object RasPrj

Explicit initialized :class:RasPrj. Uses the package global project only when omitted.

None
result_modified_after Optional[datetime]

Optional timezone-aware filesystem timestamp threshold. This is not a full RAS input-currency check.

None
hash_files bool

Stream-hash inspected source artifacts for provenance.

False

Returns:

Type Description
Immutable

class:ExecutionEvidence with a fixed observation

ExecutionEvidence

registry and JSON-serializable to_dict() representation.

Notes

This method is read-only. It does not execute or preprocess a plan, launch a COM controller, or evaluate hydraulic acceptability.

inspect_plan_processes staticmethod

Python
inspect_plan_processes(plan_number: Union[str, Number], ras_object=None) -> PlanProcessInventory

Return strict process evidence narrowed to one project plan.

Matching uses complete command-line tokens after Windows path normalization. A launcher must contain the exact project and plan paths. A steady solver must contain the exact project .rNN run file. An unsteady solver must contain either the exact plan .tmp.hdf path or the exact project working directory plus complete bNN plan token used by native unsteady launches. When the plan's geometry reference is readable, that form must also contain the exact project .cNN computation-file path. Basenames and substrings are never sufficient. The host-wide inventory also covers exact legacy and modern compute/preprocess names whose plan-specific command signature is not established.

preprocess_geometry_linux staticmethod

Python
preprocess_geometry_linux(plan_number: Union[str, Number], ras_exe_dir: Union[str, Path], ras_object=None, timeout_sec: int = 7200, dos2unix: bool = True) -> ComputeResult

Run the native Linux RasGeomPreprocess geometry preprocessor (CLB-885).

This regenerates the geometry preprocessor tables (1D cross-section property tables and 2D cell/face HTab property tables) inside an existing {project}.p{plan}.tmp.hdf, headlessly on Linux — mirroring :meth:compute_plan_linux (LD_LIBRARY_PATH auto-detect, dos2unix, output validation).

Scope / honest limitation: the native RasGeomPreprocess binary operates in place on an existing .tmp.hdf that already contains the raw /Geometry group. It does not build the .tmp.hdf skeleton (nor the .b##/.x## files) from raw .prj/.g##/.u## text — that initial assembly is still the Windows Phase-1 step. Use this to (re)compute geometry HTab tables on Linux after a geometry-only change, or to refresh /Geometry/GeomPreprocess before :meth:compute_plan_linux without round-tripping to Windows.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

Plan number whose .tmp.hdf to preprocess (e.g. "04").

required
ras_exe_dir Union[str, Path]

Directory containing the RasGeomPreprocess binary and sibling libs/ directory (e.g. /opt/hecras/6.6).

required
ras_object RasPrj

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

None
timeout_sec int

Maximum preprocessing time in seconds (default 7200).

7200
dos2unix bool

Convert CRLF->LF in text files first (default True).

True

Returns:

Type Description
ComputeResult

success True when the preprocessor finished and the

ComputeResult

.tmp.hdf contains a populated /Geometry/GeomPreprocess group.

Raises:

Type Description
FileNotFoundError

If the RasGeomPreprocess binary or the .tmp.hdf/.x## prerequisites are missing.

remove_plan_execution_artifacts staticmethod

Python
remove_plan_execution_artifacts(plan_number: Union[str, Number, Path], *, result_format: RemovalFormat, include_message_sidecars: bool = False, ras_object=None) -> PlanExecutionCleanup

Permanently remove exact result artifacts owned by one plan.

Parameters:

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

Plan number or existing .p## plan path.

required
result_format RemovalFormat

Required selection: "hdf", "legacy", or "both". This names the result family to remove.

required
include_message_sidecars bool

Also remove the plan's exact .comp_msgs.txt, .computeMsgs.txt, and .bco## files.

False
ras_object RasPrj

Explicit initialized :class:RasPrj. Uses the package global project only when omitted.

None

Returns:

Type Description
Immutable

class:PlanExecutionCleanup listing removed and

PlanExecutionCleanup

already-missing paths.

Warning

Removal is permanent. Geometry HDF, DSS, terrain, and Linux .tmp.hdf preprocessing files are never included.

Structured execution evidence

RasCmdr.inspect_execution_evidence() reads existing plan-result artifacts without executing HEC-RAS or opening COM. It keeps HDF attributes, embedded messages, stored message sidecars, legacy output files, process outcome, and COM outcome as separate observations. Mechanical completion does not imply hydraulic acceptance or an error-free computation.

result_modified_after, when provided, must be a timezone-aware datetime. result_artifact_structural_state narrowly reports whether the plan- information group is present; it does not claim that a readable HDF is a complete result. Embedded HDF messages take precedence for health parsing, with stored messages used as a fallback.

When HDF and .O## results coexist, selection follows the current plan-file Program Version= declaration. Unsafe combinations raise ResultArtifactAmbiguityError; the inspector never combines completion or runtime evidence from two result families. Use RasCmdr.remove_plan_execution_artifacts() for explicit, permanent, plan-scoped remediation, or rerun through ras-commander so the selected engine normalizes the artifacts. Actual runs clean before and after execution; skipped runs do not delete result artifacts. Cleanup requires a resolvable selected engine version and fails before mutation when that version is unknown. Worker and Docker promotion accepts only a successful plan's exact final result family; Linux preprocessing .tmp.hdf files are never published as results.

Batch promotion safety

compute_parallel() and compute_test_mode() treat destination promotion as one batch safety decision. Immediately before copying any plan result, message sidecar, or shared geometry HDF, ras-commander acquires an exact-create, tokenized destination lock and requires a complete, globally empty strict HEC-RAS process inventory. This intentionally blocks promotion when any recognized HEC-RAS launcher, solver, or preprocessor is active, even when it belongs to another plan: shared geometry makes plan-only occupancy checks insufficient.

If the lock is already held, process inspection is incomplete, or the strict inventory is nonempty, no candidate in the batch is promoted or finalized. Every otherwise successful candidate is returned as unsuccessful with the lock and process-gate evidence in execution_details_by_plan. Fresh outputs remain available for explicit review or recovery at the exact retained_worker_folder or retained_test_folder path recorded there.

The same recoverability rule applies after the gate succeeds. A missing primary result, any artifact copy that raises or returns False, or a finalization error marks the affected plan unsuccessful and retains its worker or test folder. Each candidate plan uses a destination-local publication transaction. Ras-commander first copies and hash-verifies the primary result, same-run message sidecars, and any selected shared geometry HDF under a unique hidden stage, without changing any recognized destination artifact. It then quarantines both result families, every known plan-message sidecar, and the shared geometry artifact being replaced. Only after that quarantine succeeds does it commit the fresh same-run set and run finalization.

If staging, commit, verification, or finalization fails, ras-commander first removes every fresh artifact from recognized names. It restores the complete prior primary-family set as one safety group, then restores supporting artifacts. If either group cannot be completed, every artifact restored so far is re-quarantined; this avoids exposing one primary family with an ambiguous or partial sidecar set. Hash verification must prove the exact prior destination state before the transaction is discarded. When that proof succeeds, rollback_confirmed is true and no partial publication remains. When it cannot be proved, later publication in that batch is refused, partial_promotion_possible is true, and the hidden transaction, backup paths, and fresh worker or test folder remain available for explicit recovery. This ordering prevents an old result primary from being paired with a message sidecar from the failed new run.

The lock prevents two cooperative ras-commander promotion batches from racing. It cannot prevent a person or unrelated program from launching HEC-RAS after the process snapshot, so do not open or compute the destination project in the GUI during promotion.

WSL solver supervision

On Windows, compute_plan_linux() uses a fail-closed WSL adapter. Before any solver launch it atomically acquires a per-plan lease and verifies that Bash, setsid --wait, /proc identity, durable sync, and process-group signalling are available. The solver runs as a session/process-group leader and publishes the lease token, its Linux PID, /proc start-time tick, and process-group ID before exec. Recovery rejects state that is not bound to the held lease.

On timeout or Python interruption, ras-commander kills only its Windows WSL launcher and invokes a separate WSL recovery command. Recovery sends TERM and, if needed, KILL only after the current /proc identity exactly matches the published PID, start time, and process group; it then waits for positive group absence. Identity mismatch, unavailable identity, or incomplete recovery is recorded as indeterminate and never authorizes a signal.

The WSL path deliberately does not remove an opposing result family before launch. It finalizes result artifacts only after exact solver quiescence is proved. If that proof or owned-state cleanup is uncertain, both visible result families and the per-plan lease are preserved, result validation/promotion and retry are refused, and a subsequent duplicate execution fails closed.

Structured process safety

RasControl.inspect_processes() returns a strict host-wide inventory of recognized HEC-RAS launchers, solvers, preprocessors, sediment, and water-quality engines. RasCmdr.inspect_plan_processes() narrows that evidence to one initialized project and plan using exact path/token signatures. Both records expose complete and explicit query errors; callers making safety decisions must fail closed when inspection is incomplete.

RasCmdr.cancel_plan_exact() revalidates process identity as (pid, create_time) before signalling and returns matched, stopped, survivor, query- error, timing, and tri-state quiescence evidence. Use this structured method for supervision and recovery. An incomplete exact-plan inventory is returned as indeterminate without sending any signal. The older Boolean cancel_plan() remains a compatibility wrapper: it returns True only when it found an exact match and quiescence was positively proved. Process creation, observation, and cancellation start/finish times are Unix epoch seconds.

ExecutionEvidence dataclass

Immutable, version-aware evidence for one HEC-RAS plan result.

Source code in ras_commander/ExecutionEvidence.py
Python
@dataclass(frozen=True)
class ExecutionEvidence:
    """Immutable, version-aware evidence for one HEC-RAS plan result."""

    schema_version: int
    evidence_id: str
    inspected_at: datetime
    project_file: Path
    plan_file: Path
    plan_number: str
    declared_program_version: Optional[str]
    mechanical_completion: EvidenceObservation[bool]
    observations: Mapping[ObservationName, EvidenceObservation[Any]]
    conflicts: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        if self.schema_version != 1:
            raise ValueError("Only execution evidence schema_version=1 is supported")
        if not self.evidence_id:
            raise ValueError("evidence_id must not be empty")
        if self.inspected_at.tzinfo is None:
            raise ValueError("inspected_at must be timezone-aware")
        if not re.fullmatch(r"\d{2}", self.plan_number):
            raise ValueError("plan_number must be a two-digit string")
        if self.mechanical_completion.channel != "derived":
            raise ValueError("mechanical_completion must use the derived channel")
        if (
            self.mechanical_completion.state == "available"
            and not isinstance(self.mechanical_completion.value, bool)
        ):
            raise TypeError("mechanical_completion must contain a bool")

        copied = dict(self.observations)
        actual_names = set(copied)
        expected_names = set(EXECUTION_OBSERVATION_NAMES)
        if actual_names != expected_names:
            missing = sorted(expected_names - actual_names)
            extra = sorted(actual_names - expected_names)
            raise ValueError(
                "execution observation registry mismatch: "
                f"missing={missing}, extra={extra}"
            )

        for name in EXECUTION_OBSERVATION_NAMES:
            observation = copied[name]
            if not isinstance(observation, EvidenceObservation):
                raise TypeError(f"Observation {name!r} has an invalid value")
            value_types, channels = _OBSERVATION_SPECS[name]
            if observation.channel not in channels:
                raise ValueError(
                    f"Observation {name!r} cannot use channel "
                    f"{observation.channel!r}"
                )
            value = observation.value
            if observation.state == "available":
                if int in value_types and isinstance(value, bool):
                    raise TypeError(
                        f"Observation {name!r} cannot use bool as an integer"
                    )
                if not isinstance(value, value_types):
                    raise TypeError(
                        f"Observation {name!r} requires "
                        f"{value_types}, got {type(value)}"
                    )

        object.__setattr__(self, "project_file", Path(self.project_file))
        object.__setattr__(self, "plan_file", Path(self.plan_file))
        object.__setattr__(self, "observations", MappingProxyType(copied))
        object.__setattr__(self, "conflicts", tuple(self.conflicts))

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-serializable evidence record without message text."""
        return {
            "schema_version": self.schema_version,
            "evidence_id": self.evidence_id,
            "inspected_at": self.inspected_at.isoformat(),
            "project_file": str(self.project_file),
            "plan_file": str(self.plan_file),
            "plan_number": self.plan_number,
            "declared_program_version": self.declared_program_version,
            "mechanical_completion": self.mechanical_completion.to_dict(),
            "observations": {
                name: self.observations[name].to_dict()
                for name in EXECUTION_OBSERVATION_NAMES
            },
            "conflicts": list(self.conflicts),
        }
to_dict
Python
to_dict() -> dict[str, Any]

Return a JSON-serializable evidence record without message text.

Source code in ras_commander/ExecutionEvidence.py
Python
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-serializable evidence record without message text."""
    return {
        "schema_version": self.schema_version,
        "evidence_id": self.evidence_id,
        "inspected_at": self.inspected_at.isoformat(),
        "project_file": str(self.project_file),
        "plan_file": str(self.plan_file),
        "plan_number": self.plan_number,
        "declared_program_version": self.declared_program_version,
        "mechanical_completion": self.mechanical_completion.to_dict(),
        "observations": {
            name: self.observations[name].to_dict()
            for name in EXECUTION_OBSERVATION_NAMES
        },
        "conflicts": list(self.conflicts),
    }

EvidenceObservation dataclass

Bases: Generic[T]

One typed execution observation with explicit state and provenance.

Source code in ras_commander/ExecutionEvidence.py
Python
@dataclass(frozen=True)
class EvidenceObservation(Generic[T]):
    """One typed execution observation with explicit state and provenance."""

    state: EvidenceState
    value: Optional[T]
    channel: EvidenceChannel
    source_locator: Optional[str]
    source_sha256: Optional[str]
    observed_program_version: Optional[str]
    inspected_at: datetime
    reason_code: Optional[str] = None
    detail: Optional[str] = None

    def __post_init__(self) -> None:
        if self.state not in EVIDENCE_STATES:
            raise ValueError(f"Unsupported evidence state: {self.state!r}")
        if self.channel not in EVIDENCE_CHANNELS:
            raise ValueError(f"Unsupported evidence channel: {self.channel!r}")
        if self.inspected_at.tzinfo is None:
            raise ValueError("inspected_at must be timezone-aware")
        if self.state == "available" and self.value is None:
            raise ValueError("available evidence must contain a value")
        if self.state != "available" and self.value is not None:
            raise ValueError(
                f"{self.state} evidence cannot contain a value"
            )
        if self.state != "available" and not self.reason_code:
            raise ValueError(
                f"{self.state} evidence must include a reason_code"
            )
        if self.source_sha256 is not None and not re.fullmatch(
            r"[0-9a-f]{64}", self.source_sha256
        ):
            raise ValueError("source_sha256 must be a lowercase SHA-256 digest")
        if self.detail is not None and len(self.detail) > 1000:
            raise ValueError("detail must not exceed 1000 characters")

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-serializable observation record."""
        return {
            "state": self.state,
            "value": _json_value(self.value),
            "channel": self.channel,
            "source_locator": self.source_locator,
            "source_sha256": self.source_sha256,
            "observed_program_version": self.observed_program_version,
            "inspected_at": self.inspected_at.isoformat(),
            "reason_code": self.reason_code,
            "detail": self.detail,
        }
to_dict
Python
to_dict() -> dict[str, Any]

Return a JSON-serializable observation record.

Source code in ras_commander/ExecutionEvidence.py
Python
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-serializable observation record."""
    return {
        "state": self.state,
        "value": _json_value(self.value),
        "channel": self.channel,
        "source_locator": self.source_locator,
        "source_sha256": self.source_sha256,
        "observed_program_version": self.observed_program_version,
        "inspected_at": self.inspected_at.isoformat(),
        "reason_code": self.reason_code,
        "detail": self.detail,
    }

PlanExecutionCleanup dataclass

Audit record returned after exact, permanent artifact removal.

Source code in ras_commander/ExecutionArtifacts.py
Python
@dataclass(frozen=True)
class PlanExecutionCleanup:
    """Audit record returned after exact, permanent artifact removal."""

    plan_number: str
    result_format: RemovalFormat
    include_message_sidecars: bool
    removed_paths: tuple[Path, ...]
    missing_paths: tuple[Path, ...]

    def to_dict(self) -> dict[str, object]:
        """Return a JSON-safe representation for execution audit records."""
        return {
            "plan_number": self.plan_number,
            "result_format": self.result_format,
            "include_message_sidecars": self.include_message_sidecars,
            "removed_paths": [str(path) for path in self.removed_paths],
            "missing_paths": [str(path) for path in self.missing_paths],
        }
to_dict
Python
to_dict() -> dict[str, object]

Return a JSON-safe representation for execution audit records.

Source code in ras_commander/ExecutionArtifacts.py
Python
def to_dict(self) -> dict[str, object]:
    """Return a JSON-safe representation for execution audit records."""
    return {
        "plan_number": self.plan_number,
        "result_format": self.result_format,
        "include_message_sidecars": self.include_message_sidecars,
        "removed_paths": [str(path) for path in self.removed_paths],
        "missing_paths": [str(path) for path in self.missing_paths],
    }

PlanExecutionCleanupError

Bases: RuntimeError

Raised when exact cleanup fails after reporting any partial removal.

Source code in ras_commander/ExecutionArtifacts.py
Python
class PlanExecutionCleanupError(RuntimeError):
    """Raised when exact cleanup fails after reporting any partial removal."""

    def __init__(
        self,
        *,
        cleanup: PlanExecutionCleanup,
        failed_path: Path,
        cause: BaseException,
    ) -> None:
        self.cleanup = cleanup
        self.failed_path = failed_path
        self.cause = cause
        super().__init__(
            f"Could not remove execution artifact {failed_path}: {cause}. "
            f"Already removed: {[str(path) for path in cleanup.removed_paths]}"
        )

ResultArtifactAmbiguityError

Bases: RuntimeError

Raised when coexisting result formats cannot be read safely.

Source code in ras_commander/ExecutionArtifacts.py
Python
class ResultArtifactAmbiguityError(RuntimeError):
    """Raised when coexisting result formats cannot be read safely."""

    def __init__(
        self,
        *,
        paths: PlanResultArtifactPaths,
        declared_program_version: Optional[str],
        expected_format: Optional[ResultFormat],
        reason_code: str,
        hdf_mtime_ns: Optional[int] = None,
        legacy_mtime_ns: Optional[int] = None,
        detail: Optional[str] = None,
    ) -> None:
        self.plan_number = paths.plan_number
        self.plan_file = paths.plan_file
        self.declared_program_version = declared_program_version
        self.expected_format = expected_format
        self.hdf_path = paths.hdf
        self.legacy_output_path = paths.legacy_output
        self.hdf_mtime_ns = hdf_mtime_ns
        self.legacy_mtime_ns = legacy_mtime_ns
        self.reason_code = reason_code
        self.detail = detail
        message = (
            f"Plan {paths.plan_number} has ambiguous result artifacts "
            f"({paths.hdf.name} and {paths.legacy_output.name}); "
            f"reason={reason_code}, declared_program_version="
            f"{declared_program_version or 'unresolved'}. Remove one format with "
            "RasCmdr.remove_plan_execution_artifacts(..., "
            "result_format='hdf' or 'legacy'), or rerun the plan with the "
            "selected HEC-RAS version through ras-commander."
        )
        if detail:
            message = f"{message} {detail}"
        super().__init__(message)

Real-Time Execution Monitoring (v0.88.0+)

The compute_plan() stream_callback parameter enables real-time progress monitoring during HEC-RAS execution. The execution capability and return table distinguishes the single-plan and batch entry points.

Python
from ras_commander import RasCmdr
from ras_commander.callbacks import ConsoleCallback

# Simple console monitoring
callback = ConsoleCallback(verbose=True)
RasCmdr.compute_plan("01", stream_callback=callback)

Output:

Text Only
[Plan 01] Starting execution...
[Plan 01] Geometry Preprocessor Version 6.6
[Plan 01] Computing Cross Section HTAB's
[Plan 01] Starting Unsteady Flow Computations
[Plan 01] Time: 01JAN2020 0600 [  1.25% Done]
[Plan 01] SUCCESS in 45.2s

Callback Lifecycle

Callbacks receive notifications at key execution points:

  1. on_prep_start(plan_number) - Before plan setup, including requested preprocessor-file clearing and core settings
  2. on_prep_complete(plan_number) - After plan setup; engine preprocessing may still be required
  3. on_exec_start(plan_number, command) - Immediately before launching the HEC-RAS subprocess
  4. on_exec_message(plan_number, message) - Each .bco file message (real-time)
  5. on_exec_complete(plan_number, success, duration) - After execution
  6. on_verify_result(plan_number, verified) - After HDF verification (if verify=True)
Built-in Callbacks
ConsoleCallback

Simple callback that prints execution progress to console.

This is the simplest possible callback implementation, suitable for: - Interactive sessions - Debugging - Quick scripts

Thread Safety

Uses print() with file argument for atomic writes. Safe for concurrent use in compute_parallel().

Example

from ras_commander import RasCmdr from ras_commander.callbacks import ConsoleCallback

callback = ConsoleCallback() RasCmdr.compute_plan("01", stream_callback=callback) [Plan 01] Starting execution... [Plan 01] Geometry Preprocessor Version 6.6 [Plan 01] SUCCESS in 45.2s

Source code in ras_commander/callbacks.py
Python
class ConsoleCallback:
    """
    Simple callback that prints execution progress to console.

    This is the simplest possible callback implementation, suitable for:
    - Interactive sessions
    - Debugging
    - Quick scripts

    Thread Safety:
        Uses print() with file argument for atomic writes.
        Safe for concurrent use in compute_parallel().

    Example:
        >>> from ras_commander import RasCmdr
        >>> from ras_commander.callbacks import ConsoleCallback
        >>>
        >>> callback = ConsoleCallback()
        >>> RasCmdr.compute_plan("01", stream_callback=callback)
        [Plan 01] Starting execution...
        [Plan 01] Geometry Preprocessor Version 6.6
        [Plan 01] SUCCESS in 45.2s
    """

    def __init__(self, verbose: bool = False, show_command: bool = False):
        """
        Initialize console callback.

        Args:
            verbose: If True, print all messages. If False, only print start/complete.
            show_command: If True, print the full command when execution starts.
                This may include full executable, project, and plan paths.
        """
        self.verbose = verbose
        self.show_command = show_command

    def on_exec_start(self, plan_number: str, command: str) -> None:
        """Print execution start message."""
        print(f"[Plan {plan_number}] Starting execution...", file=sys.stdout, flush=True)
        if self.show_command:
            print(f"[Plan {plan_number}] Command: {command}", file=sys.stdout, flush=True)

    def on_exec_message(self, plan_number: str, message: str) -> None:
        """Print execution messages (if verbose mode enabled)."""
        if self.verbose:
            print(f"[Plan {plan_number}] {message.strip()}", file=sys.stdout, flush=True)

    def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
        """Print execution completion message."""
        status = "SUCCESS" if success else "FAILED"
        print(f"[Plan {plan_number}] {status} in {duration:.1f}s", file=sys.stdout, flush=True)
__init__
Python
__init__(verbose: bool = False, show_command: bool = False)

Initialize console callback.

Parameters:

Name Type Description Default
verbose bool

If True, print all messages. If False, only print start/complete.

False
show_command bool

If True, print the full command when execution starts. This may include full executable, project, and plan paths.

False
Source code in ras_commander/callbacks.py
Python
def __init__(self, verbose: bool = False, show_command: bool = False):
    """
    Initialize console callback.

    Args:
        verbose: If True, print all messages. If False, only print start/complete.
        show_command: If True, print the full command when execution starts.
            This may include full executable, project, and plan paths.
    """
    self.verbose = verbose
    self.show_command = show_command
on_exec_start
Python
on_exec_start(plan_number: str, command: str) -> None

Print execution start message.

Source code in ras_commander/callbacks.py
Python
def on_exec_start(self, plan_number: str, command: str) -> None:
    """Print execution start message."""
    print(f"[Plan {plan_number}] Starting execution...", file=sys.stdout, flush=True)
    if self.show_command:
        print(f"[Plan {plan_number}] Command: {command}", file=sys.stdout, flush=True)
on_exec_message
Python
on_exec_message(plan_number: str, message: str) -> None

Print execution messages (if verbose mode enabled).

Source code in ras_commander/callbacks.py
Python
def on_exec_message(self, plan_number: str, message: str) -> None:
    """Print execution messages (if verbose mode enabled)."""
    if self.verbose:
        print(f"[Plan {plan_number}] {message.strip()}", file=sys.stdout, flush=True)
on_exec_complete
Python
on_exec_complete(plan_number: str, success: bool, duration: float) -> None

Print execution completion message.

Source code in ras_commander/callbacks.py
Python
def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
    """Print execution completion message."""
    status = "SUCCESS" if success else "FAILED"
    print(f"[Plan {plan_number}] {status} in {duration:.1f}s", file=sys.stdout, flush=True)
FileLoggerCallback

Callback that writes execution progress to per-plan log files.

Creates a separate log file for each plan, enabling: - Detailed execution logs - Post-execution analysis - Archival records

Thread Safety

Uses threading.Lock to ensure thread-safe file operations. Safe for concurrent use in compute_parallel().

Example

from pathlib import Path from ras_commander.callbacks import FileLoggerCallback

callback = FileLoggerCallback(output_dir=Path("logs")) RasCmdr.compute_plan("01", stream_callback=callback)

Creates logs/plan_01_execution.log with full details
Source code in ras_commander/callbacks.py
Python
class FileLoggerCallback:
    """
    Callback that writes execution progress to per-plan log files.

    Creates a separate log file for each plan, enabling:
    - Detailed execution logs
    - Post-execution analysis
    - Archival records

    Thread Safety:
        Uses threading.Lock to ensure thread-safe file operations.
        Safe for concurrent use in compute_parallel().

    Example:
        >>> from pathlib import Path
        >>> from ras_commander.callbacks import FileLoggerCallback
        >>>
        >>> callback = FileLoggerCallback(output_dir=Path("logs"))
        >>> RasCmdr.compute_plan("01", stream_callback=callback)
        # Creates logs/plan_01_execution.log with full details
    """

    def __init__(self, output_dir: Path):
        """
        Initialize file logger callback.

        Args:
            output_dir: Directory for log files (created if doesn't exist)
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.log_handles = {}
        self.lock = Lock()
        logger.debug(f"FileLoggerCallback initialized: {self.output_dir}")

    def on_exec_start(self, plan_number: str, command: str) -> None:
        """Open log file for this plan."""
        with self.lock:
            log_file = self.output_dir / f"plan_{plan_number}_execution.log"
            self.log_handles[plan_number] = open(log_file, 'w', encoding='utf-8')
            self.log_handles[plan_number].write(f"=== Plan {plan_number} Execution Log ===\n")
            self.log_handles[plan_number].write(f"Command: {command}\n")
            self.log_handles[plan_number].write("=" * 80 + "\n\n")
            self.log_handles[plan_number].flush()

    def on_exec_message(self, plan_number: str, message: str) -> None:
        """Write message to plan's log file."""
        with self.lock:
            if plan_number in self.log_handles:
                self.log_handles[plan_number].write(message + '\n')
                self.log_handles[plan_number].flush()

    def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
        """Write completion message and close log file."""
        with self.lock:
            if plan_number in self.log_handles:
                status = "SUCCESS" if success else "FAILED"
                self.log_handles[plan_number].write("\n" + "=" * 80 + "\n")
                self.log_handles[plan_number].write(f"Execution {status} in {duration:.1f} seconds\n")
                self.log_handles[plan_number].close()
                del self.log_handles[plan_number]

    def __del__(self):
        """Cleanup: close any remaining open file handles."""
        with self.lock:
            for handle in self.log_handles.values():
                try:
                    handle.close()
                except:
                    pass
__init__
Python
__init__(output_dir: Path)

Initialize file logger callback.

Parameters:

Name Type Description Default
output_dir Path

Directory for log files (created if doesn't exist)

required
Source code in ras_commander/callbacks.py
Python
def __init__(self, output_dir: Path):
    """
    Initialize file logger callback.

    Args:
        output_dir: Directory for log files (created if doesn't exist)
    """
    self.output_dir = Path(output_dir)
    self.output_dir.mkdir(parents=True, exist_ok=True)
    self.log_handles = {}
    self.lock = Lock()
    logger.debug(f"FileLoggerCallback initialized: {self.output_dir}")
on_exec_start
Python
on_exec_start(plan_number: str, command: str) -> None

Open log file for this plan.

Source code in ras_commander/callbacks.py
Python
def on_exec_start(self, plan_number: str, command: str) -> None:
    """Open log file for this plan."""
    with self.lock:
        log_file = self.output_dir / f"plan_{plan_number}_execution.log"
        self.log_handles[plan_number] = open(log_file, 'w', encoding='utf-8')
        self.log_handles[plan_number].write(f"=== Plan {plan_number} Execution Log ===\n")
        self.log_handles[plan_number].write(f"Command: {command}\n")
        self.log_handles[plan_number].write("=" * 80 + "\n\n")
        self.log_handles[plan_number].flush()
on_exec_message
Python
on_exec_message(plan_number: str, message: str) -> None

Write message to plan's log file.

Source code in ras_commander/callbacks.py
Python
def on_exec_message(self, plan_number: str, message: str) -> None:
    """Write message to plan's log file."""
    with self.lock:
        if plan_number in self.log_handles:
            self.log_handles[plan_number].write(message + '\n')
            self.log_handles[plan_number].flush()
on_exec_complete
Python
on_exec_complete(plan_number: str, success: bool, duration: float) -> None

Write completion message and close log file.

Source code in ras_commander/callbacks.py
Python
def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
    """Write completion message and close log file."""
    with self.lock:
        if plan_number in self.log_handles:
            status = "SUCCESS" if success else "FAILED"
            self.log_handles[plan_number].write("\n" + "=" * 80 + "\n")
            self.log_handles[plan_number].write(f"Execution {status} in {duration:.1f} seconds\n")
            self.log_handles[plan_number].close()
            del self.log_handles[plan_number]
__del__
Python
__del__()

Cleanup: close any remaining open file handles.

Source code in ras_commander/callbacks.py
Python
def __del__(self):
    """Cleanup: close any remaining open file handles."""
    with self.lock:
        for handle in self.log_handles.values():
            try:
                handle.close()
            except:
                pass
ProgressBarCallback

Callback that displays tqdm progress bars for execution.

Shows real-time progress with: - Per-plan progress bar - Last message displayed - Execution time tracking

Thread Safety

Uses threading.Lock to ensure thread-safe tqdm operations. Safe for concurrent use in compute_parallel().

Requirements

Requires tqdm package: pip install tqdm

Example

from ras_commander.callbacks import ProgressBarCallback

callback = ProgressBarCallback() RasCmdr.compute_plan("01", stream_callback=callback) Plan 01: 100%|████████████| 1234/1234 [00:45<00:00, 27.42msg/s]

Source code in ras_commander/callbacks.py
Python
class ProgressBarCallback:
    """
    Callback that displays tqdm progress bars for execution.

    Shows real-time progress with:
    - Per-plan progress bar
    - Last message displayed
    - Execution time tracking

    Thread Safety:
        Uses threading.Lock to ensure thread-safe tqdm operations.
        Safe for concurrent use in compute_parallel().

    Requirements:
        Requires tqdm package: pip install tqdm

    Example:
        >>> from ras_commander.callbacks import ProgressBarCallback
        >>>
        >>> callback = ProgressBarCallback()
        >>> RasCmdr.compute_plan("01", stream_callback=callback)
        Plan 01: 100%|████████████| 1234/1234 [00:45<00:00, 27.42msg/s]
    """

    def __init__(self):
        """Initialize progress bar callback."""
        if not TQDM_AVAILABLE:
            raise ImportError(
                "ProgressBarCallback requires tqdm package. "
                "Install with: pip install tqdm"
            )
        self.pbars = {}
        self.lock = Lock()

    def on_exec_start(self, plan_number: str, command: str) -> None:
        """Create progress bar for this plan."""
        with self.lock:
            self.pbars[plan_number] = tqdm(
                desc=f"Plan {plan_number}",
                unit="msg",
                dynamic_ncols=True
            )

    def on_exec_message(self, plan_number: str, message: str) -> None:
        """Update progress bar with new message."""
        with self.lock:
            if plan_number in self.pbars:
                # Show last 50 characters of message
                short_message = message.strip()[-50:]
                self.pbars[plan_number].set_postfix_str(short_message)
                self.pbars[plan_number].update(1)

    def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
        """Close progress bar and display final status."""
        with self.lock:
            if plan_number in self.pbars:
                status = "SUCCESS" if success else "FAILED"
                self.pbars[plan_number].set_postfix_str(f"{status} in {duration:.1f}s")
                self.pbars[plan_number].close()
                del self.pbars[plan_number]
__init__
Python
__init__()

Initialize progress bar callback.

Source code in ras_commander/callbacks.py
Python
def __init__(self):
    """Initialize progress bar callback."""
    if not TQDM_AVAILABLE:
        raise ImportError(
            "ProgressBarCallback requires tqdm package. "
            "Install with: pip install tqdm"
        )
    self.pbars = {}
    self.lock = Lock()
on_exec_start
Python
on_exec_start(plan_number: str, command: str) -> None

Create progress bar for this plan.

Source code in ras_commander/callbacks.py
Python
def on_exec_start(self, plan_number: str, command: str) -> None:
    """Create progress bar for this plan."""
    with self.lock:
        self.pbars[plan_number] = tqdm(
            desc=f"Plan {plan_number}",
            unit="msg",
            dynamic_ncols=True
        )
on_exec_message
Python
on_exec_message(plan_number: str, message: str) -> None

Update progress bar with new message.

Source code in ras_commander/callbacks.py
Python
def on_exec_message(self, plan_number: str, message: str) -> None:
    """Update progress bar with new message."""
    with self.lock:
        if plan_number in self.pbars:
            # Show last 50 characters of message
            short_message = message.strip()[-50:]
            self.pbars[plan_number].set_postfix_str(short_message)
            self.pbars[plan_number].update(1)
on_exec_complete
Python
on_exec_complete(plan_number: str, success: bool, duration: float) -> None

Close progress bar and display final status.

Source code in ras_commander/callbacks.py
Python
def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
    """Close progress bar and display final status."""
    with self.lock:
        if plan_number in self.pbars:
            status = "SUCCESS" if success else "FAILED"
            self.pbars[plan_number].set_postfix_str(f"{status} in {duration:.1f}s")
            self.pbars[plan_number].close()
            del self.pbars[plan_number]
SynchronizedCallback

Thread-safe wrapper for any callback implementation.

Wraps an existing callback to add thread-safety using locks. Useful when: - Using a callback that isn't thread-safe - Working with compute_parallel() - Sharing state across callbacks

Thread Safety

Wraps all callback methods with threading.Lock. Guarantees only one thread executes callback at a time.

Example

class MyCallback: ... def init(self): ... self.messages = [] # Not thread-safe! ... def on_exec_message(self, plan_number, message): ... self.messages.append((plan_number, message))

unsafe_callback = MyCallback() safe_callback = SynchronizedCallback(unsafe_callback) RasCmdr.compute_parallel(["01", "02"], stream_callback=safe_callback)

Source code in ras_commander/callbacks.py
Python
class SynchronizedCallback:
    """
    Thread-safe wrapper for any callback implementation.

    Wraps an existing callback to add thread-safety using locks.
    Useful when:
    - Using a callback that isn't thread-safe
    - Working with compute_parallel()
    - Sharing state across callbacks

    Thread Safety:
        Wraps all callback methods with threading.Lock.
        Guarantees only one thread executes callback at a time.

    Example:
        >>> class MyCallback:
        ...     def __init__(self):
        ...         self.messages = []  # Not thread-safe!
        ...     def on_exec_message(self, plan_number, message):
        ...         self.messages.append((plan_number, message))
        >>>
        >>> unsafe_callback = MyCallback()
        >>> safe_callback = SynchronizedCallback(unsafe_callback)
        >>> RasCmdr.compute_parallel(["01", "02"], stream_callback=safe_callback)
    """

    def __init__(self, callback: ExecutionCallback):
        """
        Wrap a callback with thread-safety.

        Args:
            callback: Callback object to wrap (must implement ExecutionCallback methods)
        """
        self._callback = callback
        self._lock = Lock()

    def on_prep_start(self, plan_number: str) -> None:
        """Thread-safe wrapper for on_prep_start."""
        with self._lock:
            if hasattr(self._callback, 'on_prep_start'):
                self._callback.on_prep_start(plan_number)

    def on_prep_complete(self, plan_number: str) -> None:
        """Thread-safe wrapper for on_prep_complete."""
        with self._lock:
            if hasattr(self._callback, 'on_prep_complete'):
                self._callback.on_prep_complete(plan_number)

    def on_exec_start(self, plan_number: str, command: str) -> None:
        """Thread-safe wrapper for on_exec_start."""
        with self._lock:
            if hasattr(self._callback, 'on_exec_start'):
                self._callback.on_exec_start(plan_number, command)

    def on_exec_message(self, plan_number: str, message: str) -> None:
        """Thread-safe wrapper for on_exec_message."""
        with self._lock:
            if hasattr(self._callback, 'on_exec_message'):
                self._callback.on_exec_message(plan_number, message)

    def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
        """Thread-safe wrapper for on_exec_complete."""
        with self._lock:
            if hasattr(self._callback, 'on_exec_complete'):
                self._callback.on_exec_complete(plan_number, success, duration)

    def on_verify_result(self, plan_number: str, verified: bool) -> None:
        """Thread-safe wrapper for on_verify_result."""
        with self._lock:
            if hasattr(self._callback, 'on_verify_result'):
                self._callback.on_verify_result(plan_number, verified)
__init__
Python
__init__(callback: ExecutionCallback)

Wrap a callback with thread-safety.

Parameters:

Name Type Description Default
callback ExecutionCallback

Callback object to wrap (must implement ExecutionCallback methods)

required
Source code in ras_commander/callbacks.py
Python
def __init__(self, callback: ExecutionCallback):
    """
    Wrap a callback with thread-safety.

    Args:
        callback: Callback object to wrap (must implement ExecutionCallback methods)
    """
    self._callback = callback
    self._lock = Lock()
on_prep_start
Python
on_prep_start(plan_number: str) -> None

Thread-safe wrapper for on_prep_start.

Source code in ras_commander/callbacks.py
Python
def on_prep_start(self, plan_number: str) -> None:
    """Thread-safe wrapper for on_prep_start."""
    with self._lock:
        if hasattr(self._callback, 'on_prep_start'):
            self._callback.on_prep_start(plan_number)
on_prep_complete
Python
on_prep_complete(plan_number: str) -> None

Thread-safe wrapper for on_prep_complete.

Source code in ras_commander/callbacks.py
Python
def on_prep_complete(self, plan_number: str) -> None:
    """Thread-safe wrapper for on_prep_complete."""
    with self._lock:
        if hasattr(self._callback, 'on_prep_complete'):
            self._callback.on_prep_complete(plan_number)
on_exec_start
Python
on_exec_start(plan_number: str, command: str) -> None

Thread-safe wrapper for on_exec_start.

Source code in ras_commander/callbacks.py
Python
def on_exec_start(self, plan_number: str, command: str) -> None:
    """Thread-safe wrapper for on_exec_start."""
    with self._lock:
        if hasattr(self._callback, 'on_exec_start'):
            self._callback.on_exec_start(plan_number, command)
on_exec_message
Python
on_exec_message(plan_number: str, message: str) -> None

Thread-safe wrapper for on_exec_message.

Source code in ras_commander/callbacks.py
Python
def on_exec_message(self, plan_number: str, message: str) -> None:
    """Thread-safe wrapper for on_exec_message."""
    with self._lock:
        if hasattr(self._callback, 'on_exec_message'):
            self._callback.on_exec_message(plan_number, message)
on_exec_complete
Python
on_exec_complete(plan_number: str, success: bool, duration: float) -> None

Thread-safe wrapper for on_exec_complete.

Source code in ras_commander/callbacks.py
Python
def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
    """Thread-safe wrapper for on_exec_complete."""
    with self._lock:
        if hasattr(self._callback, 'on_exec_complete'):
            self._callback.on_exec_complete(plan_number, success, duration)
on_verify_result
Python
on_verify_result(plan_number: str, verified: bool) -> None

Thread-safe wrapper for on_verify_result.

Source code in ras_commander/callbacks.py
Python
def on_verify_result(self, plan_number: str, verified: bool) -> None:
    """Thread-safe wrapper for on_verify_result."""
    with self._lock:
        if hasattr(self._callback, 'on_verify_result'):
            self._callback.on_verify_result(plan_number, verified)
Custom Callbacks

Create custom callbacks by implementing the ExecutionCallback protocol:

Python
class CustomCallback:
    """Minimal custom callback - implement only what you need."""

    def on_exec_complete(self, plan_number, success, duration):
        status = "SUCCESS" if success else "FAILED"
        print(f"Plan {plan_number}: {status} in {duration:.1f}s")

# Use it
RasCmdr.compute_plan("01", stream_callback=CustomCallback())

compute_parallel() and compute_test_mode() do not accept stream_callback. For serial monitoring, call compute_plan() in a loop. SynchronizedCallback protects callbacks shared by caller-managed threads; it does not enable callbacks on the batch APIs. Callback completion notifications are distinct from the final ComputeResult and its artifact-handling outcome.

Linux-Hosted Unsteady Preparation

RasPreprocess

Static class for Windows preprocessing of HEC-RAS plans for Linux execution.

Automates Phase 1 of the two-phase Linux execution workflow: 1. Launches HEC-RAS on Windows 2. Monitors the .bco log or owned process tree for compute-engine startup 3. Terminates HEC-RAS at that point (preprocessing complete) 4. Verifies .tmp.hdf, .b##, .x## files were generated

All methods are static — do not instantiate this class.

Example

from ras_commander import RasPreprocess, init_ras_project init_ras_project("/path/to/project", "7.0") result = RasPreprocess.preprocess_plan("01") if result: ... print(f"Ready for Linux in {result.elapsed_seconds:.1f}s")

Source code in ras_commander/RasPreprocess.py
Python
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
class RasPreprocess:
    """
    Static class for Windows preprocessing of HEC-RAS plans for Linux execution.

    Automates Phase 1 of the two-phase Linux execution workflow:
    1. Launches HEC-RAS on Windows
    2. Monitors the .bco log or owned process tree for compute-engine startup
    3. Terminates HEC-RAS at that point (preprocessing complete)
    4. Verifies .tmp.hdf, .b##, .x## files were generated

    All methods are static — do not instantiate this class.

    Example:
        >>> from ras_commander import RasPreprocess, init_ras_project
        >>> init_ras_project("/path/to/project", "7.0")
        >>> result = RasPreprocess.preprocess_plan("01")
        >>> if result:
        ...     print(f"Ready for Linux in {result.elapsed_seconds:.1f}s")
    """

    @staticmethod
    @log_call
    def write_event_conditions(
        plan_hdf: Union[str, Path], geom_hdf: Union[str, Path],
        flow_file: Union[str, Path], *, start_time: datetime, end_time: datetime,
        units: str, target_ras_version: str,
    ) -> Path:
        """Write experimental 7.0.1 2D boundary forcing from flow text.

        Args:
            plan_hdf: Existing staged HDF without boundary forcing, containing
                the same area order, mesh and boundary tables as geom_hdf.
            geom_hdf: Compiled geometry with External Faces and BC Length.
                When boundaries were repaired, both HDFs must retain matching,
                current repair provenance. Flow-file types must agree with every
                flow/normal-depth tie decision recorded by the repair.
            flow_file: Unsteady text containing flow hydrographs or normal depth.
            start_time: Naive local datetime defining hydrograph day zero.
            end_time: Naive local simulation end datetime.
            units: ``Metric`` or ``English``; must match both HDF unit labels.
                Hydrograph ordinates retain the caller-declared flow-file units.
            target_ras_version: Must be ``7.0.1``.

        Returns:
            Path: Updated plan HDF. A sibling .events.bak retains the original.

        Raises:
            ValueError: Unsupported forcing, associations, units, or time basis.
            FileExistsError: Backup already exists.
            OSError: File access or atomic replacement failed.

        Prevalidates all forcing, writes a temporary sibling, then backs up and
        atomically replaces the destination. Unrelated content is preserved.
        Both HDF files must declare 7.0.1. Does not mark preprocessing complete
        or write initial conditions, mesh,
        plan data, .x or .b files. Native solver equivalence remains unqualified.
        Call only while no other process is modifying these files.
        """
        from ._event_conditions import _write_events
        return _write_events(plan_hdf, geom_hdf, flow_file, start_time,
                             end_time, units, target_ras_version)

    _TCU_DIALOG_TITLE = TCU_DIALOG_TITLE
    _TCU_BLOCKING_ERROR = TCU_BLOCKING_ERROR
    _TCU_SUPERVISION_ERROR = (
        "HEC-RAS legal-dialog supervision could not establish the launched "
        "process tree. ras-commander refused to continue without a scoped "
        "first-run TCU check."
    )
    _UNSTEADY_PROCESS_NAMES = frozenset(
        {
            "rasunsteady",
            "rasunsteady.exe",
            "rasunsteady64",
            "rasunsteady64.exe",
        }
    )
    _GRIDDED_PRECIPITATION_GROUP = "Event Conditions/Meteorology/Precipitation"
    _GRIDDED_PRECIPITATION_INTERPOLATION_DATASETS = (
        "Cell Indexes",
        "Cell Info",
        "Cell Weights",
        "Face Indexes",
        "Face Info",
        "Face Weights",
    )
    _GRIDDED_PRECIPITATION_STABLE_SECONDS = 2.0

    @staticmethod
    def _ras_compute_command_line(
        ras_exe: Union[str, Path],
        project_file: Union[str, Path],
        plan_file: Union[str, Path],
    ) -> str:
        """Build the fully quoted command line required by ``Ras.exe -c``.

        HEC-RAS parses the optional plan path from the raw Windows command
        line and requires it to be quoted even when the path has no spaces.
        Passing an argument vector through ``subprocess`` is therefore not
        equivalent to the documented command-line contract.
        """
        values = tuple(str(value) for value in (ras_exe, project_file, plan_file))
        if any('"' in value for value in values):
            raise ValueError("HEC-RAS command paths cannot contain a double quote")
        executable, project, plan = values
        return f'"{executable}" -c "{project}" "{plan}"'

    @staticmethod
    @log_call
    def preprocess_plan(
        plan_number: Union[str, Number],
        ras_object=None,
        max_wait: int = 300,
        clear_existing: bool = True,
        fix_line_endings: bool = True,
        require_linux_solver_ready: bool = True,
        *,
        accept_tcu: bool = False,
        precipitation_repair_attempts: int = 6,
        precipitation_repair_timeout: Optional[int] = None,
    ) -> PreprocessResult:
        """
        Preprocess a plan on Windows for Linux execution.

        Runs HEC-RAS with early termination to generate .tmp.hdf, .b##, and .x##
        files required by the Linux RasUnsteady binary. The process is killed when
        the .bco log indicates preprocessing is complete ("Starting Unsteady Flow
        Computations" signal), or when an owned ``RasUnsteady.exe`` descendant has
        started and all three prerequisite files are non-empty. The process-tree
        fallback supports releases that create an empty ``.bco`` file.

        Set require_linux_solver_ready=False for native Windows computation:
        that mode stops after the observed event writer exits, checks file
        quiescence after owned cleanup, and validates materialized meteorology.
        The default additionally requires Linux-specific geometry input tables.

        After owned writers stop, success also requires Event Conditions to
        report ``Completed Successfully=True``. Enabled point or gridded rain
        requires a non-empty two-dimensional precipitation ``Values`` dataset.
        Missing completion evidence is rejected, including when copying a fresh
        final HDF. Failure retains artifact paths and readiness-signal details.

        HEC-RAS's own event-condition writer, ``RasProcess.exe
        CompletePreProcess``, can intermittently write no point precipitation
        for identical inputs. It reports "No valid precipitation time-series
        data found for this time-window" and "Error processing Precipitation
        data, exiting...", and Ras.exe then exits 0 before the unsteady
        computation. This was observed in 8 of 47 processes (17%) with HEC-RAS
        6.6 under Wine, and also with 6.4.1; it is not caused by the
        early-stop logic. When a point-precipitation plan fails Event
        Conditions validation and the temporary HDF, ``.b##`` and ``.x##`` are
        all present, this method re-runs only ``RasProcess.exe
        CompletePreProcess <project>.rasmap <plan>.tmp.hdf`` on the same
        temporary HDF, from the project folder, and re-validates after each
        attempt. A repaired file matched a first-try success exactly. Gridded
        precipitation is not repaired this way.

        With HEC-RAS before 6.3, fails without launching HEC-RAS when the plan's
        geometry HDF references a land-cover, infiltration, or sediment file that
        does not exist. Those releases would otherwise skip the geometry and
        write no 2D mesh.

        Unpatched HEC-RAS 7.0.2 temporarily receives a project declaration containing only
        this plan. The original project bytes are restored after owned processes
        stop. An unproved stop retains the single-plan file, original backup,
        and claim and fails the result with a recovery diagnostic.
        An exact recognized local CLI patch skips the project transaction;
        the single-plan execution guide records its SHA-256 and tested scope.

        Args:
            plan_number: Plan number to preprocess (e.g., "01", 1).
            ras_object (RasPrj, optional): Optional RasPrj instance. If None, uses global ras.
            max_wait: Maximum seconds to wait for preprocessing (default 300).
            clear_existing: Delete stale preprocessing files before running (default True).
            fix_line_endings: Convert .x file CRLF to LF for Linux (default True).
            accept_tcu: Explicitly authorize accepting an exact owned TCU wizard
                during this launch. False by default; acceptance failures block
                preprocessing and receipts are retained in the result.
            precipitation_repair_attempts: Maximum ``CompletePreProcess``
                re-runs used to complete point precipitation (default 6; 0
                disables the repair). Repairs stop early on a timeout, a
                legal-dialog block, a launch failure, or surviving processes.
            precipitation_repair_timeout: Seconds allowed for each repair
                attempt. Defaults to ``max_wait``, which already bounds the
                full preprocessing run that includes this step.

        Returns:
            PreprocessResult: Result with success flag, file paths, and timing.
                Bool-compatible: ``if preprocess_plan("01"):`` works.
                ``precipitation_repair_attempts`` records each repair attempt,
                and ``signal_source`` is ``"completepreprocess_repair"`` when
                a repair completed the temporary HDF.

        Note:
            Errors are captured in PreprocessResult.error.

        Example:
            >>> result = RasPreprocess.preprocess_plan("01")
            >>> if result:
            ...     print(f"tmp.hdf: {result.tmp_hdf_path}")
            ...     print(f".b file: {result.b_file_path}")
            ...     print(f".x file: {result.x_file_path}")
        """
        # A HEC-RAS 7.0.2 single-plan project declaration must be restored on
        # every exit, including exceptions, so the launch lifecycle runs inside
        # one owned try/finally. Result paths release it through make_result;
        # this finally covers only exits that never built a result.
        lifecycle = SinglePlanLaunchLifecycle()
        try:
            return RasPreprocess._preprocess_plan_lifecycle(
                plan_number,
                ras_object,
                max_wait,
                clear_existing,
                fix_line_endings,
                require_linux_solver_ready,
                accept_tcu=accept_tcu,
                precipitation_repair_attempts=precipitation_repair_attempts,
                precipitation_repair_timeout=precipitation_repair_timeout,
                lifecycle=lifecycle,
            )
        finally:
            if lifecycle.pending:
                lifecycle.finish()

    @staticmethod
    def _preprocess_plan_lifecycle(
        plan_number: Union[str, Number],
        ras_object=None,
        max_wait: int = 300,
        clear_existing: bool = True,
        fix_line_endings: bool = True,
        require_linux_solver_ready: bool = True,
        *,
        accept_tcu: bool = False,
        precipitation_repair_attempts: int = 6,
        precipitation_repair_timeout: Optional[int] = None,
        lifecycle: SinglePlanLaunchLifecycle,
    ) -> PreprocessResult:
        """Run one owned preprocessing launch; see :meth:`preprocess_plan`."""
        if not isinstance(require_linux_solver_ready, bool):
            raise ValueError("require_linux_solver_ready must be a bool")
        if not isinstance(accept_tcu, bool):
            raise ValueError("accept_tcu must be a bool")
        start_time = time.time()
        started_monotonic = time.monotonic() if accept_tcu else 0.0
        tcu_receipts = []

        def make_result(**values):
            if accept_tcu:
                result = PreprocessResult(**values, tcu_acceptance_receipts=list(tcu_receipts))
            else:
                result = PreprocessResult(**values)
            if lifecycle.pending:
                # Every result path passes here, so the HEC-RAS 7.0.2
                # single-plan declaration is restored before the caller sees
                # the result. A restoration that cannot be proved fails the
                # result and carries the recovery path.
                outcome = lifecycle.finish()
                if outcome is not None and not outcome.ok:
                    error = outcome.detail
                    if result.error:
                        error = f"{result.error}. {error}"
                    result = dataclasses.replace(result, success=False, error=error)
            return result

        ras_obj = ras_object if ras_object is not None else ras

        # Normalize plan number
        if isinstance(plan_number, Number):
            plan_num = f"{int(plan_number):02d}"
        else:
            plan_num = str(plan_number).zfill(2)

        try:
            ras_obj.check_initialized()
        except Exception as e:
            return make_result(
                success=False, plan_number=plan_num,
                error=f"Project not initialized: {e}",
                elapsed_seconds=time.time() - start_time,
            )

        project_folder = Path(ras_obj.project_folder)
        project_name = ras_obj.project_name

        # Get geometry number from plan_df (DataFrame-first), fallback to file parsing
        geometry_number = None
        try:
            plan_row = ras_obj.plan_df[ras_obj.plan_df['plan_number'] == plan_num]
            if not plan_row.empty and 'Geom File' in plan_row.columns:
                geom_ref = str(plan_row['Geom File'].iloc[0])
                m = re.search(r'(\d+)', geom_ref)
                if m:
                    geometry_number = m.group(1)
        except Exception:
            pass

        if geometry_number is None:
            plan_path = RasPlan.get_plan_path(plan_num, ras_obj)
            if plan_path:
                geometry_number = RasPreprocess._extract_geometry_number(Path(plan_path))
            if geometry_number is None:
                return make_result(
                    success=False, plan_number=plan_num,
                    error=f"Could not determine geometry number for plan {plan_num}",
                    elapsed_seconds=time.time() - start_time,
                )

        logger.debug(f"Plan {plan_num} uses geometry g{geometry_number}")

        # Build file paths
        tmp_hdf = project_folder / f"{project_name}.p{plan_num}.tmp.hdf"
        hdf_file = project_folder / f"{project_name}.p{plan_num}.hdf"
        b_file = project_folder / f"{project_name}.b{plan_num}"
        x_file = project_folder / f"{project_name}.x{geometry_number}"
        plan_file = project_folder / f"{project_name}.p{plan_num}"
        prj_file = project_folder / f"{project_name}.prj"
        precipitation_mode = (
            RasPreprocess._plan_precipitation_mode(
                plan_file,
                project_folder,
                project_name,
            )
        )
        requires_gridded_precipitation = precipitation_mode == "gridded"

        hdf_state_before = None
        if hdf_file.is_file():
            hdf_stat = hdf_file.stat()
            hdf_state_before = (hdf_stat.st_size, hdf_stat.st_mtime_ns)

        # Validate plan file exists
        if not plan_file.exists():
            return make_result(
                success=False, plan_number=plan_num,
                geometry_number=geometry_number,
                error=f"Plan file not found: {plan_file}",
                elapsed_seconds=time.time() - start_time,
            )

        # Validate project file exists
        if not prj_file.exists():
            return make_result(
                success=False, plan_number=plan_num,
                geometry_number=geometry_number,
                error=f"Project file not found: {prj_file}",
                elapsed_seconds=time.time() - start_time,
            )

        # Get HEC-RAS executable
        ras_exe = ras_obj.ras_exe_path
        if not ras_exe or not Path(ras_exe).exists():
            return make_result(
                success=False, plan_number=plan_num,
                geometry_number=geometry_number,
                error=f"HEC-RAS executable not found: {ras_exe}",
                elapsed_seconds=time.time() - start_time,
            )

        # Before 6.3, HEC-RAS skips the geometry without an error when a
        # referenced land-classification file is missing, leaving no 2D mesh
        # in the plan HDF. Refuse to run rather than report that as success.
        if RasPreprocess._skips_geometry_without_land_classification(ras_exe):
            geom_hdf = project_folder / f"{project_name}.g{geometry_number}.hdf"
            missing_files = RasPreprocess._missing_land_classification_files(geom_hdf)
            if missing_files:
                return make_result(
                    success=False, plan_number=plan_num,
                    geometry_number=geometry_number,
                    error=(
                        f"Geometry g{geometry_number} references files that do not "
                        f"exist: {'; '.join(missing_files)}. HEC-RAS "
                        f"{Path(ras_exe).parent.name} skips the geometry when they "
                        "are missing. Restore them or update the geometry's "
                        "associations before preprocessing."
                    ),
                    elapsed_seconds=time.time() - start_time,
                )

        supervision_error = RasPreprocess._tcu_supervision_availability_error()
        if supervision_error:
            return make_result(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                error=supervision_error,
                elapsed_seconds=time.time() - start_time,
            )

        # HEC-RAS 7.0.2 computes the project's listed plans in order and
        # ignores the plan argument and Current Plan. Expose only the
        # requested plan for this owned launch; make_result and the enclosing
        # finally restore the original project bytes.
        if single_plan_project_required(
            ras_exe_path=ras_exe,
            ras_version=getattr(ras_obj, "ras_version", None),
        ):
            lifecycle.transaction = SinglePlanProjectTransaction(
                prj_file,
                plan_num,
                launch_owner="RasPreprocess.preprocess_plan",
            )
            try:
                lifecycle.transaction.apply()
            except SinglePlanProjectError as e:
                return make_result(
                    success=False,
                    plan_number=plan_num,
                    geometry_number=geometry_number,
                    error=(
                        f"Could not expose plan {plan_num} as the only HEC-RAS "
                        f"7.0.2 project plan: {e}"
                    ),
                    elapsed_seconds=time.time() - start_time,
                )

        # Clear existing preprocessing files
        if clear_existing:
            RasPreprocess._clear_preprocessing_files(
                project_folder, project_name, plan_num, geometry_number
            )

        artifact_baseline = {
            path: RasPreprocess._artifact_state(path)
            for path in (tmp_hdf, b_file, x_file, hdf_file)
        }

        # Enable detailed logging to create .bco file
        BcoMonitor.enable_detailed_logging(plan_file)

        # Keep a Python launcher alive while the GUI-subsystem Ras.exe runs.
        # This provides a stable job-owned ancestry under native Windows and
        # Windows Python hosted by Wine.
        launcher = (
            "import subprocess,sys; "
            "ras_exe,command_line=sys.argv[1:3]; "
            "raise SystemExit(subprocess.call(command_line, "
            "executable=ras_exe, shell=False))"
        )
        try:
            compute_command_line = RasPreprocess._ras_compute_command_line(
                ras_exe,
                prj_file,
                plan_file,
            )
        except ValueError as e:
            return make_result(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                error=f"Could not launch HEC-RAS preprocessing: {e}",
                elapsed_seconds=time.time() - start_time,
            )
        cmd = [
            sys.executable,
            "-c",
            launcher,
            str(ras_exe),
            compute_command_line,
        ]
        logger.info("Starting HEC-RAS preprocessing for plan %s", plan_num)
        logger.debug(f"Command: {cmd}")

        # Launch HEC-RAS
        try:
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                cwd=str(project_folder),
                shell=False,
            )
        except OSError as e:
            return make_result(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                error=f"Could not launch HEC-RAS preprocessing: {e}",
                elapsed_seconds=time.time() - start_time,
            )

        def _owned_launch_quiescent() -> bool:
            # Restore the project only after the owned launcher and any
            # exact-plan residue from this launch window are stopped.
            if process.poll() is None:
                RasPreprocess._terminate_process_tree(process)
            _stopped, surviving = RasPreprocess._terminate_exact_preprocess_residue(
                project_file=prj_file,
                plan_file=plan_file,
                tmp_hdf=tmp_hdf,
                started_at=start_time,
            )
            return process.poll() is not None and not surviving

        lifecycle.prove_quiescent = _owned_launch_quiescent

        launch_create_time = None
        if accept_tcu:
            try:
                import psutil

                launch_create_time = float(psutil.Process(process.pid).create_time())
            except Exception as exc:
                # A missing identity never authorizes assent. Normal scoped
                # supervision remains active if no TCU dialog is encountered.
                logger.warning("Could not capture explicit TCU launch identity: %s", exc)
        tcu_acceptance_state = {}

        gridded_stability_state: Dict[str, object] = {}
        solver_started = lambda: RasPreprocess._unsteady_compute_started(
            process.pid,
            tmp_hdf,
            b_file,
            x_file,
            artifact_baseline=artifact_baseline,
        )
        if requires_gridded_precipitation:
            alternate_signal_condition = lambda: (
                RasPreprocess._completepreprocess_handoff_ready(
                    tmp_hdf,
                    b_file,
                    x_file,
                    gridded_stability_state,
                    started_at=start_time,
                    artifact_baseline=artifact_baseline,
                    solver_started=solver_started,
                    defer_stat_quiescence=not require_linux_solver_ready,
                )
            )
            alternate_signal_description = (
                "an exited native writer or a witnessed owned solver start; "
                "stopping before post-cleanup artifact quiescence"
            )
        else:
            alternate_signal_condition = lambda: (
                RasPreprocess._unsteady_compute_started(
                    process.pid,
                    tmp_hdf,
                    b_file,
                    x_file,
                    artifact_baseline=artifact_baseline,
                )
            )
            alternate_signal_description = (
                "owned RasUnsteady.exe startup with complete preprocessing "
                "artifacts"
            )

        # Monitor .bco file for preprocessing completion signal
        monitor = BcoMonitor(
            project_path=project_folder,
            plan_number=plan_num,
            project_name=project_name,
            signal_string="Starting Unsteady Flow Computations",
            max_wait_seconds=max_wait,
            blocking_condition=lambda: (
                RasPreprocess._preprocessing_tcu_probe(
                    process, accept_tcu=accept_tcu,
                    launch_create_time=launch_create_time, ras_exe=ras_exe,
                    deadline=started_monotonic + float(max_wait),
                    receipts=tcu_receipts, acceptance_state=tcu_acceptance_state,
                )
            ),
            alternate_signal_condition=alternate_signal_condition,
            alternate_signal_description=alternate_signal_description,
        )

        signal_detected = monitor.monitor_until_signal(process)
        blocked_reason = getattr(monitor, "blocked_reason", None)
        monitor_source = getattr(monitor, "signal_source", None)
        signal_source = (
            (
                "completepreprocess_writer_quiescent"
                if requires_gridded_precipitation
                else "owned_process_artifacts"
            )
            if monitor_source == "alternate"
            else monitor_source
        )
        if signal_detected and signal_source is None:
            signal_source = "bco"

        if blocked_reason:
            if process.poll() is None:
                RasPreprocess._terminate_process_tree(process)
            return make_result(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                signal_source="blocked_legal_dialog",
                error=blocked_reason,
                elapsed_seconds=time.time() - start_time,
            )

        # The BCO marker is written before the owned RasUnsteady process is
        # guaranteed to have started. That distinction matters for gridded
        # precipitation: the BCO marker is telemetry, not proof that it is
        # safe to open or stop around the temporary HDF.  A native
        # CompletePreProcess writer can continue after it.  Keep polling only
        # process metadata and filesystem stat state until an observed writer
        # exits; no HDF inspection occurs in this active-engine loop.
        if (
            signal_detected
            and signal_source == "bco"
            and requires_gridded_precipitation
            and process.poll() is None
        ):
            readiness_deadline = start_time + float(max_wait)
            # A fast launcher can exit during the required writer/stat quiet
            # period. Keep checking the observed writer's quiescence after
            # that exit; launcher lifetime is not the readiness criterion.
            while time.time() < readiness_deadline:
                if RasPreprocess._completepreprocess_handoff_ready(
                    tmp_hdf,
                    b_file,
                    x_file,
                    gridded_stability_state,
                    started_at=start_time,
                    artifact_baseline=artifact_baseline,
                    solver_started=solver_started,
                    allow_completed_hdf=process.poll() is not None,
                    defer_stat_quiescence=True,
                ):
                    signal_source = "bco_completepreprocess_writer_quiescent"
                    logger.info(
                        "Observed CompletePreProcess writer exited; stopping "
                        "before post-cleanup artifact quiescence"
                    )
                    break
                time.sleep(0.1)

            if signal_source == "bco":
                if process.poll() is None:
                    RasPreprocess._terminate_process_tree(process)
                return make_result(
                    success=False,
                    plan_number=plan_num,
                    geometry_number=geometry_number,
                    signal_source="timeout",
                    timed_out=True,
                    error=(
                        "HEC-RAS reported the BCO computation-start marker, but an "
                        "exact launch-owned CompletePreProcess writer was not "
                        "observed to exit with quiescent artifacts before the "
                        f"preprocessing timeout ({int(max_wait)} seconds)."
                    ),
                    elapsed_seconds=time.time() - start_time,
                )

        # Terminate process tree
        process_was_running = process.poll() is None
        if process_was_running:
            RasPreprocess._terminate_process_tree(process)
            if not signal_detected:
                return make_result(
                    success=False,
                    plan_number=plan_num,
                    geometry_number=geometry_number,
                    signal_source="timeout",
                    timed_out=True,
                    error=(
                        "Preprocessing timed out after "
                        f"{int(max_wait)} seconds before a readiness signal"
                    ),
                    elapsed_seconds=time.time() - start_time,
                )
            logger.debug("Preprocessing signal detected; terminating HEC-RAS")
        elif signal_detected:
            logger.debug("Preprocessing complete; HEC-RAS process already exited")
        else:
            logger.warning(f"Process exited with code {process.returncode} before signal detected")
            signal_source = "natural_completion"
            if process.returncode not in (0, None):
                return make_result(
                    success=False,
                    plan_number=plan_num,
                    geometry_number=geometry_number,
                    signal_source=signal_source,
                    error=(
                        "HEC-RAS exited with code "
                        f"{process.returncode} before a readiness signal"
                    ),
                    elapsed_seconds=time.time() - start_time,
                )

        # Ras.exe is a GUI-subsystem launcher. On some HEC-RAS 7.x runs the
        # Python-owned launcher exits after spawning CompletePreProcess even
        # though an exact-plan Ras.exe/RasProcess.exe tree is still alive. In
        # that state ``process.poll()`` cannot prove quiescence, and the next
        # compute correctly refuses to replace artifacts that may still be
        # open. Clean only processes from this launch window whose command
        # lines contain the exact project+plan pair or the exact temporary HDF.
        stopped_residue, surviving_residue = (
            RasPreprocess._terminate_exact_preprocess_residue(
                project_file=prj_file,
                plan_file=plan_file,
                tmp_hdf=tmp_hdf,
                started_at=start_time,
            )
        )
        if stopped_residue:
            logger.info(
                "Stopped detached HEC-RAS preprocessing residue for plan %s: %s",
                plan_num,
                ", ".join(str(pid) for pid in stopped_residue),
            )
        if surviving_residue:
            return make_result(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                signal_source=signal_source,
                error=(
                    "Exact-plan HEC-RAS preprocessing processes remained active "
                    "after cleanup: "
                    + ", ".join(str(pid) for pid in surviving_residue)
                ),
                elapsed_seconds=time.time() - start_time,
            )

        if requires_gridded_precipitation and not RasPreprocess._wait_stopped_artifacts_quiet(
            (tmp_hdf if tmp_hdf.is_file() else hdf_file, b_file, x_file),
        ):
            return make_result(
                success=False, plan_number=plan_num, geometry_number=geometry_number,
                signal_source=signal_source,
                error="Stopped preprocessing artifacts did not become quiescent before HDF validation",
                elapsed_seconds=time.time() - start_time,
            )

        # If the process completed fully and wrote a new/changed final HDF but
        # no .tmp.hdf, use that fresh file as the Linux preprocessing input.
        # Never mistake an unchanged pre-existing final result for new output.
        full_result_copied = False
        hdf_state_after = None
        if hdf_file.is_file():
            hdf_stat = hdf_file.stat()
            hdf_state_after = (hdf_stat.st_size, hdf_stat.st_mtime_ns)
        if (
            not tmp_hdf.exists()
            and hdf_state_after is not None
            and hdf_state_after[0] > 0
            and hdf_state_after != hdf_state_before
        ):
            logger.warning(
                "Full simulation completed before early termination; copying %s to %s",
                hdf_file.name,
                tmp_hdf.name,
            )
            shutil.copy2(hdf_file, tmp_hdf)
            full_result_copied = True
            signal_source = "full_result_copy"

        # Verify all three prerequisite files exist and are non-empty
        missing = []
        if not tmp_hdf.exists() or tmp_hdf.stat().st_size == 0:
            missing.append(f".p{plan_num}.tmp.hdf")
        if not b_file.exists() or b_file.stat().st_size == 0:
            missing.append(f".b{plan_num}")
        if not x_file.exists() or x_file.stat().st_size == 0:
            missing.append(f".x{geometry_number}")

        if missing:
            return make_result(
                success=False, plan_number=plan_num,
                geometry_number=geometry_number,
                signal_source=signal_source,
                full_result_copied=full_result_copied,
                error=f"Preprocessing did not generate: {', '.join(missing)}",
                elapsed_seconds=time.time() - start_time,
            )

        if requires_gridded_precipitation:
            materialized, detail = (
                RasPreprocess._validate_materialized_gridded_precipitation(
                    tmp_hdf
                )
            )
            if not materialized:
                return make_result(
                    success=False,
                    plan_number=plan_num,
                    geometry_number=geometry_number,
                    tmp_hdf_path=tmp_hdf,
                    b_file_path=b_file,
                    x_file_path=x_file,
                    signal_source=signal_source,
                    full_result_copied=full_result_copied,
                    error=(
                        "Gridded precipitation is configured, but HEC-RAS "
                        "preprocessing did not create structurally materialized "
                        f"precipitation in {tmp_hdf.name}: {detail}. Imported "
                        "Raster Data alone is not solver-ready."
                    ),
                    elapsed_seconds=time.time() - start_time,
                )
            if require_linux_solver_ready:
                solver_ready, detail = (
                    RasPreprocess._validate_completed_gridded_preprocessing(
                        tmp_hdf
                    )
                )
                if not solver_ready:
                    return make_result(
                        success=False,
                        plan_number=plan_num,
                        geometry_number=geometry_number,
                        tmp_hdf_path=tmp_hdf,
                        b_file_path=b_file,
                        x_file_path=x_file,
                        signal_source=signal_source,
                        full_result_copied=full_result_copied,
                        error=(
                            "Gridded precipitation is configured, but HEC-RAS "
                            "preprocessing did not create a completed Linux "
                            f"solver-ready temporary HDF in {tmp_hdf.name}: {detail}. "
                            "Imported Raster Data or partial interpolation mappings "
                            "alone are not solver-ready."
                        ),
                        elapsed_seconds=time.time() - start_time,
                    )

        # Read only after owned writers have stopped, including natural exits.
        # Non-empty prerequisite files alone do not prove completed event data.
        try:
            import h5py
            from ._preprocess_validation import _event_condition_errors
            from ._preprocess_validation import _hdf_ras_major_version

            with h5py.File(tmp_hdf, "r") as hdf:
                event_errors = _event_condition_errors(hdf, precipitation_mode)
                ras_major = _hdf_ras_major_version(hdf)
            hdf_readable = True
            compatibility_errors = []
            if ras_major is not None and ras_major < 6:
                c_file = project_folder / f"{project_name}.c{geometry_number}"
                if not c_file.is_file() or c_file.stat().st_size == 0:
                    compatibility_errors.append(
                        f"HEC-RAS {ras_major}.x preprocessing did not write {c_file.name}"
                    )
        except Exception as exc:
            from .fast_hdf import reraise_required

            reraise_required(exc)
            event_errors = [f"could not validate Event Conditions: {exc}"]
            hdf_readable = False
            compatibility_errors = []

        repair_attempts: List[Dict[str, Any]] = []
        repair_note = None
        if (
            event_errors
            and precipitation_mode == "point"
            and int(precipitation_repair_attempts or 0) > 0
            and hdf_readable
            and not full_result_copied
            and RasPreprocess._preprocessing_artifacts_ready(tmp_hdf, b_file, x_file)
        ):
            repaired, repair_attempts, repair_errors, repair_note = (
                RasPreprocess._repair_point_precipitation(
                    ras_exe=Path(ras_exe),
                    project_folder=project_folder,
                    project_name=project_name,
                    prj_file=prj_file,
                    plan_file=plan_file,
                    tmp_hdf=tmp_hdf,
                    precipitation_mode=precipitation_mode,
                    max_attempts=int(precipitation_repair_attempts),
                    timeout_seconds=(
                        max_wait
                        if precipitation_repair_timeout is None
                        else precipitation_repair_timeout
                    ),
                )
            )
            if repaired:
                logger.info(
                    "Point precipitation for plan %s completed by "
                    "CompletePreProcess repair attempt %d (initial signal: %s)",
                    plan_num,
                    len(repair_attempts),
                    signal_source,
                )
                event_errors = []
                signal_source = "completepreprocess_repair"
            elif repair_attempts:
                event_errors = repair_errors or event_errors

        validation_errors = [*event_errors, *compatibility_errors]
        if validation_errors:
            error = "Preprocessing is incomplete: " + "; ".join(validation_errors)
            if repair_attempts:
                error += ". " + RasPreprocess._describe_failed_repair(
                    repair_attempts, repair_note
                )
            elif repair_note:
                error += f". Point-precipitation repair not attempted: {repair_note}"
            return make_result(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                tmp_hdf_path=tmp_hdf,
                b_file_path=b_file,
                x_file_path=x_file,
                signal_source=signal_source,
                full_result_copied=full_result_copied,
                error=error,
                elapsed_seconds=time.time() - start_time,
                precipitation_repair_attempts=repair_attempts,
            )

        # Fix line endings on .x file for Linux compatibility
        if fix_line_endings:
            RasPreprocess._fix_x_file_line_endings(x_file)

        elapsed = time.time() - start_time
        logger.info(
            "Preprocessing complete for plan %s in %.1fs: tmp.hdf=%.1fMB, b=%.0fKB, x=%.0fKB",
            plan_num,
            elapsed,
            tmp_hdf.stat().st_size / 1024 / 1024,
            b_file.stat().st_size / 1024,
            x_file.stat().st_size / 1024,
        )
        logger.debug(
            "Generated preprocessing files for plan %s: tmp_hdf=%s, b_file=%s, x_file=%s",
            plan_num,
            tmp_hdf,
            b_file,
            x_file,
        )

        return make_result(
            success=True,
            plan_number=plan_num,
            geometry_number=geometry_number,
            tmp_hdf_path=tmp_hdf,
            b_file_path=b_file,
            x_file_path=x_file,
            elapsed_seconds=elapsed,
            signal_source=signal_source,
            full_result_copied=full_result_copied,
            precipitation_repair_attempts=repair_attempts,
        )

    @staticmethod
    def _read_event_condition_errors(
        tmp_hdf: Path,
        precipitation_mode: Optional[str],
    ) -> Tuple[List[str], bool]:
        """Validate Event Conditions in a writer-free temporary HDF.

        Returns the problems and whether the HDF could be opened at all.
        """
        try:
            import h5py
            from ._preprocess_validation import _event_condition_errors

            with h5py.File(tmp_hdf, "r") as hdf:
                return list(_event_condition_errors(hdf, precipitation_mode)), True
        except Exception as exc:
            from .fast_hdf import reraise_required

            reraise_required(exc)
            return [f"could not validate Event Conditions: {exc}"], False

    @staticmethod
    def _repair_point_precipitation(
        *,
        ras_exe: Path,
        project_folder: Path,
        project_name: str,
        prj_file: Path,
        plan_file: Path,
        tmp_hdf: Path,
        precipitation_mode: str,
        max_attempts: int,
        timeout_seconds: float,
    ) -> Tuple[bool, List[Dict[str, Any]], List[str], Optional[str]]:
        """Re-run ``RasProcess.exe CompletePreProcess`` until Event Conditions validate.

        HEC-RAS's ``PointPrecipitationLayer`` can write no point precipitation
        for identical inputs ("No valid precipitation time-series data found
        for this time-window"). A fresh ``CompletePreProcess`` process on the
        same temporary HDF writes it on a later attempt. The gauge DSS paths
        in the HDF are relative (``.\\Hydrology\\<file>.dss``) and resolve
        against the process working directory, so each attempt runs from the
        project folder.

        Returns ``(repaired, attempts, last_validation_errors, note)``. ``note``
        explains why no attempt ran, or why attempts stopped before
        ``max_attempts``.
        """
        rasprocess = Path(ras_exe).parent / "RasProcess.exe"
        rasmap = Path(project_folder) / f"{project_name}.rasmap"
        if not rasprocess.is_file():
            return False, [], [], f"{rasprocess.name} not found beside {Path(ras_exe).name}"
        if not rasmap.is_file():
            return False, [], [], f"project file {rasmap.name} not found"

        attempts: List[Dict[str, Any]] = []
        errors: List[str] = []
        for attempt in range(1, int(max_attempts) + 1):
            logger.warning(
                "Event Conditions incomplete in %s; re-running RasProcess.exe "
                "CompletePreProcess (attempt %d of %d)",
                tmp_hdf.name,
                attempt,
                max_attempts,
            )
            attempt_started = time.time()
            run = RasPreprocess._run_completepreprocess(
                rasprocess,
                rasmap,
                tmp_hdf,
                working_dir=Path(project_folder),
                timeout_seconds=timeout_seconds,
            )
            stop_reason = run["error"]
            _stopped, surviving = RasPreprocess._terminate_exact_preprocess_residue(
                project_file=prj_file,
                plan_file=plan_file,
                tmp_hdf=tmp_hdf,
                started_at=attempt_started,
            )
            if surviving:
                stop_reason = (
                    "CompletePreProcess processes remained active after cleanup: "
                    + ", ".join(str(pid) for pid in surviving)
                )
                errors = [stop_reason]
            else:
                errors, _readable = RasPreprocess._read_event_condition_errors(
                    tmp_hdf, precipitation_mode
                )
            output = run["output"]
            record = {
                "attempt": attempt,
                "return_code": run["return_code"],
                "elapsed_seconds": round(time.time() - attempt_started, 1),
                "no_valid_precipitation": (
                    "no valid precipitation" in output.casefold()
                ),
                "validation_errors": list(errors),
                "timed_out": run["timed_out"],
                "error": stop_reason,
            }
            attempts.append(record)
            if stop_reason is None and not errors and run["return_code"] == 0:
                return True, attempts, [], None
            if stop_reason is not None:
                return False, attempts, errors, stop_reason
        return False, attempts, errors, None

    @staticmethod
    def _run_completepreprocess(
        rasprocess: Path,
        rasmap: Path,
        tmp_hdf: Path,
        *,
        working_dir: Path,
        timeout_seconds: float,
    ) -> Dict[str, Any]:
        """Run one owned ``RasProcess.exe CompletePreProcess`` to completion.

        Uses an argument vector, file-backed output (no pipe can fill while
        polling) and the same scoped legal-dialog check and process-tree
        termination as the Ras.exe launch. ``preprocess_plan`` already requires
        Windows-hosted Python, including Windows Python under Wine, so
        ``RasProcess.exe`` is launched directly.
        """
        import tempfile

        command = [str(rasprocess), "CompletePreProcess", str(rasmap), str(tmp_hdf)]
        result: Dict[str, Any] = {
            "return_code": None,
            "output": "",
            "timed_out": False,
            "error": None,
        }
        with tempfile.TemporaryFile(
            mode="w+", encoding="utf-8", errors="replace"
        ) as output_file:
            try:
                process = subprocess.Popen(
                    command,
                    cwd=str(working_dir),
                    stdout=output_file,
                    stderr=subprocess.STDOUT,
                    shell=False,
                )
            except OSError as exc:
                result["error"] = f"could not launch {Path(rasprocess).name}: {exc}"
                return result

            deadline = time.monotonic() + max(float(timeout_seconds), 1.0)
            while process.poll() is None:
                blocked = RasPreprocess._detect_first_run_tcu_dialog(process.pid)
                if blocked and process.poll() is None:
                    RasPreprocess._terminate_process_tree(process)
                    result["error"] = blocked
                    break
                if time.monotonic() >= deadline:
                    RasPreprocess._terminate_process_tree(process)
                    result["timed_out"] = True
                    result["error"] = (
                        "CompletePreProcess timed out after "
                        f"{int(timeout_seconds)} seconds"
                    )
                    break
                time.sleep(0.5)

            result["return_code"] = process.poll()
            try:
                output_file.seek(0)
                result["output"] = output_file.read()
            except (OSError, ValueError):
                pass
        return result

    @staticmethod
    def _describe_failed_repair(
        attempts: List[Dict[str, Any]],
        stop_note: Optional[str],
    ) -> str:
        """Summarize unsuccessful CompletePreProcess repair attempts for an error."""
        details = []
        for record in attempts:
            detail = f"attempt {record['attempt']}: exit {record['return_code']}"
            if record.get("no_valid_precipitation"):
                detail += ", 'No valid precipitation' reported"
            if record.get("error"):
                detail += f", {record['error']}"
            details.append(detail)
        summary = (
            f"Re-running RasProcess.exe CompletePreProcess {len(attempts)} "
            f"time(s) did not complete point precipitation ({'; '.join(details)})"
        )
        if stop_note:
            summary += f". Repair stopped early: {stop_note}"
        return summary

    @staticmethod
    @log_call
    def run_ras_geom_preprocess(
        plan_number: Union[str, Number],
        ras_object=None,
        input_hdf_path: Optional[Union[str, Path]] = None,
        x_file_path: Optional[Union[str, Path]] = None,
        executable_path: Optional[Union[str, Path]] = None,
        timeout_sec: int = 300,
        require_hdf_change: bool = False,
    ) -> GeometryPreprocessResult:
        """Run vendor ``RasGeomPreprocess.exe`` for one staged plan.

        :meth:`preprocess_plan` creates the plan ``*.tmp.hdf`` and geometry
        ``.x##`` inputs. This method executes the matching standalone geometry
        preprocessor using an argument vector, enforces a bounded timeout, and
        records executable and before/after HDF fingerprints. It is intended for
        Windows Python, including Windows Python hosted by Wine.

        Args:
            plan_number: Plan number (for example ``"06"``).
            ras_object (RasPrj, optional): Initialized :class:`RasPrj`; defaults to the global project.
            input_hdf_path: Optional explicit plan ``*.tmp.hdf`` input.
            x_file_path: Optional explicit project ``.x##`` file.
            executable_path: Optional explicit ``RasGeomPreprocess.exe`` path.
                The default is the ``x64`` directory beside ``Ras.exe``.
            timeout_sec: Maximum execution time in seconds.
            require_hdf_change: Require the input HDF fingerprint to change.
                Leave False for idempotent reruns; qualification of a fresh input
                should set this to True.

        Returns:
            GeometryPreprocessResult: Bool-compatible execution evidence.
        """
        start_time = time.time()
        ras_obj = ras_object if ras_object is not None else ras

        if isinstance(plan_number, Number):
            plan_num = f"{int(plan_number):02d}"
        else:
            plan_num = str(plan_number).zfill(2)

        try:
            ras_obj.check_initialized()
        except Exception as e:
            return GeometryPreprocessResult(
                success=False,
                plan_number=plan_num,
                error=f"Project not initialized: {e}",
                elapsed_seconds=time.time() - start_time,
            )

        project_folder = Path(ras_obj.project_folder)
        project_name = ras_obj.project_name
        plan_path = project_folder / f"{project_name}.p{plan_num}"
        geometry_number = None
        try:
            plan_row = ras_obj.plan_df[ras_obj.plan_df["plan_number"] == plan_num]
            if not plan_row.empty and "Geom File" in plan_row.columns:
                match = re.search(r"(\d+)", str(plan_row["Geom File"].iloc[0]))
                if match:
                    geometry_number = match.group(1)
        except Exception:
            pass
        if geometry_number is None and plan_path.is_file():
            geometry_number = RasPreprocess._extract_geometry_number(plan_path)
        if geometry_number is None:
            return GeometryPreprocessResult(
                success=False,
                plan_number=plan_num,
                error=f"Could not determine geometry number for plan {plan_num}",
                elapsed_seconds=time.time() - start_time,
            )

        input_hdf = (
            Path(input_hdf_path)
            if input_hdf_path is not None
            else project_folder / f"{project_name}.p{plan_num}.tmp.hdf"
        )
        x_file = (
            Path(x_file_path)
            if x_file_path is not None
            else project_folder / f"{project_name}.x{geometry_number}"
        )
        if executable_path is None:
            ras_exe_path = Path(str(getattr(ras_obj, "ras_exe_path", "")))
            executable = ras_exe_path.parent / "x64" / "RasGeomPreprocess.exe"
        else:
            executable = Path(executable_path)

        missing = [
            str(path)
            for path in (executable, input_hdf, x_file)
            if not path.is_file() or path.stat().st_size == 0
        ]
        if missing:
            return GeometryPreprocessResult(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                executable_path=executable,
                input_hdf_path=input_hdf,
                x_file_path=x_file,
                error=(
                    "Missing or empty geometry-preprocessor input: "
                    + ", ".join(missing)
                ),
                elapsed_seconds=time.time() - start_time,
            )

        expected_x_name = f"{project_name}.x{geometry_number}".casefold()
        try:
            same_parent = x_file.parent.resolve() == input_hdf.parent.resolve()
        except OSError:
            same_parent = x_file.parent.absolute() == input_hdf.parent.absolute()
        if not same_parent or x_file.name.casefold() != expected_x_name:
            return GeometryPreprocessResult(
                success=False,
                plan_number=plan_num,
                geometry_number=geometry_number,
                executable_path=executable,
                input_hdf_path=input_hdf,
                x_file_path=x_file,
                error=(
                    "RasGeomPreprocess requires the project execution file "
                    f"{project_name}.x{geometry_number} beside the input HDF"
                ),
                elapsed_seconds=time.time() - start_time,
            )

        executable_sha256 = RasPreprocess._file_sha256(executable)
        before_sha256 = RasPreprocess._file_sha256(input_hdf)
        command = [str(executable), str(input_hdf), f"x{geometry_number}"]
        command_text = subprocess.list2cmdline(command)
        process = None
        stdout = ""
        stderr = ""
        timed_out = False
        launch_error = None

        try:
            process = subprocess.Popen(
                command,
                cwd=str(input_hdf.parent),
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding="utf-8",
                errors="replace",
            )
            try:
                stdout, stderr = process.communicate(timeout=int(timeout_sec))
            except subprocess.TimeoutExpired:
                timed_out = True
                RasPreprocess._terminate_process_tree(process)
                try:
                    stdout, stderr = process.communicate(timeout=2)
                except Exception:
                    stdout, stderr = "", ""
        except OSError as e:
            launch_error = str(e)

        after_sha256 = (
            RasPreprocess._file_sha256(input_hdf)
            if input_hdf.is_file() and input_hdf.stat().st_size > 0
            else None
        )
        output_changed = bool(
            before_sha256 and after_sha256 and before_sha256 != after_sha256
        )
        return_code = process.returncode if process is not None else None

        hdf_readable = False
        geometry_group_present = False
        hdf_error = None
        if after_sha256 is not None:
            try:
                import h5py

                with h5py.File(input_hdf, "r") as handle:
                    hdf_readable = True
                    geometry_group_present = "Geometry" in handle
            except Exception as e:
                hdf_error = str(e)

        errors = []
        if launch_error:
            errors.append(f"Could not launch RasGeomPreprocess: {launch_error}")
        if timed_out:
            errors.append(
                f"RasGeomPreprocess timed out after {int(timeout_sec)} seconds"
            )
        if return_code is None:
            errors.append("RasGeomPreprocess did not report a final return code")
        elif return_code != 0:
            errors.append(f"RasGeomPreprocess exited with code {return_code}")
        if after_sha256 is None:
            errors.append("RasGeomPreprocess did not leave a non-empty input HDF")
        elif not hdf_readable:
            errors.append(f"RasGeomPreprocess output HDF is unreadable: {hdf_error}")
        elif not geometry_group_present:
            errors.append("RasGeomPreprocess output HDF has no Geometry group")
        if require_hdf_change and not output_changed:
            errors.append("RasGeomPreprocess did not change the input HDF fingerprint")

        combined_output = "\n".join(item for item in (stdout, stderr) if item)
        from .results import ResultsParser

        parsed = ResultsParser.parse_compute_messages(combined_output)
        operational_error_count = len(errors)
        if parsed["has_errors"]:
            errors.append(
                "RasGeomPreprocess reported an error: "
                f"{parsed['first_error_line']}"
            )

        return GeometryPreprocessResult(
            success=not errors,
            plan_number=plan_num,
            geometry_number=geometry_number,
            elapsed_seconds=time.time() - start_time,
            command=command_text,
            return_code=return_code,
            executable_path=executable,
            executable_sha256=executable_sha256,
            input_hdf_path=input_hdf,
            x_file_path=x_file,
            input_hdf_sha256_before=before_sha256,
            input_hdf_sha256_after=after_sha256,
            output_changed=output_changed,
            hdf_readable=hdf_readable,
            geometry_group_present=geometry_group_present,
            timed_out=timed_out,
            stdout=stdout or "",
            stderr=stderr or "",
            artifact_paths=[input_hdf, x_file],
            error_count=operational_error_count + parsed["error_count"],
            warning_count=parsed["warning_count"],
            first_error_line=parsed["first_error_line"],
            error="; ".join(errors) if errors else None,
        )

    @staticmethod
    @log_call
    def verify_preprocessing(
        plan_number: Union[str, Number],
        ras_object=None,
    ) -> bool:
        """
        Check if prerequisite files for Linux execution exist.

        Verifies that .tmp.hdf, .b##, and .x## files exist and are non-empty.
        Useful before calling ``RasCmdr.compute_plan_linux()``.

        Args:
            plan_number: Plan number to check (e.g., "01", 1).
            ras_object (RasPrj, optional): Optional RasPrj instance. If None, uses global ras.

        Returns:
            bool: True if all three files exist and are non-empty.

        Example:
            >>> if RasPreprocess.verify_preprocessing("01"):
            ...     RasCmdr.compute_plan_linux("01", ras_exe_dir="/opt/hecras/6.6")
            ... else:
            ...     RasPreprocess.preprocess_plan("01")
        """
        ras_obj = ras_object if ras_object is not None else ras

        if isinstance(plan_number, Number):
            plan_num = f"{int(plan_number):02d}"
        else:
            plan_num = str(plan_number).zfill(2)

        try:
            ras_obj.check_initialized()
        except Exception:
            return False

        project_folder = Path(ras_obj.project_folder)
        project_name = ras_obj.project_name

        # Determine geometry number
        geometry_number = None
        try:
            plan_row = ras_obj.plan_df[ras_obj.plan_df['plan_number'] == plan_num]
            if not plan_row.empty and 'Geom File' in plan_row.columns:
                geom_ref = str(plan_row['Geom File'].iloc[0])
                m = re.search(r'(\d+)', geom_ref)
                if m:
                    geometry_number = m.group(1)
        except Exception:
            pass

        if geometry_number is None:
            plan_path = RasPlan.get_plan_path(plan_num, ras_obj)
            if plan_path:
                geometry_number = RasPreprocess._extract_geometry_number(Path(plan_path))
            if geometry_number is None:
                return False

        tmp_hdf = project_folder / f"{project_name}.p{plan_num}.tmp.hdf"
        b_file = project_folder / f"{project_name}.b{plan_num}"
        x_file = project_folder / f"{project_name}.x{geometry_number}"

        for f in [tmp_hdf, b_file, x_file]:
            if not f.exists() or f.stat().st_size == 0:
                logger.debug(f"Missing or empty: {f.name}")
                return False

        logger.debug("All preprocessing files verified for plan %s", plan_num)
        return True

    @staticmethod
    def _extract_geometry_number(plan_path: Path) -> Optional[str]:
        """
        Extract geometry number from a plan file.

        Parses the ``Geom File=g##`` line in a HEC-RAS plan file.

        Args:
            plan_path: Path to the plan file (.p##).

        Returns:
            Geometry number as string (e.g., "04"), or None if not found.
        """
        try:
            content = plan_path.read_text(encoding='utf-8', errors='ignore')
            for line in content.splitlines():
                if line.strip().startswith("Geom File="):
                    geom_ref = line.split('=', 1)[1].strip()
                    m = re.search(r'(\d+)', geom_ref)
                    if m:
                        return m.group(1)
        except Exception as e:
            logger.debug(f"Could not read geometry number from {plan_path}: {e}")
        return None

    @staticmethod
    def _file_sha256(path: Path) -> str:
        """Return a streaming SHA-256 digest for a preprocessing artifact."""
        digest = hashlib.sha256()
        with Path(path).open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()

    @staticmethod
    def _artifact_state(path: Path) -> Optional[Tuple[int, int]]:
        """Return a size/mtime fingerprint, or None when an artifact is absent."""
        try:
            stat = Path(path).stat()
        except OSError:
            return None
        return stat.st_size, stat.st_mtime_ns

    @staticmethod
    def _normalized_preprocess_path(value: object) -> str:
        """Normalize a command-line path for exact process ownership checks."""
        text = str(value).strip().strip('"')
        try:
            return os.path.normcase(os.path.abspath(text))
        except (OSError, ValueError):
            return os.path.normcase(text)

    @staticmethod
    def _is_exact_complete_preprocess_process(
        info: Dict[str, object],
        tmp_hdf: Path,
        started_at: float,
    ) -> bool:
        """Match this launch's event writer, including older runtime verbs."""
        try:
            if float(info.get("create_time") or 0.0) < float(started_at) - 2.0:
                return False
            if str(info.get("name") or "").casefold() != "rasprocess.exe":
                return False
            arguments = tuple(info.get("cmdline") or ())
        except (TypeError, ValueError):
            return False
        return (
            bool({"completepreprocess", "completeeventconditions"} & {
                str(argument).strip().casefold() for argument in arguments
            })
            and RasPreprocess._normalized_preprocess_path(tmp_hdf)
            in {
                RasPreprocess._normalized_preprocess_path(argument)
                for argument in arguments
            }
        )

    @staticmethod
    def _preprocess_process_inventory() -> Optional[List[Tuple[object, Dict[str, object]]]]:
        """Inspect RAS candidates without querying unrelated command lines.

        ``None`` means ownership could not be established. Callers must refuse
        handoff and artifact inspection in that case. A process which vanished
        while being queried is harmless; an unreadable name or RAS candidate
        is not evidence of absence.
        """
        try:
            import psutil

            candidates = []
            # On Wine, prefetching every process's command line can raise
            # OSError(87) in the iterator itself, before its body runs.
            for candidate in psutil.process_iter(["pid", "name"]):
                try:
                    info = dict(candidate.info)
                    name = info.get("name")
                    if not isinstance(name, str) or not name.strip():
                        # Windows kernel minimal processes ("Secure System" under
                        # virtualization-based security, "Memory Compression")
                        # report no image name. Their parent is the kernel
                        # (PID 0 or 4); they cannot be a RAS engine.
                        if os.name == "nt" and candidate.ppid() in (0, 4):
                            continue
                        from ._process_inspection import _recover_empty_process_name

                        name, recovered_created = _recover_empty_process_name(
                            candidate, int(info["pid"]), psutil,
                        )
                        info.update(name=name, create_time=recovered_created)
                    if name.casefold() not in {"ras.exe", "rasprocess.exe"}:
                        continue
                    # Reuse explicitly cached fields when available. Normally
                    # process_iter above supplies only PID and name.
                    arguments = (
                        info["cmdline"] if "cmdline" in info else candidate.cmdline()
                    )
                    created = float(
                        info["create_time"]
                        if "create_time" in info else candidate.create_time()
                    )
                    pid = int(info["pid"])
                    if (
                        pid <= 0 or not 0.0 < created < float("inf")
                        or not isinstance(arguments, (list, tuple))
                        or not arguments
                        or any(not isinstance(argument, str) for argument in arguments)
                    ):
                        raise ValueError("RAS process identity is incomplete")
                    info.update(cmdline=arguments, create_time=created, pid=pid)
                    candidates.append((candidate, info))
                except psutil.NoSuchProcess:
                    continue
            return candidates
        except Exception as exc:
            logger.warning("Could not establish preprocessing process ownership: %s", exc)
            return None

    @staticmethod
    def _active_complete_preprocess_writers(
        tmp_hdf: Path,
        started_at: float,
    ) -> Tuple[int, ...]:
        """Return exact launch-owned native event-writer PIDs.

        HDF size/mtime stability alone cannot prove that the detached Windows
        writer is done.  This intentionally excludes similarly named RAS
        processes and only reports a process with the exact temporary HDF,
        ``CompletePreProcess`` or ``CompleteEventConditions`` action, and
        launch-window creation time. CompleteGeometry is not an event writer.
        """
        processes = RasPreprocess._preprocess_process_inventory()
        if processes is None:
            return (-1,)
        writers = []
        for _candidate, info in processes:
            if RasPreprocess._is_exact_complete_preprocess_process(
                info, tmp_hdf, started_at,
            ):
                writers.append(int(info["pid"]))
        return tuple(sorted(set(writers)))

    @staticmethod
    def _detect_first_run_tcu_dialog(
        root_pid: Optional[int] = None,
    ) -> Optional[str]:
        """Return a diagnostic for a TCU modal in one launched process tree."""
        try:
            titles = RasPreprocess._get_visible_window_titles(root_pid=root_pid)
        except Exception as e:
            return f"{RasPreprocess._TCU_SUPERVISION_ERROR} Detail: {e}"
        for title in titles:
            reason = legal_dialog_blocking_reason(title=title)
            if reason:
                return reason
        return None

    _LAND_CLASSIFICATION_ASSOCIATIONS = (
        ("landcover", "land cover (Manning's n)"),
        ("infiltration", "infiltration"),
        ("sediment_soils", "sediment bed material"),
    )

    @staticmethod
    def _skips_geometry_without_land_classification(ras_exe: Union[str, Path]) -> bool:
        """Return whether this HEC-RAS release skips the geometry when a
        referenced land-classification file is missing.

        6.0-6.2 do; 6.3 and later still preprocess the mesh. The release is read
        from the install folder name (e.g. ``...\\HEC-RAS\\6.2\\Ras.exe``); when it
        cannot be determined, the check is applied.
        """
        match = re.search(r"(\d+)\.(\d+)", Path(str(ras_exe)).parent.name)
        if match is None:
            return True
        return (int(match.group(1)), int(match.group(2))) < (6, 3)

    @staticmethod
    def _missing_land_classification_files(geom_hdf: Path) -> List[str]:
        """Describe land-classification files the geometry HDF references but that do not exist.

        Returns an empty list when the geometry HDF is absent or unreadable;
        HEC-RAS then compiles the geometry from text and this check does not apply.
        """
        if not geom_hdf.is_file():
            return []
        try:
            from ._geometry_association import read_geometry_association

            association = read_geometry_association(geom_hdf)
        except Exception as exc:
            from .fast_hdf import reraise_required

            # Required-native mode must not pass the pre-launch guard on a refusal.
            reraise_required(exc)
            logger.debug(f"Could not read associations from {geom_hdf.name}: {exc}")
            return []

        missing = []
        for key, label in RasPreprocess._LAND_CLASSIFICATION_ASSOCIATIONS:
            resolved = association.get(f"{key}_hdf_path")
            if resolved and not Path(resolved).is_file():
                raw = association.get(f"{key}_raw_filename")
                missing.append(f"{label} '{raw}' (resolved to {resolved})")
        return missing

    @staticmethod
    def _owned_tcu_ras_process(
        launcher_pid: int,
        launcher_create_time: float,
        ras_exe: Union[str, Path],
    ) -> Tuple[int, float]:
        """Select one witnessed exact-runtime descendant of the Python launcher."""
        import psutil

        root = psutil.Process(launcher_pid)
        if float(root.create_time()) != launcher_create_time:
            raise RuntimeError("Preprocessing launcher PID was reused")
        expected_name = ntpath.basename(str(ras_exe)).casefold()
        normalize = lambda value: ntpath.normcase(ntpath.normpath(str(value)))
        expected_exe = normalize(ras_exe)
        matches = []
        for candidate in root.children(recursive=True):
            try:
                name = candidate.name()
                if not isinstance(name, str) or not name:
                    raise RuntimeError("A launcher descendant name is unavailable")
                if name.casefold() != expected_name:
                    continue
                created = float(candidate.create_time())
                if not launcher_create_time <= created < float("inf"):
                    raise RuntimeError("RAS descendant creation time is inconsistent")
                fresh = psutil.Process(candidate.pid)
                if float(fresh.create_time()) != created:
                    raise RuntimeError("RAS descendant PID was reused")
                if normalize(fresh.exe()) != expected_exe:
                    continue
                # children() witnesses ancestry; a second live parent-chain
                # query must still bind the exact child to this exact launcher.
                if not any(
                    parent.pid == launcher_pid
                    and float(parent.create_time()) == launcher_create_time
                    for parent in fresh.parents()
                ):
                    raise RuntimeError("RAS descendant ancestry changed")
                if float(psutil.Process(candidate.pid).create_time()) != created:
                    raise RuntimeError("RAS descendant PID changed during ancestry inspection")
                matches.append((int(candidate.pid), created))
            except psutil.NoSuchProcess:
                continue
        if float(psutil.Process(launcher_pid).create_time()) != launcher_create_time:
            raise RuntimeError("Preprocessing launcher identity changed")
        if len(matches) != 1:
            raise RuntimeError("Expected exactly one witnessed exact-runtime RAS descendant")
        return matches[0]

    @staticmethod
    def _preprocessing_tcu_probe(
        process,
        *,
        accept_tcu: bool,
        launch_create_time: Optional[float],
        ras_exe: Union[str, Path],
        deadline: float,
        receipts: list,
        acceptance_state: dict,
    ) -> Optional[str]:
        """Keep default blocking; allow one explicitly authorized owned action."""
        reason = RasPreprocess._detect_running_tcu_dialog(process)
        if not accept_tcu or reason != RasPreprocess._TCU_BLOCKING_ERROR:
            return reason
        if acceptance_state.get("attempted"):
            return reason + " The TCU dialog remained after explicit acceptance."
        acceptance_state["attempted"] = True
        audit = {
            "preprocess_launcher_pid": process.pid,
            "preprocess_launcher_create_time": launch_create_time,
            "executable": str(ras_exe), "operator_acceptance": True,
        }
        try:
            if launch_create_time is None or not 0 < launch_create_time < float("inf"):
                raise RuntimeError("Exact preprocessing launcher creation time is unavailable")
            remaining = float(deadline) - time.monotonic()
            if not 0 < remaining < float("inf"):
                raise TimeoutError("No bounded preprocessing time remains for TCU acceptance")
            from .RasTcu import RasTcu

            ras_pid, ras_created = RasPreprocess._owned_tcu_ras_process(
                process.pid, launch_create_time, ras_exe,
            )
            # Scope inspection consumes time too; never extend the caller's
            # preprocessing limit to make room for a legal-dialog action.
            remaining = float(deadline) - time.monotonic()
            if not 0 < remaining < float("inf"):
                raise TimeoutError("Preprocessing time expired during TCU ownership inspection")
            audit.update(ras_pid=ras_pid, ras_create_time=ras_created)
            audit["requested_timeout_seconds"] = remaining
            receipt = RasTcu.accept_running_terms(
                ras_pid, expected_create_time=ras_created,
                ras_version=str(ras_exe), operator_acceptance=True, timeout=remaining,
            )
            if not isinstance(receipt, dict):
                raise RuntimeError("Owned TCU acceptance returned no action receipt")
            audit.update(receipt)
            if receipt.get("dialog_closed") is not True:
                raise RuntimeError("Owned TCU wizard closure was not verified")
            audit["success"] = True
            receipts.append(audit)
            logger.info("Explicit preprocessing TCU acceptance receipt: %s", audit)
            return None
        except Exception as exc:
            audit.update(success=False, error=str(exc))
            receipts.append(audit)
            logger.warning("Explicit preprocessing TCU acceptance failed: %s", audit)
            return reason + f" Explicit owned TCU acceptance failed: {exc}"

    @staticmethod
    def _detect_running_tcu_dialog(process) -> Optional[str]:
        """Retain scoped supervision while the owned launcher is alive.

        The launcher can exit between BcoMonitor's poll and window enumeration.
        A scope-query failure in that race is not evidence of a legal dialog.
        Natural-exit cleanup and artifact validation still run; live query
        failures and any actually detected legal dialog remain blocking.
        """
        if process.poll() is not None:
            return None
        reason = RasPreprocess._detect_first_run_tcu_dialog(process.pid)
        if (
            reason and reason.startswith(RasPreprocess._TCU_SUPERVISION_ERROR)
            and process.poll() is not None
        ):
            logger.debug("Preprocessing launcher exited during scoped TCU inspection")
            return None
        return reason

    @staticmethod
    def _tcu_supervision_availability_error() -> Optional[str]:
        """Return a prelaunch diagnostic when scoped TCU detection is unavailable."""
        if os.name != "nt":
            return (
                f"{RasPreprocess._TCU_SUPERVISION_ERROR} "
                "A Windows-hosted Python process is required for this Ras.exe path."
            )
        try:
            import psutil  # noqa: F401
        except Exception as e:
            return (
                f"{RasPreprocess._TCU_SUPERVISION_ERROR} "
                f"psutil is unavailable: {e}"
            )
        return None

    @staticmethod
    def _get_visible_window_titles(
        root_pid: Optional[int] = None,
    ) -> List[str]:
        """Enumerate visible titles, optionally scoped to one process tree."""
        if os.name != "nt":
            return []

        try:
            import ctypes
            from ctypes import wintypes

            allowed_pids = None
            if root_pid is not None:
                allowed_pids = {int(root_pid)}
                try:
                    import psutil

                    root = psutil.Process(int(root_pid))
                    allowed_pids.update(
                        child.pid for child in root.children(recursive=True)
                    )
                except Exception as e:
                    raise RuntimeError(
                        "Could not enumerate descendants for TCU window scope "
                        f"PID {root_pid}: {e}"
                    ) from e

            user32 = ctypes.WinDLL("user32", use_last_error=True)
            enum_windows_proc = ctypes.WINFUNCTYPE(
                wintypes.BOOL,
                wintypes.HWND,
                wintypes.LPARAM,
            )
            user32.EnumWindows.argtypes = [enum_windows_proc, wintypes.LPARAM]
            user32.EnumWindows.restype = wintypes.BOOL
            user32.IsWindowVisible.argtypes = [wintypes.HWND]
            user32.IsWindowVisible.restype = wintypes.BOOL
            user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
            user32.GetWindowTextLengthW.restype = ctypes.c_int
            user32.GetWindowTextW.argtypes = [
                wintypes.HWND,
                wintypes.LPWSTR,
                ctypes.c_int,
            ]
            user32.GetWindowTextW.restype = ctypes.c_int
            user32.GetWindowThreadProcessId.argtypes = [
                wintypes.HWND,
                ctypes.POINTER(wintypes.DWORD),
            ]
            user32.GetWindowThreadProcessId.restype = wintypes.DWORD

            titles: List[str] = []

            @enum_windows_proc
            def collect_title(hwnd, _lparam):
                if not user32.IsWindowVisible(hwnd):
                    return True
                if allowed_pids is not None:
                    window_pid = wintypes.DWORD()
                    user32.GetWindowThreadProcessId(
                        hwnd,
                        ctypes.byref(window_pid),
                    )
                    if int(window_pid.value) not in allowed_pids:
                        return True
                length = user32.GetWindowTextLengthW(hwnd)
                if length <= 0:
                    return True
                buffer = ctypes.create_unicode_buffer(length + 1)
                if user32.GetWindowTextW(hwnd, buffer, length + 1):
                    title = buffer.value.strip()
                    if title:
                        titles.append(title)
                return True

            user32.EnumWindows(collect_title, 0)
            return titles
        except Exception as e:
            if root_pid is not None:
                raise RuntimeError(
                    f"Could not enumerate scoped visible window titles: {e}"
                ) from e
            logger.debug(f"Could not enumerate visible window titles: {e}")
            return []

    @staticmethod
    def _plan_uses_gridded_precipitation(
        plan_file: Path,
        project_folder: Path,
        project_name: str,
    ) -> bool:
        """Return whether a plan's active unsteady file enables gridded rain."""
        return RasPreprocess._plan_precipitation_mode(
            plan_file, project_folder, project_name
        ) == "gridded"

    @staticmethod
    def _plan_precipitation_mode(
        plan_file: Path,
        project_folder: Path,
        project_name: str,
    ) -> Optional[str]:
        """Read enabled rainfall mode, 'none' when disabled, or None if unavailable.

        This is intentionally read from the text inputs that HEC-RAS consumes,
        rather than inferred from an existing sidecar or temporary HDF. A stale
        HDF can be the artifact that preprocessing is supposed to replace.
        """
        try:
            plan_text = Path(plan_file).read_text(
                encoding="utf-8",
                errors="ignore",
            )
            match = re.search(
                r"^Flow File\s*=\s*[uU](\d{1,2})\s*$",
                plan_text,
                flags=re.MULTILINE,
            )
            if match is None:
                return None
            unsteady_number = match.group(1).zfill(2)
            unsteady_file = (
                Path(project_folder)
                / f"{project_name}.u{unsteady_number}"
            )
            if not unsteady_file.is_file():
                return None

            precipitation_mode = ""
            met_mode = ""
            with unsteady_file.open(
                "r",
                encoding="utf-8",
                errors="ignore",
            ) as handle:
                for line in handle:
                    stripped = line.strip()
                    if stripped.startswith("Precipitation Mode="):
                        precipitation_mode = stripped.split("=", 1)[1].strip()
                    elif stripped.startswith("Met BC=Precipitation|Mode="):
                        met_mode = stripped.split("=", 2)[-1].strip()
            if precipitation_mode.casefold() == "enable":
                return met_mode.casefold() or None
            return "none" if precipitation_mode else None
        except OSError as exc:
            logger.debug(
                "Could not inspect precipitation mode for %s: %s",
                Path(plan_file).name,
                exc,
            )
            return None

    @staticmethod
    def _validate_materialized_gridded_precipitation(
        tmp_hdf: Path,
    ) -> Tuple[bool, str]:
        """Check a completed temporary HDF's gridded-rainfall structure.

        This inexpensive predicate is deliberately *not* a solver-readiness
        check, but it still opens the HDF.  Call it only after all owned native
        writers are stopped and the file is quiescent.  ``check_solver_ready``
        performs the final completed-file numerical checks afterward.
        """
        precipitation = RasPreprocess._GRIDDED_PRECIPITATION_GROUP
        values_path = f"{precipitation}/Values"
        timestamp_path = f"{precipitation}/Timestamp"
        try:
            import h5py

            from .fast_hdf import read_typed

            with h5py.File(tmp_hdf, "r") as hdf:
                missing = [
                    path
                    for path in (values_path, timestamp_path)
                    if path not in hdf
                ]
                if missing:
                    return False, "missing " + ", ".join(missing)
                values = hdf[values_path]
                timestamps = hdf[timestamp_path]
                if values.ndim != 2 or not all(values.shape):
                    return False, f"invalid Values shape {values.shape}"
                if timestamps.ndim != 1 or not timestamps.shape[0]:
                    return False, f"invalid Timestamp shape {timestamps.shape}"
                if values.shape[0] != timestamps.shape[0]:
                    return (
                        False,
                        "Values and Timestamp lengths differ "
                        f"({values.shape[0]} != {timestamps.shape[0]})",
                    )

                areas_path = "Geometry/2D Flow Areas"
                areas_group = hdf.get(areas_path)
                if areas_group is None:
                    return True, "ready (no 2D flow areas)"
                attributes = areas_group.get("Attributes")
                if (
                    attributes is not None
                    and attributes.dtype.names
                    and "Name" in attributes.dtype.names
                ):
                    area_names = []
                    for name in read_typed(attributes)["Name"]:
                        if isinstance(name, bytes):
                            name = name.decode("utf-8", "replace")
                        name = str(name).strip()
                        if name:
                            area_names.append(name)
                else:
                    area_names = [
                        name
                        for name, node in areas_group.items()
                        if isinstance(node, h5py.Group)
                    ]

                missing_interpolation = []
                for area_name in area_names:
                    area_path = f"{precipitation}/2D Flow Areas/{area_name}"
                    area_group = hdf.get(area_path)
                    if area_group is None:
                        missing_interpolation.append(f"{area_path}/")
                        continue
                    for dataset_name in (
                        RasPreprocess._GRIDDED_PRECIPITATION_INTERPOLATION_DATASETS
                    ):
                        dataset_path = f"{area_path}/{dataset_name}"
                        dataset = hdf.get(dataset_path)
                        if (
                            dataset is None
                            or not getattr(dataset, "shape", None)
                            or dataset.shape[0] == 0
                        ):
                            missing_interpolation.append(dataset_path)
                if missing_interpolation:
                    return (
                        False,
                        "missing or empty gridded interpolation dataset(s): "
                        + ", ".join(missing_interpolation),
                    )
        except Exception as exc:
            from .fast_hdf import reraise_required

            reraise_required(exc)
            return False, f"could not inspect {Path(tmp_hdf).name}: {exc}"
        return True, "ready"

    @staticmethod
    def _wait_stopped_artifacts_quiet(paths: Tuple[Path, ...], timeout: float = 10.0) -> bool:
        """Wait for file metadata to settle after exact owned-process cleanup."""
        deadline = time.monotonic() + timeout
        previous = None
        stable_since = time.monotonic()
        while time.monotonic() < deadline:
            current = tuple(RasPreprocess._artifact_state(path) for path in paths)
            now = time.monotonic()
            if current != previous:
                previous, stable_since = current, now
            elif now - stable_since >= RasPreprocess._GRIDDED_PRECIPITATION_STABLE_SECONDS:
                return True
            time.sleep(0.1)
        return False

    @staticmethod
    def _completepreprocess_handoff_ready(
        tmp_hdf: Path,
        b_file: Path,
        x_file: Path,
        stability_state: Dict[str, object],
        *,
        started_at: float,
        artifact_baseline: Optional[
            Dict[Path, Optional[Tuple[int, int]]]
        ] = None,
        solver_started: Optional[Callable[[], bool]] = None,
        allow_completed_hdf: bool = False,
        defer_stat_quiescence: bool = False,
    ) -> bool:
        """Return when an observed native writer has ended and artifacts are quiet.

        Also return once no writer is active and ``solver_started`` reports this
        launch's own unsteady solver running: HEC-RAS starts the solver only
        after preprocessing has written the event conditions, and the solver's
        own writes would otherwise keep the artifacts from ever going quiet.
        Some releases (6.1) run no separate writer at all.

        This is an active-engine predicate.  It intentionally never opens the
        temporary HDF: HDF5 readers can deny Windows writer access.  The caller
        must stop its owned process tree and run completed-file structural and
        solver-readiness validation separately after this method returns true.
        """
        writers = RasPreprocess._active_complete_preprocess_writers(
            tmp_hdf,
            started_at,
        )
        if writers:
            if writers == (-1,):
                logger.warning(
                    "Could not enumerate CompletePreProcess writers; refusing "
                    "gridded-preprocessing handoff for this poll"
                )
                # A failed current query cannot authorize handoff, but does
                # not invalidate a previously observed exact writer. Require
                # a later successful inventory and new quiescence checks.
                for key in (
                    "active_completepreprocess_pids", "writer_absent_since",
                    "fingerprint", "observed_at",
                ):
                    stability_state.pop(key, None)
                return False
            if stability_state.get("active_completepreprocess_pids") != writers:
                logger.info(
                    "Waiting for exact CompletePreProcess writer(s) before "
                    "stopping gridded preprocessing: %s",
                    ", ".join(str(pid) for pid in writers),
                )
            stability_state["completepreprocess_seen"] = True
            stability_state["active_completepreprocess_pids"] = writers
            stability_state.pop("writer_absent_since", None)
            stability_state.pop("fingerprint", None)
            stability_state.pop("observed_at", None)
            return False

        # HEC-RAS starts its unsteady solver only after preprocessing; with no
        # writer running (a successful scan), the solver's start is the handoff.
        # Some releases (6.1) never run a separate CompletePreProcess writer.
        # Completed-file validation still requires the materialized precipitation.
        if solver_started is not None and solver_started():
            stability_state.pop("active_completepreprocess_pids", None)
            stability_state["writer_observation"] = (
                "solver_started" if stability_state.get("completepreprocess_seen")
                else "solver_started_no_writer_observed")
            logger.info(
                "No CompletePreProcess writer is active and the owned unsteady "
                "solver started; stopping before it advances"
            )
            return True

        # The narrow process matcher may not have observed a writer yet.  That
        # absence is not evidence that no writer can still start, so it cannot
        # authorize an early stop or any HDF read.
        if not stability_state.get("completepreprocess_seen"):
            stability_state.pop("active_completepreprocess_pids", None)
            stability_state.pop("writer_absent_since", None)
            stability_state.pop("fingerprint", None)
            stability_state.pop("observed_at", None)
            return False

        readiness_hdf = tmp_hdf
        if allow_completed_hdf and not tmp_hdf.is_file():
            # A completed native run may consume/rename .tmp.hdf before the
            # quiet period ends. Only a changed final file from this launch
            # can serve as the existing post-stop full-result-copy fallback.
            final_hdf = tmp_hdf.with_name(tmp_hdf.name.replace(".tmp.hdf", ".hdf"))
            final_state = RasPreprocess._artifact_state(final_hdf)
            before = (artifact_baseline or {}).get(final_hdf)
            if final_state is not None and final_state != before:
                readiness_hdf = final_hdf

        if not RasPreprocess._preprocessing_artifacts_ready(
            readiness_hdf,
            b_file,
            x_file,
            artifact_baseline=artifact_baseline,
        ):
            stability_state.pop("writer_absent_since", None)
            stability_state.pop("fingerprint", None)
            stability_state.pop("observed_at", None)
            return False

        if defer_stat_quiescence:
            # Stop the owned launcher before it consumes .tmp.hdf for the
            # solver. The native writer has already exited. Stat quiescence
            # is checked after all owned processes stop and before HDF reads.
            stability_state["writer_observation"] = "writer_exited"
            return True

        now = time.monotonic()
        stability_state.pop("active_completepreprocess_pids", None)
        if "writer_absent_since" not in stability_state:
            stability_state["writer_absent_since"] = now
            stability_state["writer_observation"] = "writer_quiescent"
            logger.info(
                "Observed CompletePreProcess writer is no longer active; "
                "requiring %.1fs writer/stat quiescence",
                RasPreprocess._GRIDDED_PRECIPITATION_STABLE_SECONDS,
            )
            return False
        writer_absent_since = stability_state["writer_absent_since"]
        if (
            not isinstance(writer_absent_since, Number)
            or now - float(writer_absent_since)
            < RasPreprocess._GRIDDED_PRECIPITATION_STABLE_SECONDS
        ):
            return False
        current = (str(readiness_hdf), RasPreprocess._artifact_state(readiness_hdf))
        if stability_state.get("fingerprint") != current:
            stability_state["fingerprint"] = current
            stability_state["observed_at"] = now
            return False
        observed_at = stability_state.get("observed_at")
        return (
            isinstance(observed_at, Number)
            and now - float(observed_at)
            >= RasPreprocess._GRIDDED_PRECIPITATION_STABLE_SECONDS
        )

    @staticmethod
    def _validate_completed_gridded_preprocessing(
        tmp_hdf: Path,
    ) -> Tuple[bool, str]:
        """Run the expensive Linux input gate once after the writer is stopped."""
        before = RasPreprocess._artifact_state(tmp_hdf)
        if before is None:
            return False, f"missing {Path(tmp_hdf).name}"
        try:
            # This check reads property-table chunks to reject NaNs and also
            # verifies Geometry/GeomPreprocess.  Do not call it while the
            # Windows engine may still be writing the temporary HDF.
            from .RasApptainer import check_solver_ready

            problems = check_solver_ready(tmp_hdf, geom_preprocess=False)
        except Exception as exc:
            return False, f"could not validate completed {Path(tmp_hdf).name}: {exc}"
        after = RasPreprocess._artifact_state(tmp_hdf)
        if after != before:
            return False, f"{Path(tmp_hdf).name} changed during solver-readiness validation"
        if problems:
            return False, "; ".join(problems)
        return True, "ready"

    @staticmethod
    def _preprocessing_artifacts_ready(
        tmp_hdf: Path,
        b_file: Path,
        x_file: Path,
        artifact_baseline: Optional[
            Dict[Path, Optional[Tuple[int, int]]]
        ] = None,
    ) -> bool:
        """Return whether all preprocessing artifacts exist and are fresh."""
        artifacts = (Path(tmp_hdf), Path(b_file), Path(x_file))
        if any(
            not path.is_file() or path.stat().st_size == 0
            for path in artifacts
        ):
            return False
        if artifact_baseline is not None:
            for path in artifacts:
                before = artifact_baseline.get(path)
                if (
                    before is not None
                    and RasPreprocess._artifact_state(path) == before
                ):
                    return False
        return True

    @staticmethod
    def _materialized_gridded_precipitation_ready(
        tmp_hdf: Path,
        b_file: Path,
        x_file: Path,
        artifact_baseline: Optional[
            Dict[Path, Optional[Tuple[int, int]]]
        ] = None,
    ) -> bool:
        """Inspect a completed, writer-free HDF for gridded-rain structure.

        This is not safe while an owned HEC-RAS process may be writing the
        temporary HDF.  Active preprocessing uses
        :meth:`_completepreprocess_handoff_ready` instead.
        """
        if not RasPreprocess._preprocessing_artifacts_ready(
            tmp_hdf,
            b_file,
            x_file,
            artifact_baseline=artifact_baseline,
        ):
            return False
        materialized, _detail = (
            RasPreprocess._validate_materialized_gridded_precipitation(
                tmp_hdf
            )
        )
        return materialized

    @staticmethod
    def _preprocessing_ready(
        root_pid: int,
        tmp_hdf: Path,
        b_file: Path,
        x_file: Path,
        artifact_baseline: Optional[
            Dict[Path, Optional[Tuple[int, int]]]
        ] = None,
        require_materialized_gridded_precipitation: bool = False,
    ) -> bool:
        """Return whether owned preprocessing reached a safe handoff point.

        With gridded precipitation this method deliberately does not inspect
        the HDF while the owned process may still write it.  It therefore
        refuses the materialized-rain option; callers must use the dedicated
        CompletePreProcess lifecycle handoff and validate only after cleanup.
        """
        if not RasPreprocess._unsteady_compute_started(
            root_pid,
            tmp_hdf,
            b_file,
            x_file,
            artifact_baseline=artifact_baseline,
        ):
            return False
        if not require_materialized_gridded_precipitation:
            return True
        return False

    @staticmethod
    def _unsteady_compute_started(
        root_pid: int,
        tmp_hdf: Path,
        b_file: Path,
        x_file: Path,
        artifact_baseline: Optional[
            Dict[Path, Optional[Tuple[int, int]]]
        ] = None,
    ) -> bool:
        """Return True when this launch owns a ready unsteady compute process."""
        if not RasPreprocess._preprocessing_artifacts_ready(
            tmp_hdf,
            b_file,
            x_file,
            artifact_baseline=artifact_baseline,
        ):
            return False

        try:
            import psutil

            descendants = psutil.Process(int(root_pid)).children(recursive=True)
        except Exception:
            return False

        for child in descendants:
            candidates = []
            try:
                candidates.append(child.name())
            except Exception:
                pass
            try:
                command = child.cmdline()
                if command:
                    candidates.append(Path(command[0]).name)
            except Exception:
                pass
            if any(
                str(candidate).casefold() in RasPreprocess._UNSTEADY_PROCESS_NAMES
                for candidate in candidates
            ):
                return True
        return False

    @staticmethod
    def _terminate_process_tree(process: subprocess.Popen) -> None:
        """
        Kill a process and all its children.

        Uses psutil for reliable process tree termination. Falls back to
        process.kill() if psutil is unavailable or fails.

        Args:
            process: Running subprocess to terminate.
        """
        try:
            import psutil
        except Exception as e:
            logger.warning(
                f"psutil unavailable ({e}); falling back to process.kill()"
            )
            try:
                process.kill()
                process.wait(timeout=10)
            except Exception:
                pass
            return

        try:
            parent = psutil.Process(process.pid)
            children = parent.children(recursive=True)

            # Kill children first, then parent
            for child in reversed(children):
                try:
                    child.kill()
                except psutil.NoSuchProcess:
                    pass

            try:
                parent.kill()
            except psutil.NoSuchProcess:
                pass

            _, survivors = psutil.wait_procs(
                [*children, parent],
                timeout=10,
            )
            for survivor in survivors:
                try:
                    survivor.kill()
                except psutil.NoSuchProcess:
                    pass
            if survivors:
                _, survivors = psutil.wait_procs(survivors, timeout=2)
            if survivors:
                logger.warning(
                    "Owned HEC-RAS processes survived termination: %s",
                    ", ".join(str(item.pid) for item in survivors),
                )
            try:
                process.wait(timeout=2)
            except Exception:
                pass
            logger.debug("HEC-RAS process tree terminated")
        except psutil.NoSuchProcess:
            # GUI-subsystem Ras.exe can detach its exact-plan replacement and
            # allow the Python-owned launcher to exit before readiness is
            # observed. The exact-plan residue cleanup immediately following
            # this call handles that scoped handoff.
            try:
                process.wait(timeout=2)
            except Exception:
                pass
            logger.debug(
                "HEC-RAS launcher exited before process-tree termination"
            )
        except Exception as e:
            # GUI-subsystem launchers can disappear between psutil discovery
            # and termination. A successful direct fallback is an expected
            # cleanup race, not a user-actionable preprocessing warning.
            logger.debug(
                "psutil process-tree termination was unavailable (%s); "
                "falling back to process.kill()",
                e,
            )
            try:
                process.kill()
                process.wait(timeout=10)
            except Exception as fallback_error:
                logger.warning(
                    "Unable to terminate the owned HEC-RAS launcher after "
                    "psutil fallback: %s",
                    fallback_error,
                )

    @staticmethod
    def _terminate_exact_preprocess_residue(
        project_file: Path,
        plan_file: Path,
        tmp_hdf: Path,
        started_at: float,
        timeout_seconds: float = 10.0,
    ) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
        """Stop detached processes proven to belong to one preprocess launch.

        ``Ras.exe`` can return control to its parent while a replacement
        ``Ras.exe`` and ``RasProcess.exe CompletePreProcess`` continue in the
        background. Process ancestry is no longer sufficient after that
        handoff, so matching is deliberately narrow:

        * ``Ras.exe`` must contain the exact project and plan path arguments.
        * ``RasProcess.exe`` must request ``CompletePreProcess`` for the exact
          temporary plan HDF.
        * the process must have started within this preprocessing launch.

        Descendants of those exact roots are included, then children are
        terminated before parents. The returned tuples contain stopped and
        surviving PIDs respectively.
        """
        try:
            import psutil
        except Exception as exc:
            logger.warning(
                "Could not inspect detached preprocessing processes: %s",
                exc,
            )
            return (), (-1,)

        exact_project = RasPreprocess._normalized_preprocess_path(project_file)
        exact_plan = RasPreprocess._normalized_preprocess_path(plan_file)
        earliest_create_time = float(started_at) - 2.0
        roots = []

        processes = RasPreprocess._preprocess_process_inventory()
        if processes is None:
            return (), (-1,)
        for candidate, info in processes:
            name = str(info["name"]).casefold()
            if float(info["create_time"]) < earliest_create_time:
                continue
            normalized_arguments = {
                RasPreprocess._normalized_preprocess_path(argument)
                for argument in info["cmdline"]
            }

            ras_launcher = (
                name == "ras.exe"
                and exact_project in normalized_arguments
                and exact_plan in normalized_arguments
            )
            complete_preprocess = RasPreprocess._is_exact_complete_preprocess_process(
                info,
                tmp_hdf,
                started_at,
            )
            if ras_launcher or complete_preprocess:
                roots.append(candidate)

        targets = {}
        for root in roots:
            try:
                root_created = float(root.create_time())
                targets[(int(root.pid), root_created)] = root
                for child in root.children(recursive=True):
                    child_created = float(child.create_time())
                    if child_created >= earliest_create_time:
                        targets[(int(child.pid), child_created)] = child
            except psutil.NoSuchProcess:
                continue
            except (psutil.AccessDenied, OSError):
                return (), (-1,)

        if not targets:
            return (), ()

        ordered = sorted(
            targets.items(),
            key=lambda item: item[1].pid,
            reverse=True,
        )
        requested = []
        stopped = []
        for (pid, create_time), target in ordered:
            try:
                if abs(float(target.create_time()) - create_time) > 1e-6:
                    continue
                target.terminate()
                requested.append(target)
            except psutil.NoSuchProcess:
                stopped.append(pid)
            except psutil.AccessDenied:
                logger.warning(
                    "Access denied while stopping preprocessing PID %s",
                    pid,
                )

        alive = []
        if requested:
            gone, alive = psutil.wait_procs(
                requested,
                timeout=max(0.1, float(timeout_seconds)),
            )
            stopped.extend(int(item.pid) for item in gone)

        for target in alive:
            try:
                target.kill()
            except psutil.NoSuchProcess:
                stopped.append(int(target.pid))
            except psutil.AccessDenied:
                logger.warning(
                    "Access denied while killing preprocessing PID %s",
                    target.pid,
                )

        if alive:
            gone, alive = psutil.wait_procs(alive, timeout=2.0)
            stopped.extend(int(item.pid) for item in gone)

        survivors = []
        for target in alive:
            try:
                if target.is_running():
                    survivors.append(int(target.pid))
                else:
                    stopped.append(int(target.pid))
            except psutil.NoSuchProcess:
                stopped.append(int(target.pid))

        return tuple(sorted(set(stopped))), tuple(sorted(set(survivors)))

    @staticmethod
    def _clear_preprocessing_files(
        project_folder: Path,
        project_name: str,
        plan_num: str,
        geom_num: str,
    ) -> None:
        """
        Delete stale preprocessing files to force regeneration.

        Removes .tmp.hdf, .b##, .x##, and .bco## files. Final plan HDF and
        legacy .O## results are deliberately preserved.

        Args:
            project_folder: Path to the project folder.
            project_name: Project name (without extension).
            plan_num: Plan number (e.g., "01").
            geom_num: Geometry number (e.g., "04").
        """
        patterns = [
            f"{project_name}.p{plan_num}.tmp.hdf",
            f"{project_name}.b{plan_num}",
            f"{project_name}.x{geom_num}",
            f"{project_name}.bco{plan_num}",
        ]
        for pattern in patterns:
            target = project_folder / pattern
            if target.exists():
                try:
                    target.unlink()
                    logger.debug(f"Deleted: {target.name}")
                except Exception as e:
                    logger.warning(f"Could not delete {target.name}: {e}")

    @staticmethod
    def _fix_x_file_line_endings(x_file_path: Path) -> None:
        """
        Convert CRLF to LF in the .x## file for Linux compatibility.

        Only modifies the .x file — other project files are handled by
        ``RasCmdr.compute_plan_linux()`` via dos2unix.

        Args:
            x_file_path: Path to the .x## file.
        """
        try:
            content = x_file_path.read_bytes()
            if b'\r\n' in content:
                fixed = content.replace(b'\r\n', b'\n')
                x_file_path.write_bytes(fixed)
                logger.debug(f"Fixed CRLF→LF in {x_file_path.name}")
        except Exception as e:
            logger.warning(f"Could not fix line endings in {x_file_path.name}: {e}")
preprocess_plan staticmethod
Python
preprocess_plan(plan_number: Union[str, Number], ras_object=None, max_wait: int = 300, clear_existing: bool = True, fix_line_endings: bool = True, require_linux_solver_ready: bool = True, *, accept_tcu: bool = False, precipitation_repair_attempts: int = 6, precipitation_repair_timeout: Optional[int] = None) -> PreprocessResult

Preprocess a plan on Windows for Linux execution.

Runs HEC-RAS with early termination to generate .tmp.hdf, .b##, and .x## files required by the Linux RasUnsteady binary. The process is killed when the .bco log indicates preprocessing is complete ("Starting Unsteady Flow Computations" signal), or when an owned RasUnsteady.exe descendant has started and all three prerequisite files are non-empty. The process-tree fallback supports releases that create an empty .bco file.

Set require_linux_solver_ready=False for native Windows computation: that mode stops after the observed event writer exits, checks file quiescence after owned cleanup, and validates materialized meteorology. The default additionally requires Linux-specific geometry input tables.

After owned writers stop, success also requires Event Conditions to report Completed Successfully=True. Enabled point or gridded rain requires a non-empty two-dimensional precipitation Values dataset. Missing completion evidence is rejected, including when copying a fresh final HDF. Failure retains artifact paths and readiness-signal details.

HEC-RAS's own event-condition writer, RasProcess.exe CompletePreProcess, can intermittently write no point precipitation for identical inputs. It reports "No valid precipitation time-series data found for this time-window" and "Error processing Precipitation data, exiting...", and Ras.exe then exits 0 before the unsteady computation. This was observed in 8 of 47 processes (17%) with HEC-RAS 6.6 under Wine, and also with 6.4.1; it is not caused by the early-stop logic. When a point-precipitation plan fails Event Conditions validation and the temporary HDF, .b## and .x## are all present, this method re-runs only RasProcess.exe CompletePreProcess <project>.rasmap <plan>.tmp.hdf on the same temporary HDF, from the project folder, and re-validates after each attempt. A repaired file matched a first-try success exactly. Gridded precipitation is not repaired this way.

With HEC-RAS before 6.3, fails without launching HEC-RAS when the plan's geometry HDF references a land-cover, infiltration, or sediment file that does not exist. Those releases would otherwise skip the geometry and write no 2D mesh.

Unpatched HEC-RAS 7.0.2 temporarily receives a project declaration containing only this plan. The original project bytes are restored after owned processes stop. An unproved stop retains the single-plan file, original backup, and claim and fails the result with a recovery diagnostic. An exact recognized local CLI patch skips the project transaction; the single-plan execution guide records its SHA-256 and tested scope.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

Plan number to preprocess (e.g., "01", 1).

required
ras_object RasPrj

Optional RasPrj instance. If None, uses global ras.

None
max_wait int

Maximum seconds to wait for preprocessing (default 300).

300
clear_existing bool

Delete stale preprocessing files before running (default True).

True
fix_line_endings bool

Convert .x file CRLF to LF for Linux (default True).

True
accept_tcu bool

Explicitly authorize accepting an exact owned TCU wizard during this launch. False by default; acceptance failures block preprocessing and receipts are retained in the result.

False
precipitation_repair_attempts int

Maximum CompletePreProcess re-runs used to complete point precipitation (default 6; 0 disables the repair). Repairs stop early on a timeout, a legal-dialog block, a launch failure, or surviving processes.

6
precipitation_repair_timeout Optional[int]

Seconds allowed for each repair attempt. Defaults to max_wait, which already bounds the full preprocessing run that includes this step.

None

Returns:

Type Description
PreprocessResult

Result with success flag, file paths, and timing. Bool-compatible: if preprocess_plan("01"): works. precipitation_repair_attempts records each repair attempt, and signal_source is "completepreprocess_repair" when a repair completed the temporary HDF.

Note

Errors are captured in PreprocessResult.error.

Example

result = RasPreprocess.preprocess_plan("01") if result: ... print(f"tmp.hdf: {result.tmp_hdf_path}") ... print(f".b file: {result.b_file_path}") ... print(f".x file: {result.x_file_path}")

Source code in ras_commander/RasPreprocess.py
Python
@staticmethod
@log_call
def preprocess_plan(
    plan_number: Union[str, Number],
    ras_object=None,
    max_wait: int = 300,
    clear_existing: bool = True,
    fix_line_endings: bool = True,
    require_linux_solver_ready: bool = True,
    *,
    accept_tcu: bool = False,
    precipitation_repair_attempts: int = 6,
    precipitation_repair_timeout: Optional[int] = None,
) -> PreprocessResult:
    """
    Preprocess a plan on Windows for Linux execution.

    Runs HEC-RAS with early termination to generate .tmp.hdf, .b##, and .x##
    files required by the Linux RasUnsteady binary. The process is killed when
    the .bco log indicates preprocessing is complete ("Starting Unsteady Flow
    Computations" signal), or when an owned ``RasUnsteady.exe`` descendant has
    started and all three prerequisite files are non-empty. The process-tree
    fallback supports releases that create an empty ``.bco`` file.

    Set require_linux_solver_ready=False for native Windows computation:
    that mode stops after the observed event writer exits, checks file
    quiescence after owned cleanup, and validates materialized meteorology.
    The default additionally requires Linux-specific geometry input tables.

    After owned writers stop, success also requires Event Conditions to
    report ``Completed Successfully=True``. Enabled point or gridded rain
    requires a non-empty two-dimensional precipitation ``Values`` dataset.
    Missing completion evidence is rejected, including when copying a fresh
    final HDF. Failure retains artifact paths and readiness-signal details.

    HEC-RAS's own event-condition writer, ``RasProcess.exe
    CompletePreProcess``, can intermittently write no point precipitation
    for identical inputs. It reports "No valid precipitation time-series
    data found for this time-window" and "Error processing Precipitation
    data, exiting...", and Ras.exe then exits 0 before the unsteady
    computation. This was observed in 8 of 47 processes (17%) with HEC-RAS
    6.6 under Wine, and also with 6.4.1; it is not caused by the
    early-stop logic. When a point-precipitation plan fails Event
    Conditions validation and the temporary HDF, ``.b##`` and ``.x##`` are
    all present, this method re-runs only ``RasProcess.exe
    CompletePreProcess <project>.rasmap <plan>.tmp.hdf`` on the same
    temporary HDF, from the project folder, and re-validates after each
    attempt. A repaired file matched a first-try success exactly. Gridded
    precipitation is not repaired this way.

    With HEC-RAS before 6.3, fails without launching HEC-RAS when the plan's
    geometry HDF references a land-cover, infiltration, or sediment file that
    does not exist. Those releases would otherwise skip the geometry and
    write no 2D mesh.

    Unpatched HEC-RAS 7.0.2 temporarily receives a project declaration containing only
    this plan. The original project bytes are restored after owned processes
    stop. An unproved stop retains the single-plan file, original backup,
    and claim and fails the result with a recovery diagnostic.
    An exact recognized local CLI patch skips the project transaction;
    the single-plan execution guide records its SHA-256 and tested scope.

    Args:
        plan_number: Plan number to preprocess (e.g., "01", 1).
        ras_object (RasPrj, optional): Optional RasPrj instance. If None, uses global ras.
        max_wait: Maximum seconds to wait for preprocessing (default 300).
        clear_existing: Delete stale preprocessing files before running (default True).
        fix_line_endings: Convert .x file CRLF to LF for Linux (default True).
        accept_tcu: Explicitly authorize accepting an exact owned TCU wizard
            during this launch. False by default; acceptance failures block
            preprocessing and receipts are retained in the result.
        precipitation_repair_attempts: Maximum ``CompletePreProcess``
            re-runs used to complete point precipitation (default 6; 0
            disables the repair). Repairs stop early on a timeout, a
            legal-dialog block, a launch failure, or surviving processes.
        precipitation_repair_timeout: Seconds allowed for each repair
            attempt. Defaults to ``max_wait``, which already bounds the
            full preprocessing run that includes this step.

    Returns:
        PreprocessResult: Result with success flag, file paths, and timing.
            Bool-compatible: ``if preprocess_plan("01"):`` works.
            ``precipitation_repair_attempts`` records each repair attempt,
            and ``signal_source`` is ``"completepreprocess_repair"`` when
            a repair completed the temporary HDF.

    Note:
        Errors are captured in PreprocessResult.error.

    Example:
        >>> result = RasPreprocess.preprocess_plan("01")
        >>> if result:
        ...     print(f"tmp.hdf: {result.tmp_hdf_path}")
        ...     print(f".b file: {result.b_file_path}")
        ...     print(f".x file: {result.x_file_path}")
    """
    # A HEC-RAS 7.0.2 single-plan project declaration must be restored on
    # every exit, including exceptions, so the launch lifecycle runs inside
    # one owned try/finally. Result paths release it through make_result;
    # this finally covers only exits that never built a result.
    lifecycle = SinglePlanLaunchLifecycle()
    try:
        return RasPreprocess._preprocess_plan_lifecycle(
            plan_number,
            ras_object,
            max_wait,
            clear_existing,
            fix_line_endings,
            require_linux_solver_ready,
            accept_tcu=accept_tcu,
            precipitation_repair_attempts=precipitation_repair_attempts,
            precipitation_repair_timeout=precipitation_repair_timeout,
            lifecycle=lifecycle,
        )
    finally:
        if lifecycle.pending:
            lifecycle.finish()
run_ras_geom_preprocess staticmethod
Python
run_ras_geom_preprocess(plan_number: Union[str, Number], ras_object=None, input_hdf_path: Optional[Union[str, Path]] = None, x_file_path: Optional[Union[str, Path]] = None, executable_path: Optional[Union[str, Path]] = None, timeout_sec: int = 300, require_hdf_change: bool = False) -> GeometryPreprocessResult

Run vendor RasGeomPreprocess.exe for one staged plan.

:meth:preprocess_plan creates the plan *.tmp.hdf and geometry .x## inputs. This method executes the matching standalone geometry preprocessor using an argument vector, enforces a bounded timeout, and records executable and before/after HDF fingerprints. It is intended for Windows Python, including Windows Python hosted by Wine.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

Plan number (for example "06").

required
ras_object RasPrj

Initialized :class:RasPrj; defaults to the global project.

None
input_hdf_path Optional[Union[str, Path]]

Optional explicit plan *.tmp.hdf input.

None
x_file_path Optional[Union[str, Path]]

Optional explicit project .x## file.

None
executable_path Optional[Union[str, Path]]

Optional explicit RasGeomPreprocess.exe path. The default is the x64 directory beside Ras.exe.

None
timeout_sec int

Maximum execution time in seconds.

300
require_hdf_change bool

Require the input HDF fingerprint to change. Leave False for idempotent reruns; qualification of a fresh input should set this to True.

False

Returns:

Type Description
GeometryPreprocessResult

Bool-compatible execution evidence.

Source code in ras_commander/RasPreprocess.py
Python
@staticmethod
@log_call
def run_ras_geom_preprocess(
    plan_number: Union[str, Number],
    ras_object=None,
    input_hdf_path: Optional[Union[str, Path]] = None,
    x_file_path: Optional[Union[str, Path]] = None,
    executable_path: Optional[Union[str, Path]] = None,
    timeout_sec: int = 300,
    require_hdf_change: bool = False,
) -> GeometryPreprocessResult:
    """Run vendor ``RasGeomPreprocess.exe`` for one staged plan.

    :meth:`preprocess_plan` creates the plan ``*.tmp.hdf`` and geometry
    ``.x##`` inputs. This method executes the matching standalone geometry
    preprocessor using an argument vector, enforces a bounded timeout, and
    records executable and before/after HDF fingerprints. It is intended for
    Windows Python, including Windows Python hosted by Wine.

    Args:
        plan_number: Plan number (for example ``"06"``).
        ras_object (RasPrj, optional): Initialized :class:`RasPrj`; defaults to the global project.
        input_hdf_path: Optional explicit plan ``*.tmp.hdf`` input.
        x_file_path: Optional explicit project ``.x##`` file.
        executable_path: Optional explicit ``RasGeomPreprocess.exe`` path.
            The default is the ``x64`` directory beside ``Ras.exe``.
        timeout_sec: Maximum execution time in seconds.
        require_hdf_change: Require the input HDF fingerprint to change.
            Leave False for idempotent reruns; qualification of a fresh input
            should set this to True.

    Returns:
        GeometryPreprocessResult: Bool-compatible execution evidence.
    """
    start_time = time.time()
    ras_obj = ras_object if ras_object is not None else ras

    if isinstance(plan_number, Number):
        plan_num = f"{int(plan_number):02d}"
    else:
        plan_num = str(plan_number).zfill(2)

    try:
        ras_obj.check_initialized()
    except Exception as e:
        return GeometryPreprocessResult(
            success=False,
            plan_number=plan_num,
            error=f"Project not initialized: {e}",
            elapsed_seconds=time.time() - start_time,
        )

    project_folder = Path(ras_obj.project_folder)
    project_name = ras_obj.project_name
    plan_path = project_folder / f"{project_name}.p{plan_num}"
    geometry_number = None
    try:
        plan_row = ras_obj.plan_df[ras_obj.plan_df["plan_number"] == plan_num]
        if not plan_row.empty and "Geom File" in plan_row.columns:
            match = re.search(r"(\d+)", str(plan_row["Geom File"].iloc[0]))
            if match:
                geometry_number = match.group(1)
    except Exception:
        pass
    if geometry_number is None and plan_path.is_file():
        geometry_number = RasPreprocess._extract_geometry_number(plan_path)
    if geometry_number is None:
        return GeometryPreprocessResult(
            success=False,
            plan_number=plan_num,
            error=f"Could not determine geometry number for plan {plan_num}",
            elapsed_seconds=time.time() - start_time,
        )

    input_hdf = (
        Path(input_hdf_path)
        if input_hdf_path is not None
        else project_folder / f"{project_name}.p{plan_num}.tmp.hdf"
    )
    x_file = (
        Path(x_file_path)
        if x_file_path is not None
        else project_folder / f"{project_name}.x{geometry_number}"
    )
    if executable_path is None:
        ras_exe_path = Path(str(getattr(ras_obj, "ras_exe_path", "")))
        executable = ras_exe_path.parent / "x64" / "RasGeomPreprocess.exe"
    else:
        executable = Path(executable_path)

    missing = [
        str(path)
        for path in (executable, input_hdf, x_file)
        if not path.is_file() or path.stat().st_size == 0
    ]
    if missing:
        return GeometryPreprocessResult(
            success=False,
            plan_number=plan_num,
            geometry_number=geometry_number,
            executable_path=executable,
            input_hdf_path=input_hdf,
            x_file_path=x_file,
            error=(
                "Missing or empty geometry-preprocessor input: "
                + ", ".join(missing)
            ),
            elapsed_seconds=time.time() - start_time,
        )

    expected_x_name = f"{project_name}.x{geometry_number}".casefold()
    try:
        same_parent = x_file.parent.resolve() == input_hdf.parent.resolve()
    except OSError:
        same_parent = x_file.parent.absolute() == input_hdf.parent.absolute()
    if not same_parent or x_file.name.casefold() != expected_x_name:
        return GeometryPreprocessResult(
            success=False,
            plan_number=plan_num,
            geometry_number=geometry_number,
            executable_path=executable,
            input_hdf_path=input_hdf,
            x_file_path=x_file,
            error=(
                "RasGeomPreprocess requires the project execution file "
                f"{project_name}.x{geometry_number} beside the input HDF"
            ),
            elapsed_seconds=time.time() - start_time,
        )

    executable_sha256 = RasPreprocess._file_sha256(executable)
    before_sha256 = RasPreprocess._file_sha256(input_hdf)
    command = [str(executable), str(input_hdf), f"x{geometry_number}"]
    command_text = subprocess.list2cmdline(command)
    process = None
    stdout = ""
    stderr = ""
    timed_out = False
    launch_error = None

    try:
        process = subprocess.Popen(
            command,
            cwd=str(input_hdf.parent),
            shell=False,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding="utf-8",
            errors="replace",
        )
        try:
            stdout, stderr = process.communicate(timeout=int(timeout_sec))
        except subprocess.TimeoutExpired:
            timed_out = True
            RasPreprocess._terminate_process_tree(process)
            try:
                stdout, stderr = process.communicate(timeout=2)
            except Exception:
                stdout, stderr = "", ""
    except OSError as e:
        launch_error = str(e)

    after_sha256 = (
        RasPreprocess._file_sha256(input_hdf)
        if input_hdf.is_file() and input_hdf.stat().st_size > 0
        else None
    )
    output_changed = bool(
        before_sha256 and after_sha256 and before_sha256 != after_sha256
    )
    return_code = process.returncode if process is not None else None

    hdf_readable = False
    geometry_group_present = False
    hdf_error = None
    if after_sha256 is not None:
        try:
            import h5py

            with h5py.File(input_hdf, "r") as handle:
                hdf_readable = True
                geometry_group_present = "Geometry" in handle
        except Exception as e:
            hdf_error = str(e)

    errors = []
    if launch_error:
        errors.append(f"Could not launch RasGeomPreprocess: {launch_error}")
    if timed_out:
        errors.append(
            f"RasGeomPreprocess timed out after {int(timeout_sec)} seconds"
        )
    if return_code is None:
        errors.append("RasGeomPreprocess did not report a final return code")
    elif return_code != 0:
        errors.append(f"RasGeomPreprocess exited with code {return_code}")
    if after_sha256 is None:
        errors.append("RasGeomPreprocess did not leave a non-empty input HDF")
    elif not hdf_readable:
        errors.append(f"RasGeomPreprocess output HDF is unreadable: {hdf_error}")
    elif not geometry_group_present:
        errors.append("RasGeomPreprocess output HDF has no Geometry group")
    if require_hdf_change and not output_changed:
        errors.append("RasGeomPreprocess did not change the input HDF fingerprint")

    combined_output = "\n".join(item for item in (stdout, stderr) if item)
    from .results import ResultsParser

    parsed = ResultsParser.parse_compute_messages(combined_output)
    operational_error_count = len(errors)
    if parsed["has_errors"]:
        errors.append(
            "RasGeomPreprocess reported an error: "
            f"{parsed['first_error_line']}"
        )

    return GeometryPreprocessResult(
        success=not errors,
        plan_number=plan_num,
        geometry_number=geometry_number,
        elapsed_seconds=time.time() - start_time,
        command=command_text,
        return_code=return_code,
        executable_path=executable,
        executable_sha256=executable_sha256,
        input_hdf_path=input_hdf,
        x_file_path=x_file,
        input_hdf_sha256_before=before_sha256,
        input_hdf_sha256_after=after_sha256,
        output_changed=output_changed,
        hdf_readable=hdf_readable,
        geometry_group_present=geometry_group_present,
        timed_out=timed_out,
        stdout=stdout or "",
        stderr=stderr or "",
        artifact_paths=[input_hdf, x_file],
        error_count=operational_error_count + parsed["error_count"],
        warning_count=parsed["warning_count"],
        first_error_line=parsed["first_error_line"],
        error="; ".join(errors) if errors else None,
    )
verify_preprocessing staticmethod
Python
verify_preprocessing(plan_number: Union[str, Number], ras_object=None) -> bool

Check if prerequisite files for Linux execution exist.

Verifies that .tmp.hdf, .b##, and .x## files exist and are non-empty. Useful before calling RasCmdr.compute_plan_linux().

Parameters:

Name Type Description Default
plan_number Union[str, Number]

Plan number to check (e.g., "01", 1).

required
ras_object RasPrj

Optional RasPrj instance. If None, uses global ras.

None

Returns:

Type Description
bool

True if all three files exist and are non-empty.

Example

if RasPreprocess.verify_preprocessing("01"): ... RasCmdr.compute_plan_linux("01", ras_exe_dir="/opt/hecras/6.6") ... else: ... RasPreprocess.preprocess_plan("01")

Source code in ras_commander/RasPreprocess.py
Python
@staticmethod
@log_call
def verify_preprocessing(
    plan_number: Union[str, Number],
    ras_object=None,
) -> bool:
    """
    Check if prerequisite files for Linux execution exist.

    Verifies that .tmp.hdf, .b##, and .x## files exist and are non-empty.
    Useful before calling ``RasCmdr.compute_plan_linux()``.

    Args:
        plan_number: Plan number to check (e.g., "01", 1).
        ras_object (RasPrj, optional): Optional RasPrj instance. If None, uses global ras.

    Returns:
        bool: True if all three files exist and are non-empty.

    Example:
        >>> if RasPreprocess.verify_preprocessing("01"):
        ...     RasCmdr.compute_plan_linux("01", ras_exe_dir="/opt/hecras/6.6")
        ... else:
        ...     RasPreprocess.preprocess_plan("01")
    """
    ras_obj = ras_object if ras_object is not None else ras

    if isinstance(plan_number, Number):
        plan_num = f"{int(plan_number):02d}"
    else:
        plan_num = str(plan_number).zfill(2)

    try:
        ras_obj.check_initialized()
    except Exception:
        return False

    project_folder = Path(ras_obj.project_folder)
    project_name = ras_obj.project_name

    # Determine geometry number
    geometry_number = None
    try:
        plan_row = ras_obj.plan_df[ras_obj.plan_df['plan_number'] == plan_num]
        if not plan_row.empty and 'Geom File' in plan_row.columns:
            geom_ref = str(plan_row['Geom File'].iloc[0])
            m = re.search(r'(\d+)', geom_ref)
            if m:
                geometry_number = m.group(1)
    except Exception:
        pass

    if geometry_number is None:
        plan_path = RasPlan.get_plan_path(plan_num, ras_obj)
        if plan_path:
            geometry_number = RasPreprocess._extract_geometry_number(Path(plan_path))
        if geometry_number is None:
            return False

    tmp_hdf = project_folder / f"{project_name}.p{plan_num}.tmp.hdf"
    b_file = project_folder / f"{project_name}.b{plan_num}"
    x_file = project_folder / f"{project_name}.x{geometry_number}"

    for f in [tmp_hdf, b_file, x_file]:
        if not f.exists() or f.stat().st_size == 0:
            logger.debug(f"Missing or empty: {f.name}")
            return False

    logger.debug("All preprocessing files verified for plan %s", plan_num)
    return True

preprocess_plan() runs Windows HEC-RAS through native Windows Python or Windows Python hosted by Wine. For ordinary plans it stops at either the detailed .bco signal or an owned RasUnsteady.exe descendant after .tmp.hdf, .b##, and .x## are all non-empty. The returned PreprocessResult.signal_source records which path was used. First-run legal-assent dialogs are reported as blockers and are never accepted automatically.

Gridded precipitation has a stricter readiness gate. The unsteady-flow HDF contains the authored source payload under Event Conditions/Meteorology/Precipitation/Imported Raster Data; HEC-RAS preprocessing must materialize the solver-facing Precipitation/Values and Precipitation/Timestamp datasets in the temporary plan HDF. The .bco marker can precede that handoff, so preprocess_plan() waits for fresh, complete preprocessing artifacts and validates both materialized datasets before reporting success. Plans without gridded precipitation retain the owned solver-process fallback. Treat a failed PreprocessResult as a failed precompute; do not launch the native solver with an incomplete temporary HDF.

Point precipitation can be missing because HEC-RAS's own RasProcess.exe CompletePreProcess intermittently writes none ("No valid precipitation time-series data found for this time-window") while Ras.exe exits 0. preprocess_plan() then re-runs only that step on the same temporary HDF, from the project folder, up to precipitation_repair_attempts times (default 6; 0 disables) and re-validates after each attempt. PreprocessResult.precipitation_repair_attempts records each attempt, and a repaired result reports signal_source="completepreprocess_repair". See point precipitation repair.

run_ras_geom_preprocess() performs the matching vendor geometry-preprocessor step with a bounded timeout, executable hash, before/after HDF hashes, compute-message parsing, and HDF readability/Geometry-group validation.

BcoMonitor Utility

BcoMonitor dataclass

Monitor HEC-RAS .bco file for execution signals and messages.

The .bco file is created when 'Write Detailed= 1' is set in the plan file. It contains detailed computation messages written incrementally during execution.

This class enables: - Real-time progress monitoring via .bco file polling - Message streaming to callbacks - Signal detection for early termination - Thread-safe operation (no shared state)

Attributes:

Name Type Description
project_path Path

Path to HEC-RAS project folder

plan_number str

Plan number (e.g., "01", "02")

project_name str

Project name (without extension)

signal_string str

String to detect in .bco for early termination

check_interval float

Seconds between .bco file polls (default: 0.5)

max_wait_seconds float

Maximum wait time before timeout (default: 300)

message_callback Optional[Callable[[str], None]]

Optional callback for new messages

blocking_condition Optional[Callable[[], Optional[str]]]

Optional callback returning a diagnostic when a known modal condition prevents progress

alternate_signal_condition Optional[Callable[[], bool]]

Optional callback for an equivalent, job-scoped readiness signal when the .bco file remains empty

alternate_signal_description Optional[str]

Human-readable alternate signal name

Example

monitor = BcoMonitor( ... project_path=Path("/path/to/project"), ... plan_number="01", ... project_name="MyProject", ... message_callback=lambda msg: print(msg) ... ) process = subprocess.Popen(["RAS.exe", ...]) signal_detected = monitor.monitor_until_signal(process)

Source code in ras_commander/RasBco.py
Python
@dataclass
class BcoMonitor:
    """
    Monitor HEC-RAS .bco file for execution signals and messages.

    The .bco file is created when 'Write Detailed= 1' is set in the plan file.
    It contains detailed computation messages written incrementally during execution.

    This class enables:
    - Real-time progress monitoring via .bco file polling
    - Message streaming to callbacks
    - Signal detection for early termination
    - Thread-safe operation (no shared state)

    Attributes:
        project_path: Path to HEC-RAS project folder
        plan_number: Plan number (e.g., "01", "02")
        project_name: Project name (without extension)
        signal_string: String to detect in .bco for early termination
        check_interval: Seconds between .bco file polls (default: 0.5)
        max_wait_seconds: Maximum wait time before timeout (default: 300)
        message_callback: Optional callback for new messages
        blocking_condition: Optional callback returning a diagnostic when a
            known modal condition prevents progress
        alternate_signal_condition: Optional callback for an equivalent,
            job-scoped readiness signal when the .bco file remains empty
        alternate_signal_description: Human-readable alternate signal name

    Example:
        >>> monitor = BcoMonitor(
        ...     project_path=Path("/path/to/project"),
        ...     plan_number="01",
        ...     project_name="MyProject",
        ...     message_callback=lambda msg: print(msg)
        ... )
        >>> process = subprocess.Popen(["RAS.exe", ...])
        >>> signal_detected = monitor.monitor_until_signal(process)
    """

    # Configuration
    project_path: Path
    plan_number: str
    project_name: str
    signal_string: str = "Starting Unsteady Flow Computations"
    check_interval: float = 0.5
    max_wait_seconds: float = 300.0

    # Optional callback for streaming messages
    message_callback: Optional[Callable[[str], None]] = None

    # Optional probes used by process-owning callers such as RasPreprocess.
    blocking_condition: Optional[Callable[[], Optional[str]]] = None
    alternate_signal_condition: Optional[Callable[[], bool]] = None
    alternate_signal_description: Optional[str] = None

    # Internal state (initialized in __post_init__)
    bco_file: Path = field(init=False)
    execution_start_time: Optional[float] = field(default=None, init=False)
    _last_file_position: int = field(default=0, init=False)
    _callback_error_logged: bool = field(default=False, init=False)
    _blocking_probe_error_logged: bool = field(default=False, init=False)
    _alternate_probe_error_logged: bool = field(default=False, init=False)
    blocked_reason: Optional[str] = field(default=None, init=False)
    signal_source: Optional[str] = field(default=None, init=False)

    def __post_init__(self):
        """Initialize paths and validate configuration."""
        self.bco_file = self.project_path / f"{self.project_name}.bco{self.plan_number}"
        logger.debug(f"BcoMonitor initialized for {self.bco_file.name}")

    @staticmethod
    def enable_detailed_logging(plan_file_path: Path) -> bool:
        """
        Enable detailed logging in a plan file by setting 'Write Detailed= 1'.

        This creates a .bcoXX file during HEC-RAS execution that can be monitored
        for the "Starting Unsteady Flow Computations" signal and other messages.

        Args:
            plan_file_path: Path to the plan file (.pXX)

        Returns:
            bool: True if successful, False otherwise

        Note:
            This modifies the plan file in-place. The modification is safe and
            follows HEC-RAS plan file format conventions.
        """
        try:
            content = plan_file_path.read_text(encoding='utf-8', errors='ignore')

            # Check if Write Detailed line exists
            if "Write Detailed=" in content:
                # Replace existing setting
                new_content = re.sub(
                    r'Write Detailed=\s*\d+',
                    'Write Detailed= 1',
                    content
                )
                if new_content != content:
                    _write_ras_text(plan_file_path, new_content, encoding="utf-8")
                    logger.debug(f"Enabled detailed logging in {plan_file_path.name}")
            else:
                # Add the setting after Run HTab line or at the end
                if "Run HTab=" in content:
                    new_content = content.replace(
                        "Run HTab=",
                        "Write Detailed= 1\nRun HTab="
                    )
                else:
                    new_content = content + "\nWrite Detailed= 1\n"
                _write_ras_text(plan_file_path, new_content, encoding="utf-8")
                logger.debug(f"Added detailed logging setting to {plan_file_path.name}")

            return True
        except Exception as e:
            logger.warning(f"Could not enable detailed logging in {plan_file_path.name}: {e}")
            logger.debug(f"Detailed logging plan file path: {plan_file_path}")
            return False

    def monitor_until_signal(self, process: subprocess.Popen) -> bool:
        """
        Monitor .bco file until signal string appears or process completes.

        This method polls the .bco file at regular intervals, checking for:
        1. Process completion (normal exit or crash)
        2. Signal string detection (for early termination)
        3. New messages (streamed to callback if provided)

        Args:
            process: Running subprocess.Popen instance

        Returns:
            bool: True if signal detected, False if process completed without signal

        Note:
            - This is a blocking call that returns when signal appears or process exits
            - Callbacks are invoked from the calling thread (not a new thread)
            - File is read incrementally to minimize I/O overhead
        """
        self.execution_start_time = time.time()
        deadline = time.monotonic() + float(self.max_wait_seconds)

        logger.info(f"Monitoring {self.bco_file.name} for '{self.signal_string}' signal...")

        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                break
            # Check if process died
            if process.poll() is not None:
                if process.returncode == 0:
                    logger.debug(
                        f"Process for plan {self.plan_number} exited with code 0 "
                        f"while monitoring {self.bco_file.name}"
                    )
                else:
                    logger.warning(
                        f"Process for plan {self.plan_number} exited with code "
                        f"{process.returncode} while monitoring {self.bco_file.name}"
                    )
                # Read any final messages
                if self.bco_file.exists():
                    self._read_and_callback_new_content()
                return False

            if self.blocking_condition is not None:
                try:
                    blocked_reason = self.blocking_condition()
                except Exception as e:
                    if not self._blocking_probe_error_logged:
                        logger.warning(f"Blocking-condition probe failed: {e}")
                        self._blocking_probe_error_logged = True
                else:
                    if blocked_reason:
                        self.blocked_reason = str(blocked_reason)
                        logger.error(self.blocked_reason)
                        return False

            if self.alternate_signal_condition is not None:
                try:
                    alternate_detected = self.alternate_signal_condition()
                except Exception as e:
                    if not self._alternate_probe_error_logged:
                        logger.warning(f"Alternate signal probe failed: {e}")
                        self._alternate_probe_error_logged = True
                else:
                    if alternate_detected:
                        description = (
                            self.alternate_signal_description
                            or "alternate completion condition"
                        )
                        self.signal_source = "alternate"
                        logger.info(f"Detected {description}")
                        return True

            # Check for .bco file with signal detection
            if self.bco_file.exists():
                # Verify file was modified after we started execution
                file_mtime = self.bco_file.stat().st_mtime
                if file_mtime >= self.execution_start_time:
                    # Read new content and check for signal
                    content = self._read_and_callback_new_content()
                    if content and self.signal_string in content:
                        self.signal_source = "bco"
                        logger.info(f"Detected '{self.signal_string}' in {self.bco_file.name}")
                        return True

            time.sleep(min(float(self.check_interval), remaining))

        logger.warning(
            f"Monitoring {self.bco_file.name} timed out after "
            f"{self.max_wait_seconds}s waiting for '{self.signal_string}'"
        )
        logger.debug(f"Timed out monitoring .bco file path: {self.bco_file}")
        return False

    def get_final_messages(self) -> Optional[str]:
        """
        Read complete .bco file content after execution.

        Returns:
            Optional[str]: Full .bco file content, or None if file doesn't exist

        Note:
            Uses encoding resilience (errors='ignore') to handle partially written files.
        """
        if not self.bco_file.exists():
            return None

        try:
            return self.bco_file.read_text(encoding='utf-8', errors='ignore')
        except Exception as e:
            logger.debug(f"Could not read .bco file {self.bco_file}: {e}")
            return None

    def _read_and_callback_new_content(self) -> Optional[str]:
        """
        Read new content since last position and invoke callback if provided.

        Returns:
            Optional[str]: New content read, or None if error/no new content

        Note:
            Updates internal _last_file_position to track reading progress.
        """
        try:
            # Get current file size
            file_size = self.bco_file.stat().st_size

            # No new content since last read
            if file_size <= self._last_file_position:
                return None

            # Read from last position to current end
            with open(self.bco_file, 'r', encoding='utf-8', errors='ignore') as f:
                f.seek(self._last_file_position)
                new_content = f.read()
                self._last_file_position = f.tell()

            # Invoke callback with new content if provided
            if new_content and self.message_callback:
                # Split into lines and call back for each non-empty line
                for line in new_content.splitlines():
                    if line.strip():
                        try:
                            self.message_callback(line)
                        except Exception as e:
                            if not self._callback_error_logged:
                                logger.warning(
                                    f"Callback error while monitoring {self.bco_file.name}: {e}"
                                )
                                logger.debug(f"Callback failure .bco path: {self.bco_file}")
                                self._callback_error_logged = True
                            else:
                                logger.debug(
                                    f"Repeated callback error while monitoring "
                                    f"{self.bco_file}: {e}"
                                )

            return new_content

        except Exception as e:
            logger.debug(f"Could not read new .bco content from {self.bco_file}: {e}")
            return None

    def has_signal(self) -> bool:
        """
        Check if signal string exists in .bco file.

        Returns:
            bool: True if signal detected, False otherwise
        """
        content = self.get_final_messages()
        return content is not None and self.signal_string in content
enable_detailed_logging staticmethod
Python
enable_detailed_logging(plan_file_path: Path) -> bool

Enable detailed logging in a plan file by setting 'Write Detailed= 1'.

This creates a .bcoXX file during HEC-RAS execution that can be monitored for the "Starting Unsteady Flow Computations" signal and other messages.

Parameters:

Name Type Description Default
plan_file_path Path

Path to the plan file (.pXX)

required

Returns:

Type Description
bool

True if successful, False otherwise

Note

This modifies the plan file in-place. The modification is safe and follows HEC-RAS plan file format conventions.

Source code in ras_commander/RasBco.py
Python
@staticmethod
def enable_detailed_logging(plan_file_path: Path) -> bool:
    """
    Enable detailed logging in a plan file by setting 'Write Detailed= 1'.

    This creates a .bcoXX file during HEC-RAS execution that can be monitored
    for the "Starting Unsteady Flow Computations" signal and other messages.

    Args:
        plan_file_path: Path to the plan file (.pXX)

    Returns:
        bool: True if successful, False otherwise

    Note:
        This modifies the plan file in-place. The modification is safe and
        follows HEC-RAS plan file format conventions.
    """
    try:
        content = plan_file_path.read_text(encoding='utf-8', errors='ignore')

        # Check if Write Detailed line exists
        if "Write Detailed=" in content:
            # Replace existing setting
            new_content = re.sub(
                r'Write Detailed=\s*\d+',
                'Write Detailed= 1',
                content
            )
            if new_content != content:
                _write_ras_text(plan_file_path, new_content, encoding="utf-8")
                logger.debug(f"Enabled detailed logging in {plan_file_path.name}")
        else:
            # Add the setting after Run HTab line or at the end
            if "Run HTab=" in content:
                new_content = content.replace(
                    "Run HTab=",
                    "Write Detailed= 1\nRun HTab="
                )
            else:
                new_content = content + "\nWrite Detailed= 1\n"
            _write_ras_text(plan_file_path, new_content, encoding="utf-8")
            logger.debug(f"Added detailed logging setting to {plan_file_path.name}")

        return True
    except Exception as e:
        logger.warning(f"Could not enable detailed logging in {plan_file_path.name}: {e}")
        logger.debug(f"Detailed logging plan file path: {plan_file_path}")
        return False
monitor_until_signal
Python
monitor_until_signal(process: Popen) -> bool

Monitor .bco file until signal string appears or process completes.

This method polls the .bco file at regular intervals, checking for: 1. Process completion (normal exit or crash) 2. Signal string detection (for early termination) 3. New messages (streamed to callback if provided)

Parameters:

Name Type Description Default
process Popen

Running subprocess.Popen instance

required

Returns:

Type Description
bool

True if signal detected, False if process completed without signal

Note
  • This is a blocking call that returns when signal appears or process exits
  • Callbacks are invoked from the calling thread (not a new thread)
  • File is read incrementally to minimize I/O overhead
Source code in ras_commander/RasBco.py
Python
def monitor_until_signal(self, process: subprocess.Popen) -> bool:
    """
    Monitor .bco file until signal string appears or process completes.

    This method polls the .bco file at regular intervals, checking for:
    1. Process completion (normal exit or crash)
    2. Signal string detection (for early termination)
    3. New messages (streamed to callback if provided)

    Args:
        process: Running subprocess.Popen instance

    Returns:
        bool: True if signal detected, False if process completed without signal

    Note:
        - This is a blocking call that returns when signal appears or process exits
        - Callbacks are invoked from the calling thread (not a new thread)
        - File is read incrementally to minimize I/O overhead
    """
    self.execution_start_time = time.time()
    deadline = time.monotonic() + float(self.max_wait_seconds)

    logger.info(f"Monitoring {self.bco_file.name} for '{self.signal_string}' signal...")

    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            break
        # Check if process died
        if process.poll() is not None:
            if process.returncode == 0:
                logger.debug(
                    f"Process for plan {self.plan_number} exited with code 0 "
                    f"while monitoring {self.bco_file.name}"
                )
            else:
                logger.warning(
                    f"Process for plan {self.plan_number} exited with code "
                    f"{process.returncode} while monitoring {self.bco_file.name}"
                )
            # Read any final messages
            if self.bco_file.exists():
                self._read_and_callback_new_content()
            return False

        if self.blocking_condition is not None:
            try:
                blocked_reason = self.blocking_condition()
            except Exception as e:
                if not self._blocking_probe_error_logged:
                    logger.warning(f"Blocking-condition probe failed: {e}")
                    self._blocking_probe_error_logged = True
            else:
                if blocked_reason:
                    self.blocked_reason = str(blocked_reason)
                    logger.error(self.blocked_reason)
                    return False

        if self.alternate_signal_condition is not None:
            try:
                alternate_detected = self.alternate_signal_condition()
            except Exception as e:
                if not self._alternate_probe_error_logged:
                    logger.warning(f"Alternate signal probe failed: {e}")
                    self._alternate_probe_error_logged = True
            else:
                if alternate_detected:
                    description = (
                        self.alternate_signal_description
                        or "alternate completion condition"
                    )
                    self.signal_source = "alternate"
                    logger.info(f"Detected {description}")
                    return True

        # Check for .bco file with signal detection
        if self.bco_file.exists():
            # Verify file was modified after we started execution
            file_mtime = self.bco_file.stat().st_mtime
            if file_mtime >= self.execution_start_time:
                # Read new content and check for signal
                content = self._read_and_callback_new_content()
                if content and self.signal_string in content:
                    self.signal_source = "bco"
                    logger.info(f"Detected '{self.signal_string}' in {self.bco_file.name}")
                    return True

        time.sleep(min(float(self.check_interval), remaining))

    logger.warning(
        f"Monitoring {self.bco_file.name} timed out after "
        f"{self.max_wait_seconds}s waiting for '{self.signal_string}'"
    )
    logger.debug(f"Timed out monitoring .bco file path: {self.bco_file}")
    return False
ExecutionCallback Protocol

ExecutionCallback

Bases: Protocol

Protocol for execution progress callbacks.

This defines the interface for monitoring HEC-RAS computation lifecycle. Implementations can provide any subset of these methods - all are optional.

Lifecycle Hooks (terminal ordering depends on the execution outcome): 1. on_prep_start() - Before plan setup 2. on_prep_complete() - After plan setup, before engine preprocessing 3. on_exec_start() - Immediately before HEC-RAS subprocess launch 4. on_exec_message() - During execution (potentially many calls) 5. on_exec_complete() - HEC-RAS subprocess finished 6. on_verify_result() - After HDF verification (if verify=True)

Thread Safety

compute_plan() accepts stream_callback; compute_parallel() and compute_test_mode() do not. If caller-managed threads share a callback, protect shared state with locks, thread-local storage, or atomic operations.

Example - Simple Console Logging

class ConsoleCallback: ... def on_exec_start(self, plan_number, command): ... print(f"[{plan_number}] Starting...") ... def on_exec_message(self, plan_number, message): ... print(f"[{plan_number}] {message}") ... def on_exec_complete(self, plan_number, success, duration): ... print(f"[{plan_number}] Done in {duration:.1f}s")

Example - Thread-Safe File Logging

from threading import Lock class FileCallback: ... def init(self): ... self.lock = Lock() ... self.files = {} ... def on_exec_start(self, plan_number, command): ... with self.lock: ... self.files[plan_number] = open(f"plan_{plan_number}.log", 'w') ... def on_exec_message(self, plan_number, message): ... with self.lock: ... if plan_number in self.files: ... self.files[plan_number].write(message + '\n')

Source code in ras_commander/ExecutionCallback.py
Python
@runtime_checkable
class ExecutionCallback(Protocol):
    """
    Protocol for execution progress callbacks.

    This defines the interface for monitoring HEC-RAS computation lifecycle.
    Implementations can provide any subset of these methods - all are optional.

    Lifecycle Hooks (terminal ordering depends on the execution outcome):
        1. on_prep_start()     - Before plan setup
        2. on_prep_complete()  - After plan setup, before engine preprocessing
        3. on_exec_start()     - Immediately before HEC-RAS subprocess launch
        4. on_exec_message()   - During execution (potentially many calls)
        5. on_exec_complete()  - HEC-RAS subprocess finished
        6. on_verify_result()  - After HDF verification (if verify=True)

    Thread Safety:
        compute_plan() accepts stream_callback; compute_parallel() and
        compute_test_mode() do not. If caller-managed threads share a callback,
        protect shared state with locks, thread-local storage, or atomic operations.

    Example - Simple Console Logging:
        >>> class ConsoleCallback:
        ...     def on_exec_start(self, plan_number, command):
        ...         print(f"[{plan_number}] Starting...")
        ...     def on_exec_message(self, plan_number, message):
        ...         print(f"[{plan_number}] {message}")
        ...     def on_exec_complete(self, plan_number, success, duration):
        ...         print(f"[{plan_number}] Done in {duration:.1f}s")

    Example - Thread-Safe File Logging:
        >>> from threading import Lock
        >>> class FileCallback:
        ...     def __init__(self):
        ...         self.lock = Lock()
        ...         self.files = {}
        ...     def on_exec_start(self, plan_number, command):
        ...         with self.lock:
        ...             self.files[plan_number] = open(f"plan_{plan_number}.log", 'w')
        ...     def on_exec_message(self, plan_number, message):
        ...         with self.lock:
        ...             if plan_number in self.files:
        ...                 self.files[plan_number].write(message + '\\n')
    """

    def on_prep_start(self, plan_number: str) -> None:
        """
        Called before plan setup, including preprocessor-file clearing and core setup.

        This is invoked before:
        - Geometry preprocessor file clearing (if clear_geompre=True)
        - Number of cores configuration (if num_cores specified)

        Args:
            plan_number: Plan identifier (e.g., "01", "02")

        Thread Safety:
            Protect shared state if caller-managed threads share this callback.
        """
        ...

    def on_prep_complete(self, plan_number: str) -> None:
        """
        Called after plan setup completes; engine preprocessing may still be required.

        This is invoked after:
        - Geometry preprocessor files cleared (if applicable)
        - Number of cores set in plan file (if applicable)
        - Just before HEC-RAS subprocess starts

        Args:
            plan_number: Plan identifier (e.g., "01", "02")

        Thread Safety:
            Protect shared state if caller-managed threads share this callback.
        """
        ...

    def on_exec_start(self, plan_number: str, command: str) -> None:
        """
        Called immediately before launching the HEC-RAS subprocess.

        This is invoked immediately before subprocess execution begins.
        The command includes the full command line that will be executed.

        Args:
            plan_number: Plan identifier (e.g., "01", "02")
            command: Full version-specific command line (for example, HEC-RAS
                6.0+ uses '"C:/RAS/RAS.exe" -c project.prj plan.p01').

        Note:
            At this point the subprocess has been constructed but not yet started.
            This is the last callback before HEC-RAS begins running.

        Thread Safety:
            Protect shared state if caller-managed threads share this callback.
        """
        ...

    def on_exec_message(self, plan_number: str, message: str) -> None:
        """
        Called for each new .bco file message during execution.

        This is invoked repeatedly as HEC-RAS writes to the .bco file.
        Messages are streamed line-by-line in near real-time (polling interval: 0.5s).

        Args:
            plan_number: Plan identifier (e.g., "01", "02")
            message: Single line from .bco file (newline stripped)

        Frequency:
            - Called potentially hundreds or thousands of times per plan
            - Frequency depends on HEC-RAS computation complexity
            - Polling interval: 0.5 seconds (configurable in BcoMonitor)

        Performance:
            - Keep callback implementation FAST (< 1ms recommended)
            - Avoid blocking I/O, network calls, or heavy computation
            - For expensive operations, queue messages and process in separate thread

        Thread Safety:
            Protect shared state if caller-managed threads share this callback.
            CRITICAL: Implement proper locking if writing to shared resources.

        Example Messages:
            - "Geometry Preprocessor Version 6.6"
            - "Computing Cross Section HTAB's"
            - "Starting Unsteady Flow Computations"
            - "Time: 01JAN2020 0600 [  1.25% Done]"
        """
        ...

    def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
        """
        Called when HEC-RAS execution finishes.

        This reports the execution-phase outcome. Later artifact handling can
        still change the final ComputeResult.success value.

        Args:
            plan_number: Plan identifier (e.g., "01", "02")
            success: Execution-phase success under the selected engine contract;
                not necessarily equivalent to a zero launcher return code
            duration: Execution time in seconds (floating point)

        Note:
            - success=True does NOT guarantee HEC-RAS succeeded (it may have errors)
            - Use on_verify_result() to check if HDF contains "Complete Process"
            - duration is wall-clock time, not CPU time

        Thread Safety:
            Protect shared state if caller-managed threads share this callback.
        """
        ...

    def on_verify_result(self, plan_number: str, verified: bool) -> None:
        """
        Called after HDF verification (only if verify=True parameter used).

        This is invoked after checking HDF file for "Complete Process" message.

        Args:
            plan_number: Plan identifier (e.g., "01", "02")
            verified: True if HDF contains "Complete Process", False otherwise

        Note:
            - Only called when RasCmdr.compute_plan(..., verify=True)
            - verified=True reports completion evidence, not hydraulic acceptance
              or successful later artifact handling
            - verified=False may indicate computation errors or incomplete results

        Thread Safety:
            Protect shared state if caller-managed threads share this callback.
        """
        ...
on_prep_start
Python
on_prep_start(plan_number: str) -> None

Called before plan setup, including preprocessor-file clearing and core setup.

This is invoked before: - Geometry preprocessor file clearing (if clear_geompre=True) - Number of cores configuration (if num_cores specified)

Parameters:

Name Type Description Default
plan_number str

Plan identifier (e.g., "01", "02")

required
Thread Safety

Protect shared state if caller-managed threads share this callback.

Source code in ras_commander/ExecutionCallback.py
Python
def on_prep_start(self, plan_number: str) -> None:
    """
    Called before plan setup, including preprocessor-file clearing and core setup.

    This is invoked before:
    - Geometry preprocessor file clearing (if clear_geompre=True)
    - Number of cores configuration (if num_cores specified)

    Args:
        plan_number: Plan identifier (e.g., "01", "02")

    Thread Safety:
        Protect shared state if caller-managed threads share this callback.
    """
    ...
on_prep_complete
Python
on_prep_complete(plan_number: str) -> None

Called after plan setup completes; engine preprocessing may still be required.

This is invoked after: - Geometry preprocessor files cleared (if applicable) - Number of cores set in plan file (if applicable) - Just before HEC-RAS subprocess starts

Parameters:

Name Type Description Default
plan_number str

Plan identifier (e.g., "01", "02")

required
Thread Safety

Protect shared state if caller-managed threads share this callback.

Source code in ras_commander/ExecutionCallback.py
Python
def on_prep_complete(self, plan_number: str) -> None:
    """
    Called after plan setup completes; engine preprocessing may still be required.

    This is invoked after:
    - Geometry preprocessor files cleared (if applicable)
    - Number of cores set in plan file (if applicable)
    - Just before HEC-RAS subprocess starts

    Args:
        plan_number: Plan identifier (e.g., "01", "02")

    Thread Safety:
        Protect shared state if caller-managed threads share this callback.
    """
    ...
on_exec_start
Python
on_exec_start(plan_number: str, command: str) -> None

Called immediately before launching the HEC-RAS subprocess.

This is invoked immediately before subprocess execution begins. The command includes the full command line that will be executed.

Parameters:

Name Type Description Default
plan_number str

Plan identifier (e.g., "01", "02")

required
command str

Full version-specific command line (for example, HEC-RAS 6.0+ uses '"C:/RAS/RAS.exe" -c project.prj plan.p01').

required
Note

At this point the subprocess has been constructed but not yet started. This is the last callback before HEC-RAS begins running.

Thread Safety

Protect shared state if caller-managed threads share this callback.

Source code in ras_commander/ExecutionCallback.py
Python
def on_exec_start(self, plan_number: str, command: str) -> None:
    """
    Called immediately before launching the HEC-RAS subprocess.

    This is invoked immediately before subprocess execution begins.
    The command includes the full command line that will be executed.

    Args:
        plan_number: Plan identifier (e.g., "01", "02")
        command: Full version-specific command line (for example, HEC-RAS
            6.0+ uses '"C:/RAS/RAS.exe" -c project.prj plan.p01').

    Note:
        At this point the subprocess has been constructed but not yet started.
        This is the last callback before HEC-RAS begins running.

    Thread Safety:
        Protect shared state if caller-managed threads share this callback.
    """
    ...
on_exec_message
Python
on_exec_message(plan_number: str, message: str) -> None

Called for each new .bco file message during execution.

This is invoked repeatedly as HEC-RAS writes to the .bco file. Messages are streamed line-by-line in near real-time (polling interval: 0.5s).

Parameters:

Name Type Description Default
plan_number str

Plan identifier (e.g., "01", "02")

required
message str

Single line from .bco file (newline stripped)

required
Frequency
  • Called potentially hundreds or thousands of times per plan
  • Frequency depends on HEC-RAS computation complexity
  • Polling interval: 0.5 seconds (configurable in BcoMonitor)
Performance
  • Keep callback implementation FAST (< 1ms recommended)
  • Avoid blocking I/O, network calls, or heavy computation
  • For expensive operations, queue messages and process in separate thread
Thread Safety

Protect shared state if caller-managed threads share this callback. CRITICAL: Implement proper locking if writing to shared resources.

Example Messages
  • "Geometry Preprocessor Version 6.6"
  • "Computing Cross Section HTAB's"
  • "Starting Unsteady Flow Computations"
  • "Time: 01JAN2020 0600 [ 1.25% Done]"
Source code in ras_commander/ExecutionCallback.py
Python
def on_exec_message(self, plan_number: str, message: str) -> None:
    """
    Called for each new .bco file message during execution.

    This is invoked repeatedly as HEC-RAS writes to the .bco file.
    Messages are streamed line-by-line in near real-time (polling interval: 0.5s).

    Args:
        plan_number: Plan identifier (e.g., "01", "02")
        message: Single line from .bco file (newline stripped)

    Frequency:
        - Called potentially hundreds or thousands of times per plan
        - Frequency depends on HEC-RAS computation complexity
        - Polling interval: 0.5 seconds (configurable in BcoMonitor)

    Performance:
        - Keep callback implementation FAST (< 1ms recommended)
        - Avoid blocking I/O, network calls, or heavy computation
        - For expensive operations, queue messages and process in separate thread

    Thread Safety:
        Protect shared state if caller-managed threads share this callback.
        CRITICAL: Implement proper locking if writing to shared resources.

    Example Messages:
        - "Geometry Preprocessor Version 6.6"
        - "Computing Cross Section HTAB's"
        - "Starting Unsteady Flow Computations"
        - "Time: 01JAN2020 0600 [  1.25% Done]"
    """
    ...
on_exec_complete
Python
on_exec_complete(plan_number: str, success: bool, duration: float) -> None

Called when HEC-RAS execution finishes.

This reports the execution-phase outcome. Later artifact handling can still change the final ComputeResult.success value.

Parameters:

Name Type Description Default
plan_number str

Plan identifier (e.g., "01", "02")

required
success bool

Execution-phase success under the selected engine contract; not necessarily equivalent to a zero launcher return code

required
duration float

Execution time in seconds (floating point)

required
Note
  • success=True does NOT guarantee HEC-RAS succeeded (it may have errors)
  • Use on_verify_result() to check if HDF contains "Complete Process"
  • duration is wall-clock time, not CPU time
Thread Safety

Protect shared state if caller-managed threads share this callback.

Source code in ras_commander/ExecutionCallback.py
Python
def on_exec_complete(self, plan_number: str, success: bool, duration: float) -> None:
    """
    Called when HEC-RAS execution finishes.

    This reports the execution-phase outcome. Later artifact handling can
    still change the final ComputeResult.success value.

    Args:
        plan_number: Plan identifier (e.g., "01", "02")
        success: Execution-phase success under the selected engine contract;
            not necessarily equivalent to a zero launcher return code
        duration: Execution time in seconds (floating point)

    Note:
        - success=True does NOT guarantee HEC-RAS succeeded (it may have errors)
        - Use on_verify_result() to check if HDF contains "Complete Process"
        - duration is wall-clock time, not CPU time

    Thread Safety:
        Protect shared state if caller-managed threads share this callback.
    """
    ...
on_verify_result
Python
on_verify_result(plan_number: str, verified: bool) -> None

Called after HDF verification (only if verify=True parameter used).

This is invoked after checking HDF file for "Complete Process" message.

Parameters:

Name Type Description Default
plan_number str

Plan identifier (e.g., "01", "02")

required
verified bool

True if HDF contains "Complete Process", False otherwise

required
Note
  • Only called when RasCmdr.compute_plan(..., verify=True)
  • verified=True reports completion evidence, not hydraulic acceptance or successful later artifact handling
  • verified=False may indicate computation errors or incomplete results
Thread Safety

Protect shared state if caller-managed threads share this callback.

Source code in ras_commander/ExecutionCallback.py
Python
def on_verify_result(self, plan_number: str, verified: bool) -> None:
    """
    Called after HDF verification (only if verify=True parameter used).

    This is invoked after checking HDF file for "Complete Process" message.

    Args:
        plan_number: Plan identifier (e.g., "01", "02")
        verified: True if HDF contains "Complete Process", False otherwise

    Note:
        - Only called when RasCmdr.compute_plan(..., verify=True)
        - verified=True reports completion evidence, not hydraulic acceptance
          or successful later artifact handling
        - verified=False may indicate computation errors or incomplete results

    Thread Safety:
        Protect shared state if caller-managed threads share this callback.
    """
    ...

All callback methods are optional - implement only what you need. The protocol uses @runtime_checkable for flexible duck-typing.

RasControl

HECRASController API wrapper with ras-commander style interface.

Works with legacy HEC-RAS versions (3.x-4.x) that use COM interface instead of HDF files. Integrates with ras-commander project management.

Usage (ras-commander style): >>> from ras_commander import init_ras_project, RasControl >>> >>> # Initialize with version (with or without periods) >>> init_ras_project(path, "4.1") # or "41" >>> >>> # Use plan numbers like HDF methods >>> RasControl.run_plan("02") >>> df = RasControl.get_steady_results("02")

Supported Versions

All installed versions: 3.x, 4.x, 5.0.x, 6.0-6.7+ Accepts formats: "4.1", "41", "5.0.6", "506", "7.0", "66", etc.

cleanup_orphans staticmethod

Python
cleanup_orphans(interactive: bool = True, dry_run: bool = False) -> int

Clean up orphaned ras.exe processes from crashed Python sessions.

This method ONLY terminates processes that: 1. Were started by RasControl (have session lock files) 2. Have a dead parent Python process 3. Are still running

Parameters:

Name Type Description Default
interactive bool

If True, prompts user for confirmation before cleanup

True
dry_run bool

If True, only reports what would be cleaned (no action)

False

Returns:

Type Description
int

Number of processes cleaned up

Example

Interactive cleanup (prompts for confirmation)

RasControl.cleanup_orphans()

Automatic cleanup (no prompts)

count = RasControl.cleanup_orphans(interactive=False) print(f"Cleaned {count} orphans")

Dry run (see what would be cleaned)

RasControl.cleanup_orphans(dry_run=True)

force_cleanup_all staticmethod

Python
force_cleanup_all() -> int

NUCLEAR OPTION: Terminate ALL ras.exe processes on the system.

⚠️ WARNING: This will kill: - Your tracked processes - Other users' processes - Manual HEC-RAS GUI sessions - Other Python scripts' processes

Requires explicit "YES" confirmation to prevent accidental use.

Returns:

Type Description
int

Number of processes terminated

Example

Prompts for "YES" confirmation

RasControl.force_cleanup_all()

get_comp_msgs staticmethod

Python
get_comp_msgs(plan: Union[str, Path], ras_object=None) -> str

Read computation messages from .txt file with fallback to HDF.

The comp_msgs file is created by HEC-RAS during plan computation and contains detailed messages about the computation process, including warnings, errors, and convergence information.

This method checks multiple naming patterns (version-dependent): - .comp_msgs.txt (HEC-RAS 3.x-5.x COM interface) - .computeMsgs.txt (HEC-RAS 6.x+) - .bco## (HEC-RAS 5.x detailed compute output)

If no text file exists, falls back to HDF extraction.

Parameters:

Name Type Description Default
plan Union[str, Path]

Plan number ("01", "02"), project .prj path, or exact .p## / .p##.hdf path. Direct plan/HDF paths resolve only adjacent files and do not require an initialized project or HEC-RAS.

required
ras_object RasPrj

Optional RasPrj instance (uses global ras if None)

None

Returns:

Type Description
str

String containing computation messages, or empty string if unavailable

Example

from ras_commander import init_ras_project, RasControl init_ras_project(path, "4.1") msgs = RasControl.get_comp_msgs("08") print(msgs)

Note

File naming conventions vary by HEC-RAS version: - COM interface: {plan_file}.comp_msgs.txt - HEC-RAS 6.x+: {plan_file}.computeMsgs.txt - HEC-RAS 5.x: {project_name}.bco{plan_number} If several filesystem sidecars exist, all are inspected and the first is returned in the fixed order listed above. A warning identifies the additional candidates. Falls back to HDF: /Results/Summary/Compute Messages (text)

get_controller_progid staticmethod

Python
get_controller_progid(version: str) -> str

Return ras-commander's configured Controller ProgID for a version.

This performs a static mapping; COM registration is checked only when the Controller is dispatched. Exact product identities remain distinct from patch releases: 6.3 and 6.3.0.2 resolve to RAS630.HECRASController while 6.3.1 resolves to RAS631.HECRASController.

get_output_times staticmethod

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

Get list of output times for unsteady run.

Parameters:

Name Type Description Default
plan Union[str, Path]

Plan number ("01", "02") or path to .prj file

required
ras_object RasPrj

Optional RasPrj instance (uses global ras if None)

None

Returns:

Type Description
List[str]

List of time strings (e.g., ["01JAN2000 0000", ...])

Example

times = RasControl.get_output_times("01") print(f"Found {len(times)} output times")

get_plans staticmethod

Python
get_plans(plan: Union[str, Path], ras_object=None) -> List[dict]

Get list of plans in project.

Parameters:

Name Type Description Default
plan Union[str, Path]

Plan number or path to .prj file

required
ras_object RasPrj

Optional RasPrj instance

None

Returns:

Type Description
List[dict]

List of dicts with 'name' and 'filename' keys

get_steady_results staticmethod

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

Extract steady state profile results from HEC-RAS via COM interface.

Opens HEC-RAS, loads the specified plan, extracts water surface elevations and hydraulic parameters for all profiles at all cross sections, then closes HEC-RAS.

Parameters

plan : str or Path Plan number (e.g., "01", "02") or full path to .prj file ras_object : RasPrj, optional RAS project object. If None, uses global ras object.

Returns

pd.DataFrame Steady state results with one row per cross-section per profile

Text Only
**Schema:**

+----------------+----------+---------------------------------------+
| Column         | Type     | Description                           |
+================+==========+=======================================+
| river          | str      | River name                            |
+----------------+----------+---------------------------------------+
| reach          | str      | Reach name                            |
+----------------+----------+---------------------------------------+
| node_id        | str      | Cross section river station           |
+----------------+----------+---------------------------------------+
| profile        | str      | Profile name (e.g., "PF 1", "50Pct")  |
+----------------+----------+---------------------------------------+
| wsel           | float    | Water surface elevation (ft or m)     |
+----------------+----------+---------------------------------------+
| velocity       | float    | Total velocity (ft/s or m/s)          |
+----------------+----------+---------------------------------------+
| flow           | float    | Total flow (cfs or cms)               |
+----------------+----------+---------------------------------------+
| froude         | float    | Channel Froude number (dimensionless) |
+----------------+----------+---------------------------------------+
| energy         | float    | Energy grade elevation (ft or m)      |
+----------------+----------+---------------------------------------+
| max_depth      | float    | Maximum channel depth (ft or m)       |
+----------------+----------+---------------------------------------+
| min_ch_el      | float    | Minimum channel elevation (ft or m)   |
+----------------+----------+---------------------------------------+

**Note on data types:**

- String columns (`river`, `reach`, `node_id`, `profile`) are decoded
    from COM byte strings and stripped of whitespace
- Numeric columns are float64
- Units depend on project settings (US customary or SI)
Raises

ValueError - If project not initialized with version - If plan number not found in project RuntimeError - If no steady state results found - If model run was not successful

Notes

Comparison with HDF Methods:

This COM-based method returns MORE data than the HDF-based HdfResultsPlan.get_steady_wse(), which only returns WSE. RasControl includes velocity, flow, Froude, energy, and depths.

Performance Notes:

  • HEC-RAS is opened and closed for each call (not persistent)
  • For HEC-RAS 6.0+, HDF methods may offer better performance
  • COM interface is single-threaded
Examples

Extract steady results for Plan 02:

from ras_commander import init_ras_project, RasControl init_ras_project(path, "4.1") df = RasControl.get_steady_results("02") df.to_csv('steady_results.csv', index=False)

Plot water surface profile:

import matplotlib.pyplot as plt profile_data = df[df['profile'] == 'PF 1'] plt.plot(profile_data['node_id'].astype(float), ... profile_data['wsel']) plt.xlabel('Station') plt.ylabel('Water Surface Elevation (ft)') plt.show()

See Also

get_unsteady_results : Extract unsteady time series run_plan : Run a plan before extracting results HdfResultsPlan.get_steady_wse : Modern HDF-based steady extraction

References

For comparison with HDF-based methods, see: feature_dev_notes/rascontrol_vs_hdf_comparison.md

get_unsteady_results staticmethod

Python
get_unsteady_results(plan: Union[str, Path], max_times: Optional[int] = None, ras_object=None) -> pd.DataFrame

Extract unsteady flow time series results from HEC-RAS via COM interface.

Opens HEC-RAS, loads the specified plan, extracts all computed time series data including the critical "Max WS" row, then closes HEC-RAS.

Parameters

plan : str or Path Plan number (e.g., "01", "02") or full path to .prj file. max_times : int, optional Maximum number of timesteps to extract. If None, extracts all timesteps. Note: "Max WS" row is always included and doesn't count toward this limit. ras_object : RasPrj, optional RAS project object. If None, uses global ras object.

Returns

pd.DataFrame Unsteady flow time series with one row per cross-section per timestep, plus one "Max WS" row per cross-section containing computational maximums.

Text Only
**Schema:**

+-----------------+----------------+-------------------------------------------+
| Column          | Type           | Description                               |
+=================+================+===========================================+
| river           | str            | River name                                |
+-----------------+----------------+-------------------------------------------+
| reach           | str            | Reach name                                |
+-----------------+----------------+-------------------------------------------+
| node_id         | str            | Cross section river station               |
+-----------------+----------------+-------------------------------------------+
| time_index      | int            | 1-based timestep index                    |
|                 |                | 1 = "Max WS", 2+ = actual timesteps       |
+-----------------+----------------+-------------------------------------------+
| time_string     | str            | RAS datetime format "01JAN2000 0000"      |
|                 |                | or "Max WS" for maximum value row         |
+-----------------+----------------+-------------------------------------------+
| datetime        | datetime64[ns] | Parsed timestamp                          |
|                 |                | pd.NaT for "Max WS" rows                  |
+-----------------+----------------+-------------------------------------------+
| wsel            | float          | Water surface elevation (ft or m)         |
+-----------------+----------------+-------------------------------------------+
| velocity        | float          | Total velocity (ft/s or m/s)              |
+-----------------+----------------+-------------------------------------------+
| flow            | float          | Total flow (cfs or cms)                   |
+-----------------+----------------+-------------------------------------------+
| froude          | float          | Channel Froude number (dimensionless)     |
+-----------------+----------------+-------------------------------------------+
| energy          | float          | Energy grade elevation (ft or m)          |
+-----------------+----------------+-------------------------------------------+
| max_depth       | float          | Maximum channel depth (ft or m)           |
+-----------------+----------------+-------------------------------------------+
| min_ch_el       | float          | Minimum channel elevation (ft or m)       |
+-----------------+----------------+-------------------------------------------+

**Units depend on project settings (US Customary or SI).**
Raises

ValueError - If project not initialized with version - If plan not found in project RuntimeError - If no unsteady results found - If HEC-RAS computation was not successful

Notes

Understanding "Max WS" Rows:

The "Max WS" row (time_index=1, time_string="Max WS") contains the maximum value at ANY computational timestep, not just the output intervals. This is critical for design applications because:

  • HEC-RAS computes at finer intervals than it outputs
  • Peak values often occur between output timesteps
  • "Max WS" captures the true computational maximum

To separate "Max WS" from time series data:

Python
>>> df_max = df[df['time_string'] == 'Max WS']
>>> df_timeseries = df[df['datetime'].notna()]  # Excludes Max WS (has NaT)

New in v0.81.0:

The datetime column is now included automatically as datetime64[ns] objects. Users no longer need to manually parse time_string. For backward compatibility, time_string is still included.

Performance Notes:

  • HEC-RAS is opened and closed for each call (not persistent)
  • For large time series, consider using HDF-based methods for better performance
  • COM interface is single-threaded
Examples

Extract and plot time series at a cross section:

Python
>>> from ras_commander import init_ras_project, RasControl
>>> import matplotlib.pyplot as plt
>>>
>>> init_ras_project(path, "4.1")
>>> df = RasControl.get_unsteady_results("01")
>>>
>>> # Separate max WS from time series
>>> df_max = df[df['time_string'] == 'Max WS']
>>> df_ts = df[df['datetime'].notna()]
>>>
>>> # Plot time series for specific cross section
>>> xs_data = df_ts[df_ts['node_id'] == '10000'].sort_values('datetime')
>>> plt.plot(xs_data['datetime'], xs_data['wsel'])
>>> plt.axhline(df_max[df_max['node_id'] == '10000']['wsel'].iloc[0],
...             color='r', linestyle='--', label='Max WS')
>>> plt.xlabel('Date/Time')
>>> plt.ylabel('WSE (ft)')
>>> plt.legend()
>>> plt.show()

Filter to specific time range using datetime column:

Python
>>> import pandas as pd
>>> start = pd.Timestamp('1999-02-18')
>>> end = pd.Timestamp('1999-02-20')
>>> filtered = df_ts[(df_ts['datetime'] >= start) & (df_ts['datetime'] <= end)]
See Also

get_steady_results : Extract steady state profile results get_output_times : List available timesteps before extracting run_plan : Run a plan before extracting results HdfResultsXsec.get_xsec_timeseries : Modern HDF-based extraction (returns xarray)

References

For comparison with HDF-based methods, see: feature_dev_notes/rascontrol_vs_hdf_comparison.md

inspect_processes staticmethod

Python
inspect_processes() -> RasProcessInventory

Return a strict host-wide HEC-RAS process inventory.

Unlike :meth:list_processes, this safety-oriented API includes exact legacy and modern HEC-RAS launcher, solver, sediment/water-quality, and geometry-preprocessor names. It preserves PID plus creation-time identity and reports every query failure. Active sessions are tracked by that complete identity, never PID alone. Callers must require result.complete before treating an empty inventory as proof that the host is clear.

Returns:

Type Description
RasProcessInventory

Immutable, JSON-safe process evidence.

list_processes staticmethod

Python
list_processes(show_all: bool = False) -> pd.DataFrame

List ras.exe processes with tracking status.

Parameters:

Name Type Description Default
show_all bool

If True, show all ras.exe processes. If False (default), only show processes tracked by this Python session.

False

Returns:

Type Description
DataFrame with columns

pid, tracked, project, age_sec, status

Example

Show only tracked processes

df = RasControl.list_processes() print(df)

Show all ras.exe on system

df_all = RasControl.list_processes(show_all=True) print(df_all)

run_plan staticmethod

Python
run_plan(plan: Union[str, Path], ras_object=None, force_recompute: bool = False, use_watchdog: bool = True, max_runtime: int = 86400, refresh_results: bool = True, *, blocking: bool = False, controller_version: Optional[str] = None, strict_close: bool = False, observe_dialogs: bool = False) -> RasControlResult

Run a plan (steady or unsteady) and wait for completion.

This method checks if results are current before running. If results are up-to-date, it skips computation (unless force_recompute=True). HEC-RAS 4.0/4.1 always wait inside their two-argument Compute_CurrentPlan call. HEC-RAS 5+ defaults to asynchronous execution followed by Compute_Complete() polling; blocking=True instead passes the modern Controller's blocking argument.

Parameters:

Name Type Description Default
plan Union[str, Path]

Plan number ("01", "02") or path to .prj file

required
ras_object RasPrj

Optional RasPrj instance (uses global ras if None)

None
force_recompute bool

If False (default), checks if results are current before running. If results are up-to-date, skips computation. If True, always runs the plan regardless of current status. Defaults to False.

False
use_watchdog bool

If True, spawns independent watchdog process that will terminate ras.exe if Python crashes/kernel restarts. Provides protection against orphaned processes in Jupyter notebooks. Defaults to True (recommended). Set to False to disable.

True
max_runtime int

Maximum runtime in seconds. The nonblocking Controller poll loop enforces this deadline. An inherently blocking 4.x call or explicit modern blocking call requires an independent watchdog or caller supervisor to interrupt a stalled call; same-thread code can only reject a late return afterwards. Defaults to 86400 (24 hours).

86400
refresh_results bool

Refresh plan_df and results_df after the controller returns. Disable for compute-only validation when detailed legacy result extraction is unnecessary. Defaults to True.

True
blocking bool

For modern Controllers, pass the blocking flag to Compute_CurrentPlan instead of polling Compute_Complete. Legacy 4.0/4.1 are inherently blocking for either value and receive exactly two arguments, with no unsupported third flag. This is required by exact HEC-RAS 6.3.0.2 batch execution. Defaults to False for backward compatibility.

False
controller_version Optional[str]

Optional exact Controller product identity. Use "6.3.0.2" to select RAS630.HECRASController while leaving the project's executable family label unchanged.

None
strict_close bool

Require the resolved Controller's safe-close contract after an otherwise successful operation. For HEC-RAS 5+, a QuitRas() failure raises. HEC-RAS 4.0/4.1 do not expose QuitRas() and instead require exact owned-process cleanup and confirmed exit. A surviving owned ras.exe always fails plan execution, including in the default non-strict mode. Defaults to False for compatibility with recoverable modern QuitRas() failures.

False
observe_dialogs bool

Opt in to exact Controller dialog observation before Project_Open. Records dialogs for the proved PID, creation time, executable path, and SHA-256; unknown dialogs are preserved. Only the exact reviewed optional example-install prompt may be declined. Requires available Windows observation support and confirmed observer shutdown. Default False preserves existing behavior. Evidence is returned as dialog_observation inside execution_details and attached to observed COM exceptions.

False

Returns:

Type Description
RasControlResult

Result object backward compatible with Tuple[bool, List[str]]. success: Whether execution succeeded. messages: List of computation messages. results_df_row: Single row from results_df (pd.Series or None). execution_details: JSON-safe Controller identity, compute mode, completion method, close capability/method, watchdog, message-count, timing provenance, owned PID plus creation time, verified Ras.exe path and SHA-256, safe-close/owned-exit state, post-close plan/global process quiescence, result-family finalization, and exact preparation and finalization cleanup records. In those records, result_format names the family targeted for deletion. Calculated success requires every terminal gate. Existing code success, msgs = RasControl.run_plan("01") still works via iter.

Example

from ras_commander import init_ras_project, RasControl init_ras_project(path, "4.1")

Old usage (still works):

success, msgs = RasControl.run_plan("02")

New usage:

result = RasControl.run_plan("02") if result: ... print(result.results_df_row)

Force recomputation even if results are current

success, msgs = RasControl.run_plan("02", force_recompute=True)

success, msgs = RasControl.run_plan("01", use_watchdog=False)

Long-running with extended timeout

success, msgs = RasControl.run_plan("01", max_runtime=7200)

Exact HEC-RAS 6.3.0.2 under an outer batch supervisor

result = RasControl.run_plan( ... "01", blocking=True, controller_version="6.3.0.2", ... use_watchdog=False, strict_close=True, ... refresh_results=False, ... )

Note

Can take several minutes for large models or unsteady runs. Progress is logged every 30 seconds. If PlanOutput_IsCurrent() check fails (e.g., older HEC-RAS versions), the plan will be run as a safe fallback.

Watchdog protection (use_watchdog=True): - Spawns independent Python process monitoring parent death - Survives kernel restarts and crashes - Automatically terminates orphaned ras.exe processes - Enforces max_runtime timeout

When computation occurs, the selected controller version governs permanent, plan-scoped result cleanup. HEC-RAS 5+ preserves HDF; HEC-RAS 3-4 preserves legacy .O##. Skipped runs do not mutate execution artifacts. Before any plan mutation or cleanup, live Controller execution requires a complete and empty strict global HEC-RAS process inventory. This intentionally enforces exclusive host use; an incomplete or occupied inventory raises while preserving existing plan artifacts.

scan_orphans staticmethod

Python
scan_orphans() -> List[SessionLock]

Scan lock files for orphaned sessions from crashed Python processes.

Returns:

Type Description
List[SessionLock]

List of SessionLock objects for orphaned processes (Python dead,

List[SessionLock]

ras.exe still running).

Example

orphans = RasControl.scan_orphans() if orphans: print(f"Found {len(orphans)} orphaned processes") for orphan in orphans: print(f" PID {orphan.ras_pid}: {Path(orphan.project_path).name}")

set_current_plan staticmethod

Python
set_current_plan(plan: Union[str, Path], ras_object=None) -> bool

Set the current/active plan by plan number.

Note: This is rarely needed - run_plan() and get_*_results() automatically set the correct plan. This is provided for advanced use cases.

Parameters:

Name Type Description Default
plan Union[str, Path]

Plan number ("01", "02") or path to .prj file

required
ras_object RasPrj

Optional RasPrj instance

None

Returns:

Type Description
bool

True if successful

Example

RasControl.set_current_plan("02") # Set to Plan 02

RasControl Details

Open-Operate-Close Pattern

Unlike other ras-commander classes, RasControl opens HEC-RAS, performs one operation, then closes it. This prevents conflicts with modern workflows and ensures clean resource management.

Supported Versions
Version Registry Key HEC-RAS Years
"31" 3.1 Legacy
"41" 4.1 ~2008-2014
"501", "503", "505", "506" 5.0.x 2015-2019
"60" 6.0 2020
"63" 6.3 2021-2022
"66" 6.6 2023-2024
"70" 7.0 2025+
RasControl vs RasCmdr
Aspect RasControl RasCmdr
HEC-RAS Versions 3.x - 7.x (COM) 5.x+ (command line)
Data Source Live COM extraction HDF file results
Requires GUI Yes (HEC-RAS installed) Yes (HEC-RAS installed)
Use Case Legacy models, validation Modern automation
Returns pandas DataFrame bool / dict
Understanding "Max WS" in Unsteady Results

When extracting unsteady results, the first row per cross section (time_index=1) contains "Max WS" - the maximum at ANY computational timestep:

Python
# Unsteady results include special "Max WS" row
df = RasControl.get_unsteady_results("01")

# time_index=1 is "Max WS" (maximum at any timestep)
df_max = df[df['time_string'] == 'Max WS']

# time_index=2+ are actual output intervals
df_timeseries = df[df['time_string'] != 'Max WS']

# Parse datetime for analysis
df_timeseries['datetime'] = pd.to_datetime(
    df_timeseries['time_string'],
    format='%d%b%Y %H%M'
)

Max WS vs Output Interval Maximums

"Max WS" captures peaks that may occur BETWEEN output intervals. This is critical for design applications - always use "Max WS" for peak values, not max() of output intervals.

Result Columns

Steady Results (get_steady_results):

Column Type Description
river str River name
reach str Reach name
node_id str Cross section station
profile str Profile name
wsel float Water surface elevation
velocity float Total velocity
flow float Total flow
froude float Froude number
energy float Energy grade elevation
max_depth float Maximum channel depth
min_ch_el float Minimum channel elevation

Unsteady Results (get_unsteady_results): Same columns plus time_index, time_string, datetime.

Compute Messages Fallback

The get_comp_msgs() method attempts to read computation messages from multiple sources:

  1. First tries .computeMsgs.txt (modern format)
  2. Falls back to .comp_msgs.txt (legacy format)
  3. Returns empty string if neither exists

File Operations

RasPlan

A class for operations on HEC-RAS plan files.

add_hdf_output_variable staticmethod

Python
add_hdf_output_variable(plan_number_or_path: Union[str, Number, Path], variable: str, ras_object=None, *, target_ras_version: Optional[Union[str, float, Path]] = None) -> bool

Add an HDF output variable to a HEC-RAS plan file.

This enables additional output variables in the HDF results file, such as Face Flow, which is needed for discharge-weighted velocity calculations.

Parameters:

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

The plan number or path to the plan file.

required
variable str

The variable name to add (e.g., "Face Flow", "Face Shear Stress").

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None
target_ras_version str, float, or Path

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

None

Returns:

Type Description
bool

True if added, already present, or an always-written default; False on error.

Supported Variables
  • "Face Flow" - Flow rate across each face (needed for discharge-weighted velocity)
  • "Face Shear Stress" - Shear stress at each face
  • "Face Cumulative Volume" - Cumulative volume through each face
  • "Cell Cumulative Precipitation Depth" - Cumulative precipitation per cell
  • "Cell Courant" - Courant number per cell
Notes

Catalogue labels and the baseline result names Water Surface and Face Velocity are accepted. Enabling either baseline name logs at INFO that it is always written for computed 2D results and leaves the plan unchanged, including any existing line for that name. Known legacy short tokens are normalized to full labels with a warning, including existing matching short-token records. Unknown labels raise ValueError before writing. The 14 spiral/curvature labels require a declared Program Version of 7.0+ (unknown versions warn) unless target_ras_version names the version that will run, in which case that version is the gate. Required physics still controls output. See HDF_OUTPUT_VARIABLE_DATASETS for observed dataset basenames. Face Point (Node) Velocities* is retained with a warning: the 6.6/7.0.1 pilot wrote no node data, and its working token is unresolved.

Example

Enable Face Flow output before running a plan

RasPlan.add_hdf_output_variable('02', 'Face Flow') RasCmdr.compute_plan('02')

apply_hdf_output_profile staticmethod

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

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

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

Parameters:

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

Plan number or path to the plan file.

required
profile str

One of balanced, speed, size, or nas.

'balanced'
additional_variables Optional[List[str]]

Optional additional HDF output variables to enable.

None
ras_object RasPrj

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

None
target_ras_version str, float, or Path

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

None

Returns:

Type Description
bool

True when all requested updates succeeded.

clone_geom staticmethod

Python
clone_geom(template_geom: Union[str, Number], ras_object=None) -> str

Copy geometry files from a template, find the next geometry number, and update the project file accordingly.

.. deprecated:: Use :meth:RasGeo.clone_geom instead, which supports new_title and description parameters.

Parameters: template_geom (Union[str, Number]): Geometry number to use as template (e.g., '01', 1, or 1.0) ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: str: New geometry number (e.g., '03')

Example:

String input

new_geom_num = RasPlan.clone_geom('01')

Integer input also works

new_geom_num = RasPlan.clone_geom(1)

Note

This function updates the ras object's dataframes after modifying the project structure.

clone_plan staticmethod

Python
clone_plan(template_plan: Union[str, Number], new_shortid=None, new_plan_shortid=None, new_title=None, geometry: Union[str, Number] = None, unsteady_flow: Union[str, Number] = None, steady_flow: Union[str, Number] = None, num_cores: int = None, intervals: Dict = None, run_flags: Dict = None, description: str = None, ras_object=None) -> str

Create a new plan file based on a template and optionally configure it.

This function clones a plan file and can optionally configure multiple settings in one call, reducing the need for separate function calls.

Parameters: template_plan (Union[str, Number]): Plan number to use as template (e.g., '01', 1, or 1.0) new_shortid (str, optional): New short identifier for the plan file (max 24 chars). If not provided, appends '_copy' to original. Alias: new_plan_shortid (for improved clarity) new_plan_shortid (str, optional): Alias for new_shortid. If both are provided, new_plan_shortid takes precedence. new_title (str, optional): New plan title (max 32 chars, updates "Plan Title=" line). If not provided, keeps original title. geometry (Union[str, Number], optional): Geometry file number to assign to the new plan. unsteady_flow (Union[str, Number], optional): Unsteady flow file number to assign. steady_flow (Union[str, Number], optional): Steady flow file number to assign. num_cores (int, optional): Number of compute cores to use. intervals (Dict, optional): Plan intervals to set. Keys can include: - 'computation' or 'computation_interval': e.g., '5SEC', '1MIN' - 'output' or 'output_interval': e.g., '15MIN', '1HOUR' - 'mapping' or 'mapping_interval': e.g., '1HOUR' - 'hydrograph' or 'hydrograph_output_interval': e.g., '15MIN' run_flags (Dict, optional): Run flags to set. Keys can include: - 'geometry_preprocessor': bool - 'unsteady_flow_simulation': bool - 'post_processor': bool - 'floodplain_mapping': bool - 'sediment': bool - 'water_quality': bool description (str, optional): Plan description text. ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: str: New plan number

Example:

Simple clone (original behavior)

new_plan = RasPlan.clone_plan('01')

Clone with full configuration in one call

new_plan = RasPlan.clone_plan( ... '01', ... new_plan_shortid='Sensitivity_01', ... geometry='01', ... unsteady_flow='02', ... num_cores=4, ... intervals={'computation': '5SEC', 'output': '1MIN'}, ... run_flags={'geometry_preprocessor': True, 'unsteady_flow_simulation': True}, ... description='Sensitivity run with modified Manning's n' ... )

Note

Both new_shortid and new_title are optional. new_plan_shortid is an alias for new_shortid for improved clarity. Configuration parameters are applied after the clone is created. This function updates the ras object's dataframes after modifying the project structure.

clone_steady staticmethod

Python
clone_steady(template_flow: Union[str, Number], new_title=None, ras_object=None)

Copy steady flow files from a template, find the next flow number, and update the project file accordingly.

Parameters: template_flow (Union[str, Number]): Flow number to use as template (e.g., '01', 1, or 1.0) new_title (str, optional): New flow title (max 32 chars, updates "Flow Title=" line) ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: str: New flow number (e.g., '03')

Example:

String input

new_flow_num = RasPlan.clone_steady('01', ... new_title='Steady Flow - HEC-RAS 4.1') print(f"New steady flow file created: f{new_flow_num}")

Integer input also works

new_flow_num = RasPlan.clone_steady(1)

Note

This function updates the ras object's dataframes after modifying the project structure.

clone_unsteady staticmethod

Python
clone_unsteady(template_unsteady: Union[str, Number], new_title=None, ras_object=None)

Copy unsteady flow files from a template, find the next unsteady number, and update the project file accordingly.

Parameters: template_unsteady (Union[str, Number]): Unsteady flow number to use as template (e.g., '01', 1, or 1.0) new_title (str, optional): New flow title (max 32 chars, updates "Flow Title=" line) ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: str: New unsteady flow number (e.g., '03')

Example:

String input

new_unsteady_num = RasPlan.clone_unsteady('01', ... new_title='Unsteady - HEC-RAS 4.1') print(f"New unsteady flow file created: u{new_unsteady_num}")

Integer input also works

new_unsteady_num = RasPlan.clone_unsteady(1)

Note

This function updates the ras object's dataframes after modifying the project structure.

create_plan_variants staticmethod

Python
create_plan_variants(base_plan: Union[str, Number], variants: DataFrame, naming_template: str = '{variant_name}', ras_object=None) -> pd.DataFrame

Create multiple plan variants from a base plan driven by a DataFrame.

Wraps clone_plan() in a loop, applying per-variant settings from the variants DataFrame. Each row creates one new plan.

Parameters

base_plan : str or Number Plan number to use as template (e.g., '01' or 1) variants : pd.DataFrame DataFrame with variant specifications. Required column: - variant_name: str — name/title for the new plan Optional columns (applied if present): - unsteady_flow: str or Number — unsteady flow file number - steady_flow: str or Number — steady flow file number - geometry: str or Number — geometry file number - num_cores: int — number of computation cores - computation_interval: str — e.g., '5MIN', '1MIN' - output_interval: str — e.g., '15MIN', '1HOUR' - description: str — plan description text naming_template : str, default '{variant_name}' Template for plan title. Supports {variant_name}, {index}, {base_plan} substitutions. ras_object : optional Custom RAS object to use instead of the global one

Returns

pd.DataFrame Report with columns: - variant_name: Name from input DataFrame - plan_number: New plan number assigned - plan_path: Full path to created plan file - status: 'created' or 'error' - message: Details or error message

Example

import pandas as pd from ras_commander import RasPlan variants = pd.DataFrame({ ... 'variant_name': ['6hr Storm', '12hr Storm', '24hr Storm'], ... 'unsteady_flow': ['01', '02', '03'], ... 'description': ['6-hour design storm', '12-hour design storm', '24-hour design storm'] ... }) report = RasPlan.create_plan_variants('01', variants) print(report[['variant_name', 'plan_number', 'status']])

Notes

Plans are created sequentially to ensure proper numbering. After all variants are created, DataFrames are refreshed once via plan_df.

delete_geom staticmethod

Python
delete_geom(geom_number: Union[str, Number], force: bool = False, permanent_delete: bool = False, ras_object=None) -> None

Delete a geometry file and its associated files from the project.

By default, moves the .gXX, .gXX.hdf, and .cXX files to a timestamped Backup folder, then removes the entry from the .prj file.

Parameters: geom_number (Union[str, Number]): Geometry number to delete (e.g., '06', 6) force (bool): If True, allow deletion even if plans reference this geometry. Default False. permanent_delete (bool): If True, permanently delete files. If False (default), move files to {project_folder}/Backup/{timestamp}_deleted_g{number}/. ras_object (RasPrj, optional): Specific RAS object to use.

Raises: ValueError: If the geometry doesn't exist, or if plans reference it and force=False.

Example:

RasPlan.delete_geom("06") # Backs up to Backup/ folder RasPlan.delete_geom("06", force=True, permanent_delete=True) # Permanently deletes

delete_plan staticmethod

Python
delete_plan(plan_number: Union[str, Number], permanent_delete: bool = False, ras_object=None) -> None

Delete a plan and its associated files from the project.

By default, moves the .pXX file and any associated .pXX.hdf, .pXX.computeMsgs.txt, and .pXX.comp_msgs.txt files to a timestamped Backup folder, then removes the entry from the .prj file.

Parameters: plan_number (Union[str, Number]): Plan number to delete (e.g., '05', 5) permanent_delete (bool): If True, permanently delete files. If False (default), move files to {project_folder}/Backup/{timestamp}_deleted_p{number}/. ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Raises: ValueError: If the plan doesn't exist.

Note: If deleting the Current Plan, a warning is logged but deletion proceeds. HEC-RAS will open without errors, but no plan will be active.

Example:

RasPlan.delete_plan("05") # Backs up to Backup/ folder RasPlan.delete_plan("05", permanent_delete=True) # Permanently deletes

delete_steady staticmethod

Python
delete_steady(flow_number: Union[str, Number], force: bool = False, permanent_delete: bool = False, ras_object=None) -> None

Delete a steady flow file from the project.

By default, moves the .fXX file to a timestamped Backup folder, then removes the entry from the .prj file.

Parameters: flow_number (Union[str, Number]): Flow number to delete (e.g., '01', 1) force (bool): If True, allow deletion even if plans reference it. Default False. permanent_delete (bool): If True, permanently delete files. If False (default), move files to {project_folder}/Backup/{timestamp}_deleted_f{number}/. ras_object (RasPrj, optional): Specific RAS object to use.

Raises: ValueError: If the flow file doesn't exist, or if plans reference it and force=False.

Example:

RasPlan.delete_steady("01") # Backs up to Backup/ folder RasPlan.delete_steady("01", permanent_delete=True) # Permanently deletes

delete_unsteady staticmethod

Python
delete_unsteady(unsteady_number: Union[str, Number], force: bool = False, permanent_delete: bool = False, ras_object=None) -> None

Delete an unsteady flow file from the project.

By default, moves the .uXX file and its .hdf companion to a timestamped Backup folder, then removes the entry from the .prj file.

Parameters: unsteady_number (Union[str, Number]): Unsteady number to delete (e.g., '07', 7) force (bool): If True, allow deletion even if plans reference it. Default False. permanent_delete (bool): If True, permanently delete files. If False (default), move files to {project_folder}/Backup/{timestamp}_deleted_u{number}/. ras_object (RasPrj, optional): Specific RAS object to use.

Raises: ValueError: If the unsteady file doesn't exist, or if plans reference it and force=False.

Example:

RasPlan.delete_unsteady("07") # Backs up to Backup/ folder RasPlan.delete_unsteady("07", permanent_delete=True) # Permanently deletes

disable_hdf_output_variable staticmethod

Python
disable_hdf_output_variable(plan_number_or_path: Union[str, Number, Path], variable_name: str, ras_object=None) -> bool

Disable one additional HDF output variable in a plan file.

enable_hdf_output_variable staticmethod

Python
enable_hdf_output_variable(plan_number_or_path: Union[str, Number, Path], variable_name: str, ras_object=None, *, target_ras_version: Optional[Union[str, float, Path]] = None) -> bool

Enable one additional HDF output variable in a plan file.

target_ras_version is passed through to add_hdf_output_variable.

get_2d_flow_options staticmethod

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

Parse 2D unsteady computation options from a HEC-RAS plan file.

Parameters:

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

Plan number or path to the plan file.

required
mesh_name Optional[str]

Optional 2D flow area name to filter the returned areas.

None
ras_object RasPrj

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

None

Returns:

Type Description
Dict[str, Any]

Parsed options with plan, default, and areas sections. Equation-set values are normalized to "DWE" or "SWE-ELM".

get_flow_path staticmethod

Python
get_flow_path(flow_number: Union[str, Number], ras_object=None) -> Optional[Path]

Return the full path for a given flow number.

Args: flow_number (Union[str, Number]): The flow number to search for (e.g., '01', 1, or 1.0). ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: Optional[Path]: The full path of the flow file if found, None otherwise.

Raises: RuntimeError: If the project is not initialized.

Example:

ras_plan = RasPlan() flow_path = ras_plan.get_flow_path('01') if flow_path: ... print(f"Flow file found at: {flow_path}") ... else: ... print("Flow file not found.")

Integer input also works

flow_path = ras_plan.get_flow_path(1)

get_geom_path staticmethod

Python
get_geom_path(geom_number: Union[str, Number], ras_object=None) -> Optional[Path]

Return the full path for a given geometry number.

Args: geom_number (Union[str, Number]): The geometry number to search for (e.g., '01', 1, or 1.0). ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: Optional[Path]: The full path of the geometry file if found, None otherwise.

Raises: RuntimeError: If the project is not initialized.

Example:

ras_plan = RasPlan() geom_path = ras_plan.get_geom_path('01') if geom_path: ... print(f"Geometry file found at: {geom_path}") ... else: ... print("Geometry file not found.")

Integer input also works

geom_path = ras_plan.get_geom_path(1)

get_hdf_output_options staticmethod

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

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

Alias for get_hdf_write_parameters() using output-control naming.

get_hdf_output_variables staticmethod

Python
get_hdf_output_variables(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> List[str]

Get list of additional HDF output variables configured in a plan file.

Parameters:

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

The plan number or path to the plan file.

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Returns:

Type Description
List[str]

List of variable names configured for HDF output.

Example

vars = RasPlan.get_hdf_output_variables('02') print(vars) # ['Face Flow', 'Face Shear Stress']

get_hdf_write_parameters staticmethod

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

Get HDF write parameters configured in a HEC-RAS plan file.

Parameters:

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

Plan number or path to the plan file.

required
ras_object RasPrj

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

None

Returns:

Type Description
Dict[str, Optional[Any]]

HDF write settings keyed by ras-commander parameter name. Missing settings are returned as None.

get_next_number staticmethod

Python
get_next_number(existing_numbers)

Determine the next available number from a list of existing numbers.

Parameters: existing_numbers (list): List of existing numbers as strings

Returns: str: Next available number as a zero-padded string

Example:

existing_numbers = ['01', '02', '04'] RasPlan.get_next_number(existing_numbers) '03' existing_numbers = ['01', '02', '03'] RasPlan.get_next_number(existing_numbers) '04'

get_plan_flow_type staticmethod

Python
get_plan_flow_type(plan_number: str, ras_object=None) -> str

Get flow type for a plan from plan metadata (fast, no HDF required).

Parameters:

Name Type Description Default
plan_number str

Plan number (e.g., "01", "08")

required
ras_object RasPrj

Optional RAS object instance

None

Returns:

Type Description
str

'Steady', 'Unsteady', or 'Unknown'

Notes
  • Uses plan file metadata (already parsed by ras-commander)
  • Deterministic: plans with unsteady_number are Unsteady, others are Steady
  • Does NOT require HDF file to exist
  • Much faster than HDF inspection (reads from memory)

get_plan_path staticmethod

Python
get_plan_path(plan_number: Union[str, Number], ras_object=None) -> Optional[Path]

Return the full path for a given plan number.

This method ensures that the latest plan entries are included by refreshing the plan dataframe before searching for the requested plan number.

Args: plan_number (Union[str, Number]): The plan number to search for (e.g., '01', 1, or 1.0). ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: Optional[Path]: The full path of the plan file if found, None otherwise.

Raises: RuntimeError: If the project is not initialized.

Example:

ras_plan = RasPlan() plan_path = ras_plan.get_plan_path('01') if plan_path: ... print(f"Plan file found at: {plan_path}") ... else: ... print("Plan file not found.")

Integer input also works

plan_path = ras_plan.get_plan_path(1)

get_plan_title staticmethod

Python
get_plan_title(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> str

Get the Plan Title from a HEC-RAS plan file.

Parameters:

Name Type Description Default
plan_number_or_path Union[str, Path]

The plan number or path to the plan file.

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Returns:

Type Description
str

The Plan Title from the plan file.

Raises:

Type Description
ValueError

If the plan file is not found.

IOError

If there's an error reading from the plan file.

Example

title = RasPlan.get_plan_title('01') print(f"Plan Title: {title}")

get_plan_value staticmethod

Python
get_plan_value(plan_number_or_path: Union[str, Path], key: str, ras_object=None) -> Any

Retrieve a specific value from a HEC-RAS plan file.

Parameters: plan_number_or_path (Union[str, Path]): The plan number (1 to 99) or full path to the plan file key (str): The key to retrieve from the plan file ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: Any: The value associated with the specified key

Raises: ValueError: If the plan file is not found IOError: If there's an error reading the plan file

Available keys and their expected types: - 'Computation Interval' (str): Time value for computational time step (e.g., '5SEC', '2MIN') - 'DSS File' (str): Name of the DSS file used - 'Flow File' (str): Name of the flow input file - 'Friction Slope Method' (int): Method selection for friction slope (e.g., 1, 2) - 'Geom File' (str): Name of the geometry input file - 'Mapping Interval' (str): Time interval for mapping output - 'Plan File' (str): Name of the plan file - 'Plan Title' (str): Title of the simulation plan - 'Program Version' (str): Version number of HEC-RAS - 'Run HTab' (int): Flag to run HTab module (-1 or 1) - 'Run Post Process' (int): Flag to run post-processing (-1 or 1) - 'Run Sediment' (int): Flag to run sediment transport module (0 or 1) - 'Run UNET' (int): Flag to run unsteady network module (-1 or 1) - 'Run WQNET' (int): Flag to run water quality module (0 or 1) - 'Short Identifier' (str): Short name or ID for the plan - 'Simulation Date' (str): Start and end dates/times for simulation - 'UNET D1 Cores' (int): Number of cores used in 1D calculations - 'UNET D2 Cores' (int): Number of cores used in 2D calculations - 'PS Cores' (int): Number of cores used in parallel simulation - 'UNET Use Existing IB Tables' (int): Flag for using existing internal boundary tables (-1, 0, or 1) - 'UNET 1D Methodology' (str): 1D calculation methodology - 'UNET D2 Solver Type' (str): 2D solver type - 'UNET D2 Name' (str): Name of the 2D area - 'Run RASMapper' (int): Flag to run RASMapper for floodplain mapping (-1 for on, 0 for off)

Note: Writing Multi line keys like 'Description' are not supported by this function.

Example:

computation_interval = RasPlan.get_plan_value("01", "Computation Interval") print(f"Computation interval: {computation_interval}")

get_restart_output_settings staticmethod

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

Get restart/Hot Start output settings from a HEC-RAS plan file.

HEC-RAS stores restart-file creation settings in the plan file using Write IC File keys. These settings control writing restart files. They do not control whether a subsequent unsteady-flow file uses a restart file; use RasUnsteady.get_restart_settings() and RasUnsteady.set_restart_settings() for that separate usage setting.

Parameters:

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

Plan number or explicit plan-file path.

required
ras_object RasPrj

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

None

Returns:

Type Description
Dict[str, Optional[Any]]

Parsed restart-output settings, including raw HEC-RAS keys for auditability.

get_results_path staticmethod

Python
get_results_path(plan_number: Union[str, Number], ras_object=None) -> Optional[Path]

Retrieve the results file path for a given HEC-RAS plan number.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

The HEC-RAS plan number for which to find the results path (e.g., '02', 2, or 2.0).

required
ras_object RasPrj

Specific RAS object to use. If None, uses the global ras instance.

None

Returns:

Type Description
Optional[Path]

The full path to the results file if found and the file exists, or None if not found.

Raises:

Type Description
RuntimeError

If the project is not initialized.

Example

ras_plan = RasPlan() results_path = ras_plan.get_results_path('01') if results_path: ... print(f"Results file found at: {results_path}") ... else: ... print("Results file not found.")

get_sediment_output_variables staticmethod

Python
get_sediment_output_variables(plan_number_or_path: Union[str, Number, Path], ras_object: Optional[RasPrj] = None) -> dict

Read the sediment output configuration from a plan file.

HEC-RAS only writes optional per-cell 2D sediment results (e.g. active-layer gradation Cell Active Layer Percentile Diameters - D50) when the plan requests them via Sediment Output Variables= lines. This returns the current requests so they can be inspected or extended.

Parameters:

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

The plan number (str, int, or float) or path to the plan file.

required
ras_object Optional[RasPrj]

The RAS project object. Defaults to None.

None

Returns:

Type Description
dict

{"output_level": Optional[int], "variables": List[str]}.

Raises:

Type Description
ValueError

If the plan file is not found.

get_shortid staticmethod

Python
get_shortid(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> str

Get the Short Identifier from a HEC-RAS plan file.

Parameters:

Name Type Description Default
plan_number_or_path Union[str, Path]

The plan number or path to the plan file.

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Returns:

Type Description
str

The Short Identifier from the plan file.

Raises:

Type Description
ValueError

If the plan file is not found.

IOError

If there's an error reading from the plan file.

Example

shortid = RasPlan.get_shortid('01') print(f"Plan's Short Identifier: {shortid}")

get_unsteady_path staticmethod

Python
get_unsteady_path(unsteady_number: Union[str, Number], ras_object=None) -> Optional[Path]

Return the full path for a given unsteady number.

Args: unsteady_number (Union[str, Number]): The unsteady number to search for (e.g., '01', 1, or 1.0). ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: Optional[Path]: The full path of the unsteady file if found, None otherwise.

Raises: RuntimeError: If the project is not initialized.

Example:

ras_plan = RasPlan() unsteady_path = ras_plan.get_unsteady_path('01') if unsteady_path: ... print(f"Unsteady file found at: {unsteady_path}") ... else: ... print("Unsteady file not found.")

Integer input also works

unsteady_path = ras_plan.get_unsteady_path(1)

is_plan_steady_state staticmethod

Python
is_plan_steady_state(plan_number: str, ras_object=None) -> bool

Check if a plan is steady state.

Parameters:

Name Type Description Default
plan_number str

Plan number (e.g., "01", "08")

required
ras_object RasPrj

Optional RAS object instance

None

Returns:

Type Description
bool

True if steady state, False otherwise

list_2d_flow_option_names staticmethod

Python
list_2d_flow_option_names() -> Dict[str, str]

List public 2D flow option names and their HEC-RAS plan-file keys.

Returns:

Type Description
Dict[str, str]

ras-commander option names mapped to plan-file keys.

list_available_hdf_output_variables staticmethod

Python
list_available_hdf_output_variables() -> List[str]

List additional 2D HDF output variables known to HEC-RAS plan files.

Baseline results Water Surface and Face Velocity are excluded from this additional-output catalogue. Enabling them is an accepted no-op: they are always written for computed 2D results, an INFO message explains this, and existing plan text is preserved.

The catalogue includes 14 secondary-flow labels requiring HEC-RAS 7.0+ (HDF_OUTPUT_VARIABLE_MIN_VERSIONS). Writers check the plan's declared Program Version; an unknown version warns. Required physics must also be active. HDF_OUTPUT_VARIABLE_DATASETS documents observed one-to-many dataset basenames, including the six Governing Equation Terms arrays; presence and compatible time axes must be checked in the results.

Face Point (Node) Velocities* remains for compatibility, but writes no dataset in the 6.6/7.0.1 pilot (recorded as Face Point Velocities). Its working token is unresolved; enabling it warns instead of promising node velocities. Unmapped labels have no qualified dataset mapping here.

Returns:

Type Description
List[str]

Variable names accepted by HDF Additional Output Variable=... plan-file entries.

list_hdf_output_setting_profiles staticmethod

Python
list_hdf_output_setting_profiles() -> Dict[str, Dict[str, Any]]

List named HDF write-parameter profiles.

Returns:

Type Description
Dict[str, Dict[str, Any]]

Profile names mapped to write parameters.

read_flow_description staticmethod

Python
read_flow_description(flow_number_or_path: Union[str, Number, Path], ras_object=None) -> str

Read the description from a steady flow file (.f##).

Parameters:

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

The flow number (e.g., '01') or path to the flow file.

required
ras_object RasPrj

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

None

Returns:

Type Description
str

The description text, or empty string if not found.

Raises:

Type Description
ValueError

If the flow file is not found.

read_geom_description staticmethod

Python
read_geom_description(geom_number_or_path: Union[str, Number, Path], ras_object=None) -> str

Read the description from a geometry file (.g##).

Parameters:

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

The geometry number (e.g., '01') or path to the geometry file.

required
ras_object RasPrj

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

None

Returns:

Type Description
str

The description text, or empty string if not found.

Raises:

Type Description
ValueError

If the geometry file is not found.

read_plan_description staticmethod

Python
read_plan_description(plan_number_or_path: Union[str, Path], ras_object: Optional[RasPrj] = None) -> str

Read the description from the plan file.

Parameters:

Name Type Description Default
plan_number_or_path Union[str, Path]

The plan number or path to the plan file.

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Returns:

Type Description
str

The description from the plan file.

Raises:

Type Description
ValueError

If the plan file is not found.

IOError

If there's an error reading from the plan file.

remove_hdf_output_variable staticmethod

Python
remove_hdf_output_variable(plan_number_or_path: Union[str, Number, Path], variable: str, ras_object=None) -> bool

Remove an HDF output variable from a HEC-RAS plan file.

Known short aliases and their full labels remove either stored form. Unknown literal labels remain removable without catalogue/version checks.

Parameters:

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

The plan number or path to the plan file.

required
variable str

The variable name to remove.

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Returns:

Type Description
bool

True if variable was removed, False if not found or on error.

Example

RasPlan.remove_hdf_output_variable('02', 'Face Flow')

renumber_geom staticmethod

Python
renumber_geom(old_number: Union[str, Number], new_number: Union[str, Number], ras_object=None) -> str

Renumber a geometry file and update all project references.

Renames .gXX, .gXX.hdf, and .cXX files, updates the .prj file, and updates all plan files that reference this geometry.

Parameters: old_number (Union[str, Number]): Current geometry number (e.g., '06', 6) new_number (Union[str, Number]): New geometry number (e.g., '02', 2) ras_object (RasPrj, optional): Specific RAS object to use.

Returns: str: The new geometry number.

Raises: ValueError: If old geometry doesn't exist or new number already exists.

Example:

RasPlan.renumber_geom("06", "02") '02'

renumber_plan staticmethod

Python
renumber_plan(old_number: Union[str, Number], new_number: Union[str, Number], ras_object=None) -> str

Renumber a plan file and update all project references.

Renames the .pXX file and associated files (.hdf, .computeMsgs.txt, .comp_msgs.txt), updates the .prj file entry, and updates Current Plan if applicable.

Parameters: old_number (Union[str, Number]): Current plan number (e.g., '05', 5) new_number (Union[str, Number]): New plan number (e.g., '02', 2) ras_object (RasPrj, optional): Specific RAS object to use.

Returns: str: The new plan number.

Raises: ValueError: If old plan doesn't exist or new plan number already exists.

Example:

RasPlan.renumber_plan("13", "01") '01'

renumber_steady staticmethod

Python
renumber_steady(old_number: Union[str, Number], new_number: Union[str, Number], ras_object=None) -> str

Renumber a steady flow file and update all project references.

Renames the .fXX file, updates the .prj file, and updates all plan files that reference this steady flow.

Parameters: old_number (Union[str, Number]): Current flow number (e.g., '01', 1) new_number (Union[str, Number]): New flow number (e.g., '02', 2) ras_object (RasPrj, optional): Specific RAS object to use.

Returns: str: The new flow number.

Raises: ValueError: If old flow doesn't exist or new number already exists.

Example:

RasPlan.renumber_steady("01", "02") '02'

renumber_unsteady staticmethod

Python
renumber_unsteady(old_number: Union[str, Number], new_number: Union[str, Number], ras_object=None) -> str

Renumber an unsteady flow file and update all project references.

Renames .uXX and .uXX.hdf files, updates the .prj file, and updates all plan files that reference this unsteady flow.

Parameters: old_number (Union[str, Number]): Current unsteady number (e.g., '07', 7) new_number (Union[str, Number]): New unsteady number (e.g., '02', 2) ras_object (RasPrj, optional): Specific RAS object to use.

Returns: str: The new unsteady number.

Raises: ValueError: If old unsteady doesn't exist or new number already exists.

Example:

RasPlan.renumber_unsteady("07", "02") '02'

set_2d_equation_set staticmethod

Python
set_2d_equation_set(plan_number_or_path: Union[str, Number, Path], equation_set: Union[str, int], mesh_name: Optional[str] = None, computation_interval: Optional[str] = None, initial_conditions_time_hours: Optional[float] = None, include_default: bool = False, ras_object=None) -> bool

Switch a plan's 2D equation set between DWE and SWE-ELM.

Parameters:

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

Plan number or path to the plan file.

required
equation_set Union[str, int]

"DWE"/0 or "SWE-ELM"/1.

required
mesh_name Optional[str]

Optional 2D flow area name. If omitted, all named areas are updated.

None
computation_interval Optional[str]

Optional plan computation interval to update with the equation-set change.

None
initial_conditions_time_hours Optional[float]

Optional 2D initial conditions time.

None
include_default bool

Also update the default unnamed 2D settings block.

False
ras_object RasPrj

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

None

Returns:

Type Description
bool

True when the plan file was updated or already matched.

set_2d_flow_options staticmethod

Python
set_2d_flow_options(plan_number_or_path: Union[str, Number, Path], mesh_name: Optional[str] = None, options: Optional[Dict[str, Any]] = None, equation_set: Optional[Union[str, int]] = None, initial_conditions_time_hours: Optional[float] = None, theta: Optional[float] = None, theta_warmup: Optional[float] = None, water_surface_tolerance: Optional[float] = None, volume_tolerance: Optional[float] = None, max_iterations: Optional[int] = None, ramp_up_fraction: Optional[float] = None, time_slices: Optional[int] = None, eddy_viscosity: Optional[float] = None, transverse_eddy_viscosity: Optional[float] = None, smagorinsky_mixing: Optional[float] = None, boundary_condition_volume_check: Optional[bool] = None, latitude: Optional[float] = None, cores: Optional[int] = None, solver_type: Optional[str] = None, coriolis: Optional[bool] = None, computation_interval: Optional[str] = None, time_step_use_courant: Optional[bool] = None, time_step_use_time_series: Optional[bool] = None, time_step_max_courant: Optional[float] = None, time_step_min_courant: Optional[float] = None, time_step_count_to_double: Optional[int] = None, time_step_max_doubling: Optional[int] = None, time_step_max_halving: Optional[int] = None, time_step_residence_courant: Optional[bool] = None, include_default: bool = False, ras_object=None) -> bool

Set typed 2D unsteady computation options in a HEC-RAS plan file.

Parameters:

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

Plan number or path to the plan file.

required
mesh_name Optional[str]

Optional 2D flow area name. If omitted, all named 2D flow-area sections are updated.

None
options Optional[Dict[str, Any]]

Optional mapping of public option names to values.

None
equation_set Optional[Union[str, int]]

"DWE"/0 or "SWE-ELM"/1.

None
initial_conditions_time_hours Optional[float]

2D initial conditions ramp-up time.

None
include_default bool

Also update the default unnamed 2D settings block.

False
ras_object RasPrj

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

None

Returns:

Type Description
bool

True when the plan file was written or already matched.

set_geom staticmethod

Python
set_geom(plan_number: Union[str, Number], new_geom: Union[str, Number], ras_object=None) -> pd.DataFrame

Set the geometry for the specified plan by updating only the plan file.

Parameters:

Name Type Description Default
plan_number Union[str, Number]

The plan number to update (accepts int, float, numpy types, etc.).

required
new_geom Union[str, Number]

The new geometry number to set (accepts int, float, numpy types, etc.).

required
ras_object RasPrj

An optional RAS object instance.

None

Returns:

Type Description
DataFrame

The updated geometry DataFrame.

Example

updated_geom_df = RasPlan.set_geom('02', '03')

Note

This function updates the Geom File= line in the plan file and updates the ras object's dataframes without modifying the PRJ file.

set_geom_preprocessor staticmethod

Python
set_geom_preprocessor(file_path, run_htab, use_ib_tables, ras_object=None)

Update the simulation plan file to modify the Run HTab and UNET Use Existing IB Tables settings.

Parameters: file_path (str): Path to the simulation plan file (.p06 or similar) that you want to modify. run_htab (int): Value for the Run HTab setting: - 0 : Do not run the geometry preprocessor, use existing geometry tables. - -1 : Run the geometry preprocessor, forcing a recomputation of the geometry tables. use_ib_tables (int): Value for the UNET Use Existing IB Tables setting: - 0 : Use existing interpolation/boundary (IB) tables without recomputing them. - -1 : Do not use existing IB tables, force a recomputation. ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: None

Raises: ValueError: If run_htab or use_ib_tables are not integers or not within the accepted values (0 or -1). FileNotFoundError: If the specified file does not exist. IOError: If there is an error reading or writing the file.

Example:

RasPlan.set_geom_preprocessor('/path/to/project.p06', run_htab=-1, use_ib_tables=0)

Note

This function updates the ras object's dataframes after modifying the project structure.

set_hdf_output_options staticmethod

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

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

Alias for set_hdf_write_parameters() using output-control naming.

set_hdf_output_variable staticmethod

Python
set_hdf_output_variable(plan_number_or_path: Union[str, Number, Path], variable: str, enabled: bool = True, ras_object=None, *, target_ras_version: Optional[Union[str, float, Path]] = None) -> bool

Enable or disable one additional HDF output variable in a plan file.

Enabling follows add_hdf_output_variable label/version validation (including target_ras_version); disabling follows remove_hdf_output_variable legacy-token cleanup and ignores it.

set_hdf_output_variables staticmethod

Python
set_hdf_output_variables(plan_number_or_path: Union[str, Number, Path], variables: List[str], enabled: bool = True, ras_object=None, *, target_ras_version: Optional[Union[str, float, Path]] = None) -> bool

Enable or disable multiple additional HDF output variables in a plan file.

Enabling prevalidates all labels and version gates before any writes. Known short tokens normalize with a warning; unknown labels raise ValueError. Disabling also accepts literal legacy labels for cleanup. Enabling baseline Water Surface or Face Velocity is a no-op with an INFO message; it preserves any existing lines for those names.

Version gate: the 14 HEC-RAS 7.0 secondary-flow labels are gated on the plan's declared Program Version by default. Shipped example plans declare 5.x/6.x even when HEC-RAS 7.0+ will run them, so pass target_ras_version (e.g. "7.0", "7.0.1", or a versioned Ras.exe path) to gate on the version that will actually run. Disabling ignores target_ras_version.

Example

RasPlan.set_hdf_output_variables( ... "03", ["Cell Vorticity"], target_ras_version="7.0.1")

set_hdf_write_parameters staticmethod

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

Set HEC-RAS HDF5 write parameters in a plan file.

Parameters:

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

Plan number or path to the plan file.

required
write_warmup Optional[bool]

Write warmup time steps to output file.

None
write_time_slices Optional[bool]

Write time-sliced steps in addition to basic time steps.

None
hdf_flush Optional[bool]

Commit writes every time step for crash diagnostics.

None
compression Optional[int]

Gzip/deflate compression level, 0 (off, no chunking) to 9.

None
chunk_size_mb Optional[int]

Maximum chunk size in MB.

None
spatial_parts Optional[int]

Number of spatial column groups.

None
use_max_rows Optional[bool]

Use maximum possible time rows per chunk.

None
fixed_rows Optional[int]

Fixed number of time rows when use_max_rows is False.

None
ras_object RasPrj

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

None

Returns:

Type Description
bool

True when the plan file was updated, False on error.

set_num_cores staticmethod

Python
set_num_cores(plan_number: Union[str, Number], num_cores: int, ras_object=None, *, refresh_dataframes: bool = True)

Update the maximum number of cores to use in the HEC-RAS plan file.

Parameters: plan_number (Union[str, Number]): Plan number (e.g., '02', 2, or 2.0) or full path to the plan file num_cores (int): Maximum number of cores to use ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance. refresh_dataframes (bool, optional): Refresh project dataframes after updating the plan. Defaults to True. Set to False when modifying an isolated plan copy.

Returns: None

Number of cores is controlled by the following parameters in the plan file corresponding to 1D, 2D, Pipe Systems and Pump Stations: UNET D1 Cores=
UNET D2 Cores= PS Cores=

A value of "0" uses "All Available" cores, and values of 1 or more specify an explicit number of cores. For complex 1D/2D models with pipe systems, a more complex approach may be needed to optimize performance. (Suggest writing a custom function based on this code). Sets all existing instances of these parameters and inserts missing controls in the default plan scope. An omitted core key must not leave an explicit request using the native runtime's default core count.

Notes on setting num_cores in HEC-RAS: The recommended setting for num_cores is 2 (most efficient) to 8 (most performant) More details in the HEC-Commander Repository Blog "Benchmarking is All You Need" https://github.com/billk-FM/HEC-Commander/blob/main/Blog/7._Benchmarking_Is_All_You_Need.md

Microsoft Windows has a maximum of 64 cores that can be allocated to a single Ras.exe process.

Example:

Using plan number

RasPlan.set_num_cores('02', 4)

Using full path to plan file

RasPlan.set_num_cores('/path/to/project.p02', 4)

Update an isolated copy without refreshing source project metadata

RasPlan.set_num_cores('/staging/project.p02', 4, refresh_dataframes=False)

Note

By default, this function updates the ras object's dataframes after modifying the plan.

set_plan_title staticmethod

Python
set_plan_title(plan_number_or_path: Union[str, Number, Path], new_title: str, ras_object=None) -> None

Set the Plan Title in a HEC-RAS plan file.

Parameters:

Name Type Description Default
plan_number_or_path Union[str, Path]

The plan number or path to the plan file.

required
new_title str

The new Plan Title to set.

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Raises:

Type Description
ValueError

If the plan file is not found.

IOError

If there's an error updating the plan file.

Example

RasPlan.set_plan_title('01', 'Updated Plan Scenario')

set_restart_output_settings staticmethod

Python
set_restart_output_settings(plan_number_or_path: Union[str, Number, Path], enabled: bool = True, save_time_hours: Optional[Union[int, float, str]] = None, save_datetime: Optional[Union[str, Tuple[str, str], datetime]] = None, recurrence_interval_hours: Optional[Union[int, float, str]] = None, write_at_sim_end: bool = False, ras_object=None) -> bool

Configure a plan to write HEC-RAS restart/Hot Start files.

HEC-RAS stores these output-save settings in the plan file as Write IC File keys. A restart file written by a run is named by HEC-RAS from the project name, plan number, and save time (ProjectName.p##.DDMMMYYYY hhmm.rst); the output filename itself is not an independent plan-file field in HEC-RAS 5.x through 7.0.

Parameters:

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

Plan number or explicit plan-file path.

required
enabled bool

Enable restart output. False clears save timing settings.

True
save_time_hours Optional[Union[int, float, str]]

First save time in hours from simulation start.

None
save_datetime Optional[Union[str, Tuple[str, str], datetime]]

First save as datetime, (DDMMMYYYY, hhmm), or "DDMMMYYYY,hhmm".

None
recurrence_interval_hours Optional[Union[int, float, str]]

Hours between subsequent restart writes.

None
write_at_sim_end bool

Also write a restart file at the final time step.

False
ras_object RasPrj

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

None

Returns:

Type Description
bool

True when the plan file was updated or already current.

set_sediment_output_variables staticmethod

Python
set_sediment_output_variables(plan_number_or_path: Union[str, Number, Path], variables: List[str], output_level: Optional[int] = None, append: bool = True, ras_object: Optional[RasPrj] = None) -> None

Request per-cell sediment output variables in a plan file.

HEC-RAS only writes optional 2D sediment results when the plan asks for them. For example, to make HEC-RAS write the active-layer gradation datasets (read by HdfResultsSediment.get_active_layer_grain_class), request the d50/d10/d90 tokens::

Text Only
RasPlan.set_sediment_output_variables(
    plan, ["2D Cell d50 Active", "2D Cell d10 Active", "2D Cell d90 Active"],
    output_level=6, ras_object=ras)

Existing Sediment Output Variables= lines are normalized to sit directly beneath the Sediment Output Level= line.

Parameters:

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

The plan number (str, int, or float) or path to the plan file.

required
variables List[str]

Sediment output variable tokens to request (verbatim HEC-RAS strings, e.g. "2D Cell d50 Active").

required
output_level Optional[int]

If provided, set Sediment Output Level= to this value (gradation outputs typically require level 6).

None
append bool

If True (default), keep existing requested variables and add the new ones (order-preserving dedupe). If False, replace them.

True
ras_object Optional[RasPrj]

The RAS project object. Defaults to None.

None

Raises:

Type Description
ValueError

If the plan file is not found, variables is empty, or the plan has no Sediment Output Level= line (not a sediment plan).

set_shortid staticmethod

Python
set_shortid(plan_number_or_path: Union[str, Number, Path], new_shortid: str, ras_object=None) -> None

Set the Short Identifier in a HEC-RAS plan file.

Parameters:

Name Type Description Default
plan_number_or_path Union[str, Path]

The plan number or path to the plan file.

required
new_shortid str

The new Short Identifier to set (max 24 characters).

required
ras_object Optional[RasPrj]

The RAS project object. If None, uses the global 'ras' object.

None

Raises:

Type Description
ValueError

If the plan file is not found or if new_shortid is too long.

IOError

If there's an error updating the plan file.

Example

RasPlan.set_shortid('01', 'NewShortIdentifier')

set_steady staticmethod

Python
set_steady(plan_number: Union[str, Number], new_steady_flow_number: Union[str, Number], ras_object=None)

Apply a steady flow file to a plan file.

Parameters: plan_number (Union[str, Number]): Plan number (e.g., '02', 2, or 2.0) new_steady_flow_number (Union[str, Number]): Steady flow number to apply (e.g., '01', 1, or 1.0) ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: None

Raises: ValueError: If the specified steady flow number is not found in the project file FileNotFoundError: If the specified plan file is not found

Example:

RasPlan.set_steady('02', '01')

Note

This function updates the ras object's dataframes after modifying the project structure.

set_unsteady staticmethod

Python
set_unsteady(plan_number: Union[str, Number], new_unsteady_flow_number: Union[str, Number], ras_object=None)

Apply an unsteady flow file to a plan file.

Parameters: plan_number (Union[str, Number]): Plan number (e.g., '04', 4, or 4.0) new_unsteady_flow_number (Union[str, Number]): Unsteady flow number to apply (e.g., '01', 1, or 1.0) ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Returns: None

Raises: ValueError: If the specified unsteady number is not found in the project file FileNotFoundError: If the specified plan file is not found

Example:

RasPlan.set_unsteady('04', '01')

Note

This function updates the ras object's dataframes after modifying the project structure.

update_flow_description staticmethod

Python
update_flow_description(flow_number_or_path: Union[str, Number, Path], description: str, ras_object=None) -> bool

Update or insert the description in a steady flow file (.f##).

Parameters:

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

The flow number (e.g., '01') or path to the flow file.

required
description str

Description text to write.

required
ras_object RasPrj

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

None

Returns:

Type Description
bool

True if successful, False otherwise.

Raises:

Type Description
ValueError

If the flow file is not found.

update_geom_description staticmethod

Python
update_geom_description(geom_number_or_path: Union[str, Number, Path], description: str, ras_object=None) -> bool

Update or insert the description in a geometry file (.g##).

Parameters:

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

The geometry number (e.g., '01') or path to the geometry file.

required
description str

Description text to write.

required
ras_object RasPrj

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

None

Returns:

Type Description
bool

True if successful, False otherwise.

Raises:

Type Description
ValueError

If the geometry file is not found.

update_plan_description staticmethod

Python
update_plan_description(plan_number: Union[str, Number], description: str, ras_object=None)

Update or insert plan description in the correct location within a plan file.

The description block will be placed after initial plan parameters (Plan Title, Program Version, Short Identifier, Simulation Date, Geom File, Flow File, and flow type) but before the Computation Interval line.

Parameters:

plan_number : Union[str, Number] Plan number to update (e.g., '01', 1, or 1.0) description : str Description text to insert. Will be automatically wrapped in BEGIN DESCRIPTION/END DESCRIPTION blocks. ras_object : RasPrj, optional RAS project object. If None, uses global 'ras' object.

Returns:

bool : True if successful, False otherwise

Examples:

RasPlan.update_plan_description('02', ... 'Atlas 14 Uncertainty Analysis\n' + ... 'AEP: 100 years\n' + ... 'Duration: 24 hours\n' + ... 'Confidence Level: upper') True

update_plan_intervals staticmethod

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

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

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

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

Notes

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

Example:

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

update_run_flags staticmethod

Python
update_run_flags(plan_number_or_path: Union[str, Path], geometry_preprocessor: bool = None, unsteady_flow_simulation: bool = None, run_sediment: bool = None, post_processor: bool = None, floodplain_mapping: bool = None, ras_object=None) -> None

Update the run flags in a HEC-RAS plan file.

Parameters: plan_number_or_path (Union[str, Path]): The plan number (1 to 99) or full path to the plan file geometry_preprocessor (bool, optional): Set Geometry Preprocessor (Run HTab, -1 = ON, 0 = OFF) unsteady_flow_simulation (bool, optional): Set Unsteady Flow (Run UNet, -1 = ON, 0 = OFF) run_sediment (bool, optional): Set Run Sediment (Run Sediment, -1 = ON, 0 = OFF) post_processor (bool, optional): Set Post Processor (Run PostProcess, -1 = ON, 0 = OFF) floodplain_mapping (bool, optional): Set Floodplain Mapping (Run RASMapper, -1 = ON, 0 = OFF) ras_object (RasPrj, optional): Specific RAS object to use. If None, uses the global ras instance.

Raises: ValueError: If the plan file is not found IOError: If there's an error reading or writing the plan file

Notes: - -1 is ON, 0 is OFF - Lines affected in plan file: Run HTab= -1 # geometry_preprocessor Run UNet= -1 # unsteady_flow_simulation Run Sediment= 0 # run_sediment Run PostProcess= -1 # post_processor Run RASMapper= 0 # floodplain_mapping

Example:

RasPlan.update_run_flags("01", geometry_preprocessor=True, unsteady_flow_simulation=True, run_sediment=False, post_processor=True, floodplain_mapping=False)

update_simulation_date staticmethod

Python
update_simulation_date(plan_number_or_path: Union[str, Number, Path], start_date: datetime, end_date: datetime, ras_object: Optional[RasPrj] = None) -> None

Update the simulation date for a given plan.

Parameters:

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

The plan number (str, int, or float) or path to the plan file.

required
start_date datetime

The start date and time for the simulation.

required
end_date datetime

The end date and time for the simulation.

required
ras_object Optional[RasPrj]

The RAS project object. Defaults to None.

None

Raises:

Type Description
ValueError

If the plan file is not found or if there's an error updating the file.

use_optimal_hdf_settings staticmethod

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

Apply ras-commander's recommended HDF write settings to a plan file.

This is an alias for apply_hdf_output_profile() using the balanced profile by default. target_ras_version is passed through; see apply_hdf_output_profile().

RasFlowOptimization

Static helpers for HEC-RAS native Automated Flow Optimization.

HEC-RAS stores flow hydrograph optimization setup in plan files using Flow Ratio ... keys and reports trial progress in compute messages. This API keeps execution in the standard ras-commander path: configure a copied plan, run it with :class:RasCmdr, then extract the trial summary.

compute_plan_and_get_trials staticmethod

Python
compute_plan_and_get_trials(plan_number: Union[str, Number, Path], ras_object=None, **compute_kwargs) -> Dict[str, Any]

Execute a plan through :class:RasCmdr and return native trials.

This method is a convenience wrapper only; it does not invoke HEC-RAS directly.

copy_plan_with_optimization staticmethod

Python
copy_plan_with_optimization(template_plan: Union[str, Number], mode: str, reference_location: str, target_value: Union[int, float], new_plan_shortid: Optional[str] = None, new_title: Optional[str] = None, ras_object=None, **settings_kwargs) -> str

Clone a plan and enable native flow optimization on the copy.

Parameters:

Name Type Description Default
template_plan Union[str, Number]

Existing plan number to copy.

required
mode str

"stage" or "flow".

required
reference_location str

Existing reference point/line.

required
target_value Union[int, float]

Target stage or flow value.

required
new_plan_shortid Optional[str]

Optional new Short Identifier.

None
new_title Optional[str]

Optional new Plan Title.

None
ras_object RasPrj

Optional RAS project object.

None
**settings_kwargs Any

Additional :meth:set_settings options.

{}

Returns:

Type Description
str

New plan number.

disable_plan staticmethod

Python
disable_plan(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> bool

Remove native Flow Ratio ... settings from a plan file.

Parameters:

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

Plan number or explicit plan path.

required
ras_object RasPrj

Optional RAS project object.

None

Returns:

Type Description
bool

True when the plan file was updated.

enable_plan staticmethod

Python
enable_plan(plan_number_or_path: Union[str, Number, Path], mode: str, reference_location: str, target_value: Union[int, float], **kwargs) -> bool

Enable native Automated Flow Optimization for an existing plan.

This is an alias for :meth:set_settings with intent-focused naming.

get_settings staticmethod

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

Read native flow optimization settings from a HEC-RAS plan file.

Parameters:

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

Plan number ("01") or explicit .p## path.

required
ras_object RasPrj

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

None

Returns:

Type Description
Dict[str, Any]

Dict with normalized keys including enabled, mode,

Dict[str, Any]

reference_location, ratio limits, and selected hydrographs.

get_trial_results staticmethod

Python
get_trial_results(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> pd.DataFrame

Extract native flow optimization trial results after compute.

Reads the trial table HEC-RAS writes to the plan HDF (Results/Unsteady/Flow Optimization Hydro Scaling/Results with the setup in Plan Data/Flow Ratio Optimization; full float32 precision). Without it, parses the Optimization trial # compute messages from the HDF Results/Summary/Compute Messages (text) dataset or a .computeMsgs.txt / .comp_msgs.txt file (values rounded as printed).

Returns:

Type Description
DataFrame

DataFrame with one row per parsed trial. Empty when no native flow

DataFrame

optimization output is available.

list_flow_hydrographs staticmethod

Python
list_flow_hydrographs(plan_number_or_path: Union[str, Number, Path], ras_object=None) -> pd.DataFrame

List flow hydrograph boundary labels available to a plan.

The returned optimization_hydrograph values are suitable for the Flow Ratio Optimization Hydrograph= plan-file lines when HEC-RAS uses 2D boundary condition line labels.

parse_compute_messages staticmethod

Python
parse_compute_messages(messages: str) -> pd.DataFrame

Parse HEC-RAS flow optimization trial lines from compute messages.

Parameters:

Name Type Description Default
messages str

Raw compute message text.

required

Returns:

Type Description
DataFrame

DataFrame with one row per Optimization trial # message.

set_settings staticmethod

Python
set_settings(plan_number_or_path: Union[str, Number, Path], mode: str, reference_location: str, target_value: Union[int, float], tolerance: Union[int, float] = 0.1, initial_ratio: Union[int, float] = 1.0, min_ratio: Union[int, float] = 0.5, max_ratio: Union[int, float] = 4.0, max_iterations: int = 10, hydrographs: Optional[Union[str, Iterable[str]]] = None, user_selected_hydrographs: Optional[bool] = None, restart_approach: Optional[str] = None, transition_period_hours: Optional[Union[int, float]] = None, update_observed_timeseries: bool = True, target_units: Optional[str] = None, ras_object=None) -> bool

Write native flow optimization settings into a plan file.

Parameters:

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

Plan number or explicit plan path.

required
mode str

"stage", "flow", or "none".

required
reference_location str

Existing HEC-RAS reference point/line name. A full value such as "Ref Point: LowPoint" is accepted; if no prefix is supplied, the prefix is inferred from mode.

required
target_value Union[int, float]

Target stage or flow value.

required
tolerance Union[int, float]

Allowed target tolerance.

0.1
initial_ratio Union[int, float]

Flow ratio used by trial 1.

1.0
min_ratio Union[int, float]

Minimum trial flow ratio.

0.5
max_ratio Union[int, float]

Maximum trial flow ratio.

4.0
max_iterations int

Maximum number of trials.

10
hydrographs Optional[Union[str, Iterable[str]]]

Exact optimization hydrograph labels, a single label, or None to auto-discover flow hydrographs where possible. Plain names are written as "BCLine: <name>".

None
user_selected_hydrographs Optional[bool]

Override the native user-selected flag. Defaults to True when hydrograph labels are written.

None
restart_approach Optional[str]

Optional restart approach. Accepted shorthands: "reuse_initial_conditions" or "recompute_each_trial".

None
transition_period_hours Optional[Union[int, float]]

Optional restart transition period.

None
update_observed_timeseries bool

Also write the constant observed stage or flow target in the referenced unsteady flow file.

True
target_units Optional[str]

Units for the observed target series. Defaults to "ft" for stage and "cfs" for flow.

None
ras_object RasPrj

Optional RAS project object.

None

Returns:

Type Description
bool

True when the plan file was written successfully.

RasGeo

RasGeo is a deprecated compatibility namespace. Prefer the geometry APIs, including GeomLandCover for roughness editing.

A class for operations on HEC-RAS geometry files.

DEPRECATED: This class is deprecated and will be removed before v1.0. Please migrate to the new geometry subpackage classes: - GeomPreprocessor for geometry preprocessor operations - GeomLandCover for Manning's n land cover operations

clear_geompre_files staticmethod

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

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

DEPRECATED: Use GeomPreprocessor.clear_geompre_files() instead. This method will be removed before v1.0.

Parameters:

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

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

None
ras_object RasPrj

An optional RAS object instance.

None

Returns:

Type Description
None

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

clone_geom staticmethod

Python
clone_geom(template_geom: Union[str, Number], new_title: Optional[str] = None, description: Optional[str] = None, ras_object=None) -> str

Copy geometry files from a template, find the next geometry number, and update the project file accordingly.

Parameters

template_geom : Union[str, Number] Geometry number to use as template (e.g., '01', 1, or 1.0). new_title : Optional[str], optional If provided, set this as the Geom Title in the new geometry file after cloning. Must be 32 characters or fewer. None keeps the template's original title (default None). description : Optional[str], optional If provided, write this as the geometry description block in the new geometry file after cloning. None keeps the template's original description (default None). ras_object : optional Specific :class:~ras_commander.RasPrj.RasPrj instance to use. If None, uses the global ras instance.

Returns

str New geometry number (e.g., '03').

Raises

ValueError If the template geometry is not found, or if new_title exceeds 32 characters.

Examples

Clone without changes

new_num = RasGeo.clone_geom('01')

Clone with a new title

new_num = RasGeo.clone_geom('01', new_title='Updated Geometry')

Clone with title and description

new_num = RasGeo.clone_geom( ... '01', ... new_title='High Flow Scenario', ... description='Modified breakline spacing for 500-yr event', ... )

Notes

This method updates the ras object's DataFrames after modifying the project structure. The backwards-compatible wrapper :meth:RasPlan.clone_geom delegates here.

get_mannings_baseoverrides staticmethod

Python
get_mannings_baseoverrides(geom_file_path)

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

DEPRECATED: Use GeomLandCover.get_base_mannings_n() instead. This method will be removed before v1.0.

Parameters:

geom_file_path : str or Path Path to the geometry file (.g##)

Returns:

pandas.DataFrame DataFrame with Table Number, Land Cover Name, and Base Mannings n Value

get_mannings_regionoverrides staticmethod

Python
get_mannings_regionoverrides(geom_file_path)

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

DEPRECATED: Use GeomLandCover.get_region_mannings_n() instead. This method will be removed before v1.0.

Parameters:

geom_file_path : str or Path Path to the geometry file (.g##)

Returns:

pandas.DataFrame DataFrame with Table Number, Land Cover Name, MainChannel value, and Region Name

set_mannings_baseoverrides staticmethod

Python
set_mannings_baseoverrides(geom_file_path, mannings_data)

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

DEPRECATED: Use GeomLandCover.set_base_mannings_n() instead. This method will be removed before v1.0.

Parameters:

geom_file_path : str or Path Path to the geometry file (.g##) mannings_data : DataFrame DataFrame with columns 'Table Number', 'Land Cover Name', and 'Base Mannings n Value'

Returns:

bool True if successful

set_mannings_regionoverrides staticmethod

Python
set_mannings_regionoverrides(geom_file_path, mannings_data)

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

DEPRECATED: Use GeomLandCover.set_region_mannings_n() instead. This method will be removed before v1.0.

Parameters:

geom_file_path : str or Path Path to the geometry file (.g##) mannings_data : DataFrame DataFrame with columns 'Table Number', 'Land Cover Name', 'MainChannel', and 'Region Name'

Returns:

bool True if successful

RasUnsteady

RasUnsteady.set_boundary_inline_hydrograph(..., max_decimals=6) retains fractional flow or stage ordinates using the existing eight-character field formatter. The keyword-only setting accepts integers from zero through six; precision is reduced where a value needs more room. Omitting it retains the two-decimal default. Invalid settings fail before changing the unsteady file. Native preprocessing and result readback remain separate validation steps.

RasUnsteady.set_constant_precipitation(path, value=0.01, units="in/hr", ratio=1.0) sets a uniform rate without an inherited rainfall reduction multiplier. The keyword-only ratio is dimensionless and must round to a positive finite native Single. That rounded value is written consistently to the text and existing HDF sidecar. Overflow and underflow to zero fail before either write. Omit ratio to preserve existing ratio records. Rates may use in/hr or mm/hr; native preprocessing and readback remain separate checks.

disable_meteorology(..., remove_source_references=True) prepares an owned boundary-only child without inherited gridded or point meteorological sources. It removes met station/source records and resets the sidecar meteorology groups to disabled. Boundary hydrographs, boundary DSS links, and infiltration are retained. The default preserves inactive sidecar sources. A valid empty unsteady sidecar is initialized with disabled meteorology groups; an owned compiled *.tmp.hdf still requires an existing Event Conditions group.

The operation retains the existing CRLF text serialization and preserves legacy filename bytes. Records split only on CRLF, CR or LF. Unicode separators, form feeds and vertical tabs remain part of filenames and other record content. boundary_conditions_unchanged compares boundary bytes with only CR/LF record separators normalized. boundary_conditions_byte_identical also compares separators. Returned evidence includes flow-text hashes and all removed meteorological source keys, including primary precipitation keys.

Changes are staged and validated before application. Original file objects, ACLs, ownership, permissions and hard links are retained, and an application exception restores original bytes. Use exclusive access. This is exception rollback, not crash atomicity. A crash or failed restoration leaves each original in the sibling .<filename>.meteorology-*/original recovery file; a restoration error reports these paths.

Class for all operations related to HEC-RAS unsteady flow files.

batch_update_dss_references staticmethod

Python
batch_update_dss_references(path_mapping: Union[Dict[str, str], DataFrame], unsteady_filter: Optional[List[str]] = None, dry_run: bool = True, ras_object: Optional[Any] = None) -> pd.DataFrame

Batch update DSS path substrings across multiple unsteady flow files.

Extends update_boundary_dss_paths() to operate across all unsteady flow files in the project. Uses ras.unsteady_df for file discovery.

Parameters

path_mapping : dict or pd.DataFrame If dict: {old_substring: new_substring} pairs for replacement. If DataFrame: must have columns 'old_value' and 'new_value'. unsteady_filter : list of str, optional List of unsteady numbers to process (e.g., ['01', '03']). If None, processes all unsteady files. dry_run : bool, default True If True, reports what would change without modifying files. Set to False to apply changes. ras_object : optional Custom RAS object to use instead of the global one

Returns

pd.DataFrame Report with columns: - unsteady_number: File number - unsteady_file: File path - river: River name - reach: Reach name - station: River station - dss_path_before: Original DSS path - dss_path_after: New DSS path (or same if no match) - line_number: Line number in file - status: 'updated', 'unchanged', or 'error'

Example

from ras_commander import RasUnsteady

Preview what exists

all_dss = RasUnsteady.preview_dss_references()

Define replacements

mapping = {'RUN:1%_24HR': 'RUN:1%_48HR', 'OLD_PROJECT': 'NEW_PROJECT'}

Dry run first

report = RasUnsteady.batch_update_dss_references(mapping, dry_run=True) print(report[report['status'] == 'updated'])

Apply changes

report = RasUnsteady.batch_update_dss_references(mapping, dry_run=False)

Notes

Always run with dry_run=True first to verify changes before applying. The method validates results by re-reading DSS boundaries after updates.

configure_gridded_dss_precipitation staticmethod

Python
configure_gridded_dss_precipitation(unsteady_file: Union[str, Path], dss_filename: Union[str, Path], dss_pathname: str, interpolation: str = '', ras_object: Optional[Any] = None, ratio: Optional[float] = None, historic: bool = False) -> None

Configure a .u## file to reference gridded DSS precipitation.

This helper wires an existing DSS grid file into the HEC-RAS unsteady flow configuration. It does not write DSS data. The required evapotranspiration, air-density, and air-pressure mode records are completed without replacing explicit nonblank choices.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##). dss_filename : str DSS filename for the gridded precipitation source. Relative values are written using RAS-style backslashes (for example, .\Precipitation\precip.dss). Absolute paths inside the unsteady file folder are converted to that relative form; absolute paths elsewhere are preserved. dss_pathname : str DSS pathname for the precipitation grid record. interpolation : str, optional Spatial interpolation method. Use "Nearest" or "Bilinear". The default empty string leaves the RAS default unset in the .u##. ras_object : optional Custom initialized RAS project. Required when unsteady_file is supplied as a two-digit unsteady-flow number. ratio : float, optional Set Met BC=Precipitation|Ratio. HEC-RAS 6.0-6.1 do not apply this multiplier, so those releases require 1.0. When omitted, a retained non-unit text or HDF ratio raises rather than silently scaling the new source; pass 1.0 or a deliberate design value. historic : bool, default False Set true for observed or analysis precipitation. With ratio=None the text and HDF ratios are reset to 1.0. A non-unit ratio is contradictory and raises.

Returns

None The .u## file and its .u##.hdf sidecar metadata are updated in place.

Raises

ValueError A legacy area Precipitation Hydrograph boundary remains. HEC-RAS 6.6 rejected that boundary together with global gridded rainfall in consumer testing; the API conservatively rejects the conflict for all versions before modifying text or HDF. Review the intended forcing and explicitly remove a superseded boundary with stage_project(), inspect_boundary_blocks(), and delete_boundary() before retrying. No boundary is auto-deleted.

delete_boundary staticmethod

Python
delete_boundary(staged_project: StageProjectResult, *, unsteady_number: str, boundary_id: str, expected_source_sha256: str, expected_block_sha256: str, expected_bc_type: str, expected_location_raw: str, dry_run: bool = True) -> BoundaryMutationResult

Preview or remove one exact boundary block from an owned stage.

Selection evidence comes from :meth:inspect_boundary_blocks. Preview is the default and performs no write. Apply uses a verified splice with CRLF serialization and atomic replacement; direct paths, partial selectors, positional selectors, force, and global-project fallback are not accepted.

disable_meteorology staticmethod

Python
disable_meteorology(unsteady_file: Union[str, Path], *, compiled_plan_hdf: Optional[Union[str, Path]] = None, remove_source_references: bool = False, ras_object: Optional[Any] = None) -> Dict[str, Any]

Disable inherited meteorological forcing in an unsteady-flow clone.

HEC-RAS can retain meteorology state in the .u##.hdf sidecar even when the corresponding .u## text contains no active precipitation, wind, or evapotranspiration record. A cloned breakout plan can then fail in-band while reading an enabled HDF variable whose Values dataset is absent. This method makes the disabled state explicit in the text file and unsteady sidecar, retaining inactive sidecar data by default. With remove_source_references=True, it resets the owned sidecar meteorology group and removes text source/station records. For an owned compiled *.tmp.hdf, it removes the meteorology group to match HEC-RAS's canonical no-meteorology execution state.

The optional compiled_plan_hdf is limited to a results-free *.tmp.hdf execution artifact. Supplying it is useful when Phase-1 Windows/Wine preprocessing has already assembled the plan and the caller must align that owned task-local artifact before native Linux execution. Result *.hdf files are rejected.

Text and HDF changes are validated in sibling staging directories before applying any edits. Application uses the original file objects to retain identity, ACLs, ownership, permissions and hard links. A failed application restores original bytes. Use exclusive access; exception rollback does not provide atomicity across a process crash. A crash or failed restoration leaves recovery bytes in the original file under each sibling .<filename>.meteorology-* directory. A valid empty unsteady sidecar is initialized with disabled groups; a compiled target still requires an existing Event Conditions group.

Parameters

unsteady_file : str or Path Unsteady-flow number or owned .u## path. compiled_plan_hdf : str or Path, optional Owned *.tmp.hdf whose /Event Conditions/Meteorology groups should also be disabled. The file must already exist and contain /Event Conditions. remove_source_references : bool, default False Remove meteorological source records and station metadata from the owned text and reset its sidecar meteorology to disabled groups. Boundary hydrographs, their DSS links, and infiltration are retained. Text uses the existing CRLF serialization. Legacy non-UTF-8 bytes are preserved with a reversible UTF-8 surrogateescape policy. Records split only on CRLF, CR or LF; Unicode separators, form feeds and vertical tabs remain part of the record content. ras_object : optional Project object used to resolve an unsteady-flow number.

Returns

dict Mutation evidence including the updated text keys, sidecar groups whose Enabled attribute was set to zero, and any compiled-plan meteorology groups removed. boundary_conditions_unchanged compares boundary bytes with only CR/LF separators normalized; boundary_conditions_byte_identical also compares separators. removed_source_keys includes managed precipitation source keys removed from the original text in both modes.

Raises

ValueError The text is not an unsteady-flow file, contains unexpected NUL bytes, or an HDF target has an invalid event or meteorology structure. OSError Reading, staging or application fails. Applied changes are restored. RuntimeError Boundary content changes, an input changes during staging, or restoration fails. A restoration error identifies retained backups.

ensure_2d_boundary_location staticmethod

Python
ensure_2d_boundary_location(unsteady_file: Union[str, Path], geometry_file: Union[str, Path], *, area_2d: str, bc_line: str, ras_object: Optional[Any] = None) -> Dict[str, Any]

Ensure one geometry-backed 2D Boundary Location= block exists.

This method creates only the empty location block. Follow it with a boundary-type writer such as :meth:set_boundary_inline_hydrograph or :meth:set_normal_depth_boundary. The geometry text file is validated first so an unsteady-flow file cannot reference a missing BC line or attach an existing line to the wrong 2D Flow Area.

Parameters

unsteady_file : str or Path Unsteady-flow file path or number resolvable through ras_object. geometry_file : str or Path Exact plain-text geometry file containing the authored BC line. area_2d : str Exact BC Line Storage Area= value. bc_line : str Exact BC Line Name= value. ras_object : optional Project object used for short-number resolution and DataFrame refresh.

Returns

dict Includes created, the canonical location text, insertion index, geometry validation evidence, and before/after boundary counts.

Raises

FileNotFoundError If the explicit geometry file does not exist. ValueError If names are empty or exceed HEC-RAS fixed-field limits, the geometry does not contain exactly one matching BC line, an existing unsteady location conflicts, or the file header cannot be identified safely.

Notes

The emitted eight-field layout matches HEC-RAS 6.x 2D projects: field 5 contains the 2D Flow Area and field 7 contains the BC line. The operation is idempotent and uses atomic same-volume replacement.

extract_boundary_and_tables staticmethod

Python
extract_boundary_and_tables(unsteady_file: str, ras_object: Optional[Any] = None) -> pd.DataFrame

Extract boundary conditions and their associated tables from an unsteady flow file.

Boundary conditions in HEC-RAS define time-varying inputs like flow hydrographs, stage hydrographs, gate operations, and lateral inflows. This function parses these conditions and their data tables from the unsteady flow file.

Parameters:

Name Type Description Default
unsteady_file str

Path to the unsteady flow file

required
ras_object optional

Custom RAS object to use instead of the global one

None

Returns:

Type Description
DataFrame

DataFrame containing boundary conditions with the following columns: - River Name, Reach Name, River Station: Location information - DSS File: Associated DSS file path if any - Tables: Dictionary containing DataFrames of time-series values

Example

Get the path to unsteady flow file "02"

unsteady_file = RasPlan.get_unsteady_path("02")

Extract boundary conditions and tables

boundaries_df = RasUnsteady.extract_boundary_and_tables(unsteady_file) print(f"Extracted {len(boundaries_df)} boundary conditions from the file.")

extract_tables staticmethod

Python
extract_tables(unsteady_file: str, ras_object: Optional[Any] = None) -> Dict[str, pd.DataFrame]

Extract all tables from an unsteady flow file and return them as DataFrames.

This function combines identify_tables() and parse_fixed_width_table() to extract all tables from an unsteady flow file in a single operation.

Parameters:

Name Type Description Default
unsteady_file str

Path to the unsteady flow file

required
ras_object optional

Custom RAS object to use instead of the global one

None

Returns:

Type Description
Dict[str, DataFrame]

Dictionary where: - Keys are table names (e.g., 'Flow Hydrograph=') - Values are DataFrames with a 'Value' column containing numeric data

Example

Extract all tables from the unsteady flow file

all_tables = RasUnsteady.extract_tables(new_unsteady_file) print(f"Extracted {len(all_tables)} tables from the file.")

Access a specific table

flow_tables = [name for name in all_tables.keys() if 'Flow Hydrograph=' in name] if flow_tables: flow_df = all_tables[flow_tables[0]] print(f"Flow table has {len(flow_df)} values")

get_dss_boundaries staticmethod

Python
get_dss_boundaries(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame

Extract all DSS-linked boundary conditions from an unsteady flow file.

This function parses .u## files and extracts boundary conditions that use DSS files (Use DSS=True), including the full DSS path information needed for updating precipitation scenarios.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) ras_object : optional Custom RAS object to use instead of the global one

Returns

pd.DataFrame DataFrame with columns: - river: River name - reach: Reach name - station: River station - bc_type: Boundary condition type (Flow Hydrograph, Lateral Inflow, etc.) - interval: Time interval (e.g., 5MIN) - dss_file: DSS file path - dss_path: Full DSS path (/A/B/C/D/E/F/; A may be empty) - dss_part_a: DSS Part A (project) - dss_part_b: DSS Part B (location/subbasin) - dss_part_c: DSS Part C (parameter) - dss_part_d: DSS Part D (date) - dss_part_e: DSS Part E (interval) - dss_part_f: DSS Part F (run identifier) - use_dss: HEC-RAS text value, returned as "True" - data_count: Number of inline values declared by the boundary - line_number: Line number of Boundary Location in file - downstream_station: Downstream river station (location field 3) - area_2d: 2D Flow Area name (location field 5) - bc_line_name: 2D boundary-condition line name (location field 7) - sa_2d_name: Deprecated compatibility alias for area_2d - bc_line: Deprecated compatibility alias for bc_line_name - boundary_name: Value from the block's Boundary Name record - boundary_index: Zero-based position among all Boundary Location blocks, including blocks that are not DSS-linked

Example

from ras_commander import RasUnsteady dss_bcs = RasUnsteady.get_dss_boundaries("project.u01") print(f"Found {len(dss_bcs)} DSS-linked boundaries")

Get unique HMS subbasins (Part B)

subbasins = dss_bcs['dss_part_b'].unique() print(f"Unique subbasins: {subbasins}")

Notes

DSS Path Format: /A/B/C/D/E/F/ - An empty Part A with five B-F fields is represented as //B/C/D/E/F/. The legacy //A/B/C/D/E/F/ form remains accepted. - Part A: Project identifier (often empty) - Part B: Location/Subbasin name (key for HMS matching) - Part C: Parameter (FLOW, STAGE, etc.) - Part D: Date reference - Part E: Time interval (5MIN, 1HOUR, etc.) - Part F: Run identifier (e.g., RUN:1%_24HR)

get_gate_openings staticmethod

Python
get_gate_openings(unsteady_number_or_path, boundary_index: int = 0, ras_object=None) -> dict

Read gate opening data from a boundary location block.

Scans the unsteady flow file for Boundary Location= blocks that contain a Gate Name= key, and returns gate metadata plus the time series opening values for the gate at boundary_index (0-based index among all gate-bearing boundaries in the file).

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or direct file path. boundary_index : int, optional 0-based index of the gate boundary to read (default 0). ras_object : optional RasPrj instance for path resolution.

Returns

dict Keys:

Text Only
- ``gate_name`` (str): gate name from ``Gate Name=`` line
- ``dss_path`` (str): DSS pathname (empty string if inline)
- ``use_dss`` (bool): whether DSS link is active
- ``interval`` (str): time interval, e.g. ``"1HOUR"``
- ``use_fixed_start`` (bool): fixed-start-time flag
- ``fixed_start`` (str): fixed start date/time string
- ``count`` (int): number of opening values
- ``values`` (list[float]): opening heights per time step

get_gridded_precipitation_capabilities staticmethod

Python
get_gridded_precipitation_capabilities(version: Optional[object] = None, ras_object: Optional[Any] = None) -> GriddedPrecipitationCapabilities

Return version-specific gridded-precipitation support and limitations.

get_groundwater_interflow staticmethod

Python
get_groundwater_interflow(unsteady_number_or_path, boundary_index: int = 0, ras_object=None) -> dict

Read groundwater interflow data from a boundary location block.

Scans the unsteady flow file for Boundary Location= blocks that contain a Ground Water Interflow= key, and returns the interflow metadata plus time-series elevation values and Darcy parameters for the boundary at boundary_index.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "01") or direct file path. boundary_index : int, optional 0-based index of the GW interflow boundary to read (default 0). ras_object : optional RasPrj instance for path resolution.

Returns

dict Keys:

Text Only
- ``interval`` (str): time interval, e.g. ``"1HOUR"``
- ``count`` (int): number of elevation values
- ``values`` (list[float]): groundwater elevation time series
- ``darcy_k`` (float or None): hydraulic conductivity
- ``darcy_k_per_day`` (float or None): conductivity per day
- ``darcy_distance`` (float or None): Darcy flow distance
- ``dss_path`` (str): DSS pathname (empty string if inline)
- ``use_dss`` (bool): whether DSS link is active

get_initial_conditions staticmethod

Python
get_initial_conditions(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame

Parse initial condition entries from a HEC-RAS unsteady flow file.

Parameters:

Name Type Description Default
unsteady_number_or_path Union[str, Path]

Unsteady flow number or path to a .u## file.

required
ras_object Optional[Any]

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

None

Returns:

Type Description
DataFrame

Initial flow, storage/2D elevation, and RRR elevation entries from the unsteady file.

get_initial_flow_method staticmethod

Python
get_initial_flow_method(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Any]

Determine which Initial Conditions method is active in an unsteady flow file.

HEC-RAS uses implicit state to select the IC method: - Use Restart= -1 or 1 → Restart File mode - Use Restart= 0 with Prior WS Filename= → Prior Water Surface mode - Use Restart= 0 with Initial Flow Loc= lines → Enter Initial Flow Distribution - Use Restart= 0 without IC lines → no IC configured (HEC-RAS uses zero flow)

Parameters

unsteady_file : str or Path Path to unsteady flow file or unsteady number. ras_object : optional RAS project object. If None, uses the global ras object.

Returns

dict Keys: - method (str): 'restart_file', 'prior_ws', 'initial_flow_distribution', or 'none' - use_restart (bool): Parsed Use Restart flag - restart_filename (str or None): Restart filename when method is restart_file - prior_ws_filename (str or None): Plan file when method is prior_ws - prior_ws_profile (str or None): Profile name when method is prior_ws - ic_count (int): Number of Initial Flow Loc / Initial Storage Elev / Initial RRR Elev lines present - raw_use_restart (str or None): Raw value from file

get_initial_storage_elevations staticmethod

Python
get_initial_storage_elevations(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame

Return only the storage/2D-area IC entries from the unsteady file.

Convenience wrapper around get_initial_conditions() that filters to type == 'storage' rows.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number or path to a .u## file. ras_object : RasPrj, optional RAS project object.

Returns

pd.DataFrame Columns: type, area_name, value.

get_inline_hydrograph_boundaries staticmethod

Python
get_inline_hydrograph_boundaries(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame

Extract all inline hydrograph boundary conditions from an unsteady flow file.

This function parses .u## files and extracts boundary conditions that have inline time series data (Use DSS=False with Flow Hydrograph or Lateral Inflow tables). These are the manually-entered hydrographs that need to be matched to HMS subbasins for DSS conversion.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) ras_object : optional Custom RAS object to use instead of the global one

Returns

pd.DataFrame DataFrame with columns: - river: River name - reach: Reach name - station: River station - bc_type: Boundary condition type - interval: Time interval (e.g., 5MIN) - data_count: Number of data points - values: numpy array of hydrograph values - peak_value: Maximum flow value - peak_index: Index of peak (time step) - time_to_peak_hrs: Time to peak in hours - min_value: Minimum flow value - line_number: Line number of Boundary Location in file

Example

from ras_commander import RasUnsteady inline_bcs = RasUnsteady.get_inline_hydrograph_boundaries("project.u01") print(f"Found {len(inline_bcs)} inline hydrograph boundaries") for idx, bc in inline_bcs.iterrows(): ... print(f"{bc['river']}/{bc['reach']}/{bc['station']}: " ... f"Peak={bc['peak_value']:.0f} cfs @ {bc['time_to_peak_hrs']:.1f} hrs")

get_lateral_inflow_hydrograph staticmethod

Python
get_lateral_inflow_hydrograph(unsteady_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None) -> Optional[pd.DataFrame]

Read a Lateral Inflow Hydrograph from a boundary condition.

Parses the Lateral Inflow Hydrograph= <count> header and the fixed-width flow values that follow it. Also reads the optional Flow Hydrograph Slope= and Interval= fields from the same boundary block and attaches them as DataFrame attrs.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01"). river, reach, station : str, optional 1D location selector. When all three are None the first Lateral Inflow Hydrograph boundary in the file is returned. For 2D/SA boundaries the river/reach/station fields are empty; pass None to match the first lateral inflow found. ras_object : optional Custom RAS object to use instead of the global one.

Returns

pd.DataFrame or None DataFrame with columns ['flow'] and integer index representing ordinal time steps, or None if no matching boundary was found.

Text Only
DataFrame ``attrs`` include:

- ``interval`` (str): e.g. ``"1HOUR"``
- ``slope`` (float or None): ``Flow Hydrograph Slope`` value
- ``matched_location`` (str): raw ``Boundary Location=`` value
- ``value_count`` (int): number of flow values
Raises

FileNotFoundError If the unsteady flow file does not exist.

Examples

from ras_commander import RasUnsteady df = RasUnsteady.get_lateral_inflow_hydrograph( ... "BaldEagleDamBrk.u01", ... ) print(f"Values: {len(df)}, peak: {df['flow'].max():.0f}") Values: 141, peak: 100000 print(f"Slope: {df.attrs['slope']}") Slope: 0.005

get_met_precipitation_config staticmethod

Python
get_met_precipitation_config(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Optional[Any]]

Parse meteorologic precipitation configuration from a .u## file.

HEC-RAS persists inactive precipitation settings in Met BC lines. This reader returns the active configuration implied by the top-level Precipitation Mode switch and Met BC=Precipitation|Mode value, plus the raw Met BC key-value pairs and any sidecar HDF attributes when <unsteady_file>.hdf exists.

Parameters:

Name Type Description Default
unsteady_file Union[str, Path]

Path to a .u## file or an unsteady flow number.

required
ras_object Optional[Any]

Optional RAS project object used when resolving a flow number.

None

Returns:

Type Description
Dict[str, Optional[Any]]

Dict with normalized precipitation keys, raw dict of all

Dict[str, Optional[Any]]

Met BC=Precipitation| values, and hdf_attributes from the

Dict[str, Optional[Any]]

sidecar HDF (empty dict if no sidecar exists).

get_meteorological_stations staticmethod

Python
get_meteorological_stations(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame

Parse meteorological station definitions from an unsteady flow file.

Returns

pandas.DataFrame Columns: name, x, y, longitude, latitude, height_m, line_number, unsteady_file.

get_min_storage_elevations staticmethod

Python
get_min_storage_elevations(geom_hdf_path: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, float]

Read minimum elevations for all storage/2D areas from geometry HDF.

Equivalent to the HEC-RAS GUI Import Min SA Elevation(s) button. Uses HdfStorageArea.get_storage_area_names() and HdfStorageArea.get_storage_area_properties() to extract the Min Elev attribute from the preprocessed geometry HDF.

Parameters

geom_hdf_path : str or Path Path to a geometry HDF file (e.g. "model.g01.hdf"). ras_object : RasPrj, optional RAS project object.

Returns

dict[str, float] Mapping of area name to minimum elevation.

get_navigation_dam staticmethod

Python
get_navigation_dam(unsteady_number_or_path, boundary_index: int = 0, ras_object=None) -> dict

Read Navigation Dam BC data from a .u## file.

Returns a dict with keys

params – raw parameter string after 'Navigation Dam=' sft_count – number of SFT points sft_flow – list of flow values (first row) sft_stage_open – list of stage values with gates open (second row) sft_stage_closed – list of stage values with gates closed (third row) flow_monitor_rrr – raw string for Flow Monitor RRR line hinge_point_rrr – raw string for Hinge Point RRR line cp_hinge_point – raw string for CP Hinge Point values cp_min_pool – raw string for CP Min Pool values cp_max_pool – raw string for CP Max Pool values

get_non_newtonian_clastic staticmethod

Python
get_non_newtonian_clastic(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Any]

Read Clastic Grain-Flow and auxiliary Non-Newtonian parameters from a .u## file.

Covers the Clastic method selector, friction angle (Coulomb Phi / legacy Voellmy Phi), Voellmy Xi, hindered settling, representative grain size, and high-concentration transport equation.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Returns

dict clastic_method (int): 0=Coulomb, 1=Voellmy. clastic_method_name (str): Human-readable clastic method name. coulomb_phi (float): Friction angle phi in degrees. voellmy_x (float): Voellmy turbulence parameter Xi. hindered_fv (int): 0=No Hindered Settling, 1=User Specified K. hindered_fv_name (str): Human-readable hindered settling method. fv_k (float): k power parameter for hindered settling. ds (float): Representative grain size in mm (O'Brien only). high_c_transport (int): High-concentration transport equation selector. high_c_transport_name (str): Human-readable transport equation name.

get_non_newtonian_concentration staticmethod

Python
get_non_newtonian_concentration(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Any]

Read Non-Newtonian concentration and bulking parameters from a .u## file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Returns

dict cv (float): Volumetric concentration in percent. bulking_method (int): 0=Do Not Bulk, 1=Bulk Fluid Volume. bulking_method_name (str): Human-readable bulking method name. max_cv (float): Maximum volumetric concentration in percent.

get_non_newtonian_herschel_bulkley staticmethod

Python
get_non_newtonian_herschel_bulkley(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Any]

Read Generalized Herschel-Bulkley parameters from a .u## file.

The HB model is: tau = tau_y + K * (du/dy)^n. When n=1 the model reduces to Bingham plastic.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Returns

dict k (float): Consistency factor K. n (float): Power index n.

get_non_newtonian_method staticmethod

Python
get_non_newtonian_method(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Any]

Read the Non-Newtonian method from an unsteady flow file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "03") or path to a .u## file. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Returns

dict method_id (int): Integer method code (0-4). method_name (str): Human-readable method name.

get_non_newtonian_shear staticmethod

Python
get_non_newtonian_shear(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Any]

Read Non-Newtonian yield stress and viscosity parameters from a .u## file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Returns

dict yield_method (int): 0=Exponential, 1=User Yield. yield_method_name (str): Human-readable yield method name. yield_coef (tuple[float, float]): Exponential yield coefficients (a, b). user_yield (float): User-specified yield stress in Pa. visc_method (int): 0=Use Coulomb, 1=Maron and Pierce, 2=User Defined Viscosity, 3=User Visc Ratio. visc_method_name (str): Human-readable viscosity method name. obrien_b (float): O'Brien exponential viscosity B coefficient. user_viscosity (float): User-defined dynamic viscosity in Pa·s. user_visc_ratio (float): Viscosity ratio multiplier.

get_point_evapotranspiration staticmethod

Python
get_point_evapotranspiration(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> pd.DataFrame

Parse ras-commander-authored point evapotranspiration data from an unsteady file.

Returns

pandas.DataFrame Columns: station_name, hour, value, interval, units, start_time, datetime, mode, point_interpolation, line_number, unsteady_file.

get_prior_ws_filename staticmethod

Python
get_prior_ws_filename(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Optional[str]]

Read Prior WS Filename and Profile from an unsteady flow file.

When HEC-RAS is configured to use a prior steady-state water surface profile as initial conditions, the .u## file contains Prior WS Filename= and Prior WS Profile= lines.

Parameters

unsteady_file : str or Path Path to unsteady flow file or unsteady number. ras_object : optional RAS project object. If None, uses the global ras object.

Returns

dict Keys: - prior_ws_filename (str or None): Plan file reference (e.g. 'ProjectName.p01') - prior_ws_profile (str or None): Profile name within that plan

get_rating_curve staticmethod

Python
get_rating_curve(unsteady_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None) -> Optional[pd.DataFrame]

Read a Rating Curve from a boundary condition in a HEC-RAS unsteady flow file.

Parses the Rating Curve= <pair_count> header and the fixed-width (stage, discharge) pair table that follows it.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01") when a project-bound ras_object is available. river, reach, station : str, optional 1D location selector. When all three are None the first Rating Curve boundary in the file is returned. ras_object : optional Custom RAS object to use instead of the global one.

Returns

pd.DataFrame or None DataFrame with columns ['stage', 'discharge'] containing the rating curve pairs, or None if no Rating Curve boundary was found matching the selectors.

Raises

FileNotFoundError If the unsteady flow file does not exist.

Examples

from ras_commander import RasUnsteady rc = RasUnsteady.get_rating_curve( ... "Manning'snCalibra.u01", ... river="Mississippi", reach="Lower Miss.", station="846", ... ) rc.head() stage discharge 0 211.0 0.0 1 225.8 80000.0

get_restart_settings staticmethod

Python
get_restart_settings(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> Dict[str, Optional[Any]]

Parse restart-file usage settings from an unsteady flow file.

HEC-RAS stores restart-file usage in the unsteady-flow file using Use Restart and Restart Filename. This is separate from plan restart output settings, which are stored as Write IC File keys.

Parameters:

Name Type Description Default
unsteady_file Union[str, Path]

Path to an unsteady flow file or an unsteady number.

required
ras_object Optional[Any]

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

None

Returns:

Type Description
Dict[str, Optional[Any]]

Parsed usage settings and raw values.

get_rules_bc staticmethod

Python
get_rules_bc(unsteady_number_or_path, boundary_index: int = 0, ras_object=None) -> dict

Read Rule Operations BC as raw text from a .u## file.

The Rules BC format is a complex scripting language; this method returns the raw lines for inspection or round-trip writing.

Returns a dict with keys

rule_lines – list of raw 'Rule Operation=...' and 'Rule Expression=...' lines (with newlines) gate_data – list of raw 'Rule Gate Data=...' lines description – text between BEGIN/END BOUNDARY DESCRIPTION if present

get_stage_flow_hydrograph staticmethod

Python
get_stage_flow_hydrograph(unsteady_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None) -> Optional[pd.DataFrame]

Read observed stage/flow pairs from an internal boundary condition.

Parses the Observed Stage and Flow Hydrograph= block from a .u## file. The block stores interleaved (stage, flow) pairs in 8-character fixed-width fields, 10 values per line (5 pairs per line).

Parameters

unsteady_file : str or Path Path to unsteady flow file or unsteady number (e.g. "01"). river : str, optional River name for location matching. reach : str, optional Reach name for location matching. station : str, optional River station for location matching. ras_object : optional RasPrj instance; falls back to the global ras object.

Returns

pd.DataFrame or None DataFrame with columns ['stage', 'flow'], one row per time step. Returns None if the boundary or data block is not found.

See Also

set_stage_flow_hydrograph : Write stage/flow pairs back to a .u## file.

get_uniform_lateral_inflow_hydrograph staticmethod

Python
get_uniform_lateral_inflow_hydrograph(unsteady_file: Union[str, Path], river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None) -> Optional[pd.DataFrame]

Read a Uniform Lateral Inflow Hydrograph from a boundary condition.

Parses the Uniform Lateral Inflow Hydrograph= <count> header and the fixed-width flow values that follow it. Also reads the optional Flow Hydrograph Slope= and Interval= fields from the same boundary block and attaches them as DataFrame attrs.

Uniform lateral inflow is a reach-based BC type: the inflow is applied uniformly across a reach segment (between two river stations), unlike a point Lateral Inflow Hydrograph.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01"). river, reach, station : str, optional 1D location selector. When all three are None the first Uniform Lateral Inflow Hydrograph boundary in the file is returned. ras_object : optional Custom RAS object to use instead of the global one.

Returns

pd.DataFrame or None DataFrame with columns ['flow'] and integer index representing ordinal time steps, or None if no matching boundary was found or count is 0 (DSS-linked).

Text Only
DataFrame ``attrs`` include:

- ``interval`` (str): e.g. ``"1HOUR"``
- ``slope`` (float or None): ``Flow Hydrograph Slope`` value
- ``matched_location`` (str): raw ``Boundary Location=`` value
- ``value_count`` (int): number of flow values
Raises

FileNotFoundError If the unsteady flow file does not exist.

get_unique_dss_subbasins staticmethod

Python
get_unique_dss_subbasins(unsteady_file: Union[str, Path], ras_object: Optional[Any] = None) -> List[str]

Get list of unique HMS subbasin names from DSS paths in unsteady file.

This convenience function extracts the DSS Part B (location/subbasin) from all DSS-linked boundaries and returns the unique values. This is useful for identifying which HMS subbasins are used by the RAS model.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) ras_object : optional Custom RAS object to use instead of the global one

Returns

List[str] Sorted list of unique subbasin names from DSS Part B

Example

from ras_commander import RasUnsteady subbasins = RasUnsteady.get_unique_dss_subbasins("project.u01") print(f"Model uses {len(subbasins)} HMS subbasins:") for sb in subbasins[:10]: ... print(f" - {sb}")

identify_tables staticmethod

Python
identify_tables(lines: List[str]) -> List[Tuple[str, int, int]]

Identify the start and end line numbers of tables in an unsteady flow file.

HEC-RAS unsteady flow files contain numeric tables in a fixed-width format. This function locates these tables within the file and provides their positions.

Parameters:

Name Type Description Default
lines List[str]

List of file lines (typically from file.readlines())

required

Returns:

Type Description
List[Tuple[str, int, int]]

List of tuples where each tuple contains: - table_name (str): The type of table (e.g., 'Flow Hydrograph=') - start_line (int): Line number where the table data begins - end_line (int): Line number where the table data ends

Example

Read the unsteady flow file

with open(new_unsteady_file, 'r', encoding='utf-8', errors='replace') as f: lines = f.readlines()

Identify tables in the file

tables = RasUnsteady.identify_tables(lines) print(f"Identified {len(tables)} tables in the unsteady flow file.")

inspect_boundary_blocks staticmethod

Python
inspect_boundary_blocks(staged_project: StageProjectResult, *, unsteady_number: str) -> pd.DataFrame

Inventory exact boundary block identities in an owned staged project.

The returned identities bind the staged file content and physical file identity. They are invalid after any change to the staged population.

parse_fixed_width_table staticmethod

Python
parse_fixed_width_table(lines: List[str], start: int, end: int) -> pd.DataFrame

Parse a fixed-width table from an unsteady flow file into a pandas DataFrame.

HEC-RAS uses a fixed-width format (8 characters per value) for numeric tables. This function converts this format into a DataFrame for easier manipulation.

Parameters:

Name Type Description Default
lines List[str]

List of file lines (from file.readlines())

required
start int

Starting line number for table data

required
end int

Ending line number for table data

required

Returns:

Type Description
DataFrame

DataFrame with a single column 'Value' containing the parsed numeric values

Example

Identify tables in the file

tables = RasUnsteady.identify_tables(lines)

Parse a specific table (e.g., first flow hydrograph)

table_name, start_line, end_line = tables[0] table_df = RasUnsteady.parse_fixed_width_table(lines, start_line, end_line)

preview_dss_references staticmethod

Python
preview_dss_references(ras_object: Optional[Any] = None) -> pd.DataFrame

Consolidated DataFrame of all DSS paths across all unsteady files in project.

Scans every unsteady flow file registered in ras.unsteady_df and extracts all DSS-linked boundary conditions into a single DataFrame.

Parameters

ras_object : optional Custom RAS object to use instead of the global one

Returns

pd.DataFrame DataFrame with all columns from get_dss_boundaries() plus: - unsteady_number: The unsteady file number (e.g., '01') - unsteady_file: Full path to the unsteady file

Example

from ras_commander import RasUnsteady all_dss = RasUnsteady.preview_dss_references() print(f"Total DSS references: {len(all_dss)}") print(all_dss[['unsteady_number', 'dss_part_b', 'dss_path']].head())

print_boundaries_and_tables staticmethod

Python
print_boundaries_and_tables(boundaries_df: DataFrame) -> None

Print boundary conditions and their associated tables in a formatted, readable way.

This function is useful for quickly visualizing the complex nested structure of boundary conditions extracted by extract_boundary_and_tables().

Parameters:

Name Type Description Default
boundaries_df DataFrame

DataFrame containing boundary information and nested tables data from extract_boundary_and_tables()

required

Returns:

Type Description
None

Output is printed to console

Example

Extract boundary conditions and tables

boundaries_df = RasUnsteady.extract_boundary_and_tables(unsteady_file)

Print in a formatted way

print("Detailed boundary conditions and tables:") RasUnsteady.print_boundaries_and_tables(boundaries_df)

read_unsteady_description staticmethod

Python
read_unsteady_description(unsteady_number_or_path: Union[str, Path], ras_object: Optional[Any] = None) -> str

Read the description from an unsteady flow file (.u##).

Parameters:

Name Type Description Default
unsteady_number_or_path Union[str, Path]

The unsteady number (e.g., '01') or path to the unsteady flow file.

required
ras_object optional

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

None

Returns:

Type Description
str

The description text, or empty string if not found.

Raises:

Type Description
ValueError

If the unsteady flow file is not found.

replace_2d_boundary_locations staticmethod

Python
replace_2d_boundary_locations(unsteady_file: Union[str, Path], geometry_file: Union[str, Path], locations: List[Dict[str, str]], *, preserve_area_precipitation: bool = False, ras_object: Optional[Any] = None) -> Dict[str, Any]

Replace every 2D boundary block with validated empty locations.

By default, existing 2D Flow Area boundary blocks—including area-wide blocks with no BC-line name—are removed with their complete type/data payloads. Opt in to preserve_area_precipitation to retain the existing area-wide rainfall forcing for the requested areas. River/reach and storage-area/structure boundary blocks are preserved. Every replacement must identify exactly one BC line in the supplied plain-text geometry. This is intentionally a reset operation: callers assign new Flow Hydrograph, Normal Depth, or other types afterward.

Parameters

unsteady_file : str or Path Unsteady-flow file path or number resolvable through ras_object. geometry_file : str or Path Exact plain-text geometry file containing all replacement lines. locations : list of dict Non-empty list with exact area_2d and bc_line strings. BC-line names must be unique. preserve_area_precipitation : bool, default False Preserve area-wide Precipitation Hydrograph blocks verbatim for areas named in locations. In this opt-in mode, reject unknown or other area-wide boundary types and precipitation on other areas before writing. Perimeter boundary blocks are still replaced. ras_object : optional Project object used for short-number resolution and DataFrame refresh.

Returns

dict Removed 2D locations, inserted locations, preserved non-2D block count, preserved precipitation locations, insertion index, and DataFrame-refresh evidence.

Raises

TypeError If preserve_area_precipitation is not a bool. ValueError If locations is empty or malformed, a BC line is missing from the geometry, or, with preserve_area_precipitation, an area-wide boundary that cannot be preserved is present.

Python
set_boundary_dss_link(unsteady_file: Union[str, Path], river: Optional[str], reach: Optional[str], station: Optional[str], dss_file: str, dss_path: str, interval: str = '5MIN', ras_object: Optional[Any] = None, *, sa_2d_name: Optional[str] = None, bc_line: Optional[str] = None, boundary_index: Optional[int] = None, expected_bc_type: Optional[str] = None) -> bool

Convert an inline hydrograph boundary to use DSS linkage.

This function modifies a boundary condition in a .u## file to use a DSS file reference instead of inline table data. It performs a complete state transition: sets Use DSS=True, adds DSS File/Path, sets the inline table count to 0, and removes any inline data lines.

unsteady_file : str or Path Path to the unsteady flow file (.u##) river : str or None River name for a 1D boundary; pass None for 2D selection. reach : str or None Reach name for a 1D boundary; pass None for 2D selection. station : str or None River station for a 1D boundary; pass None for 2D selection. dss_file : str Path to the DSS file (relative to project folder) dss_path : str Full DSS path (e.g., "//SUBBASIN/FLOW/DATE/5MIN/RUN:1%_24HR/") interval : str, default "5MIN" Time interval for the boundary condition ras_object : optional Custom RAS object to use instead of the global one sa_2d_name, bc_line : str, optional Exact 2D selector fields. sa_2d_name matches field index 5 and bc_line matches field index 7 of Boundary Location=. Partial selectors are allowed but must resolve to one block unless boundary_index disambiguates them. boundary_index : int, optional Zero-based index among Boundary Location= blocks. It may be used alone or as a cross-check for the semantic selectors. expected_bc_type : str, optional Require the selected block to have this boundary-condition type before changing the file.

bool True if boundary was successfully updated, False if not found

ValueError If selector groups are mixed or absent, a selector is ambiguous, boundary_index is invalid or inconsistent, the expected type does not match, or the input has mixed newline conventions.

from ras_commander import RasUnsteady

success = RasUnsteady.set_boundary_dss_link( ... "project.u01", ... river="Turkey Creek", ... reach="A119-00-00", ... station="23601.19", ... dss_file="P1000000.dss", ... dss_path="//A119-01-00A/FLOW/31MAY2007/5MIN/RUN:1%_24HR/" ... )

set_boundary_inline_hydrograph staticmethod

Python
set_boundary_inline_hydrograph(unsteady_file: Union[str, Path], hydrograph_df: DataFrame, bc_type: str = 'Flow Hydrograph', river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None, area_2d: Optional[str] = None, bc_line: Optional[str] = None, *, max_decimals: int = 2) -> bool

Write an inline hydrograph table to a boundary condition, converting from DSS if needed.

This method performs a complete DSS→inline state transition: sets Use DSS=False, removes DSS File/Path lines, writes inline hydrograph data in HEC-RAS fixed-width format, and updates the table count and Interval line.

Like set_precipitation_hyetograph(), this writes fixed-width values, but flow/stage ordinates and interval precipitation have different time semantics.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) or unsteady number (e.g., "01") hydrograph_df : pd.DataFrame DataFrame with columns:

Text Only
- ``'hour'``: Time in hours from start (float)
- ``'value'``: Hydrograph value at each time step (flow in cfs/cms or stage in ft/m)
str, default "Flow Hydrograph"

Boundary condition type. Must be one of:

  • "Flow Hydrograph"
  • "Stage Hydrograph"
  • "Lateral Inflow Hydrograph"
  • "Uniform Lateral Inflow"
str, optional

River name to locate the boundary. If None, updates the first matching bc_type.

reach : str, optional Reach name to locate the boundary. station : str, optional River station to locate the boundary. ras_object : optional Custom RAS object to use instead of the global one area_2d : str, optional Exact 2D Flow Area name (field 5 of Boundary Location=). Supply together with bc_line instead of the 1D selector. bc_line : str, optional Exact 2D BC line name (field 7 of Boundary Location=). Supply together with area_2d. max_decimals : int, default 2 Maximum decimal places for ordinates, from 0 through 6. The existing fixed-width formatter reduces precision as needed to fit each 8-character field; the default preserves existing output. Six is the most fractional places that fit with a leading zero.

Returns

bool True if boundary was successfully updated, False if not found

Raises

ValueError If DataFrame is missing required columns, bc_type is unsupported, or max_decimals is not an integer from 0 through 6. FileNotFoundError If unsteady flow file not found

Example

import pandas as pd from ras_commander import RasUnsteady

Create a simple flow hydrograph

hours = list(range(25)) flows = [100, 150, 300, 600, 1200, 2000, 3000, 4000, 5000, 4500, ... 4000, 3500, 3000, 2500, 2000, 1700, 1400, 1200, 1000, ... 800, 600, 400, 300, 200, 100] df = pd.DataFrame({'hour': hours, 'value': flows}) RasUnsteady.set_boundary_inline_hydrograph( ... "project.u01", df, bc_type="Flow Hydrograph", ... river="White", reach="Muncie", station="15696.24" ... )

Notes

Inline Hydrograph Format (HEC-RAS .u## files):

Flow/Stage/Lateral hydrographs store values only (not time-value pairs). Each value is 8 characters wide, 10 values per line. The count on the header line is the number of values, and time is implied from the Interval setting.

Precipitation also stores values only, but each depth applies to the preceding interval. Its dedicated writer preserves a zero-depth start ordinate; do not apply that interval-depth convention to flow/stage ordinates.

State Transition:

When converting from DSS mode, this method:

  1. Sets Use DSS=False
  2. Removes DSS File= and DSS Path= content (sets to empty)
  3. Writes inline data after the hydrograph header line
  4. Updates the value count and Interval line
See Also

ensure_2d_boundary_location : Create a geometry-validated empty 2D boundary block before assigning its first boundary type. set_boundary_dss_link : Convert inline boundary to DSS mode set_precipitation_hyetograph : Write an incremental-depth precipitation hyetograph

set_constant_precipitation staticmethod

Python
set_constant_precipitation(unsteady_file: Union[str, Path], value: float = 1.0, units: str = 'in/hr', ras_object: Optional[Any] = None, *, ratio: Optional[float] = None) -> None

Configure constant (spatially and temporally uniform) precipitation.

.. note:: Constant precipitation is a testing and 2D model-commissioning convenience, not an engineering-deliverable forcing. Real event modeling uses a time-varying hyetograph (:meth:set_precipitation_hyetograph) or a gridded record (:meth:set_gridded_precipitation / :meth:configure_gridded_dss_precipitation). A uniform rate is useful for rain-on-grid mesh shakedown, where depth = rate * duration makes the 2D solver mass balance trivially hand-checkable, for numerical / stability sensitivity runs, and for cheap CI smoke-test fixtures.

Writes the Precipitation Mode switch and the constant-mode Met BC=Precipitation|... keys, and updates the <unsteady_file>.hdf sidecar attributes when it exists.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) or unsteady number (e.g. "01"). value : float, default 1.0 Constant precipitation rate (must be finite and >= 0). units : {"in/hr", "mm/hr"}, default "in/hr" Constant precipitation rate units. ras_object : optional Custom RAS object used to resolve an unsteady number. ratio : float, optional Positive finite dimensionless multiplier written to both text and the existing HDF sidecar. Pass 1.0 to replace an inherited rainfall reduction factor and retain the supplied rate unscaled. Omission preserves existing ratio records for backward compatibility. Explicit values are rounded once to native Single precision; overflow and underflow to zero are rejected before either file is modified.

Returns

None Modifies the .u## file in-place and updates the .u##.hdf sidecar when present.

Raises

ValueError If value is not a finite, non-negative real number, or units is not "in/hr" or "mm/hr", or an explicit ratio does not round to a positive finite native Single.

Examples

Commission a 2D rain-on-grid mesh with 1 in/hr uniform rain

RasUnsteady.set_constant_precipitation("01", value=1.0, units="in/hr")

See Also

set_precipitation_hyetograph : Time-varying hyetograph (real events). set_gridded_precipitation : Gridded NetCDF precipitation (real events). configure_gridded_dss_precipitation : Gridded DSS precipitation.

set_flow_hydrograph_qmin staticmethod

Python
set_flow_hydrograph_qmin(unsteady_file: Union[str, Path], qmin: float, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, area_2d: Optional[str] = None, bc_line: Optional[str] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Add or update the Flow Hydrograph QMin= (minimum flow) line on a Flow Hydrograph boundary in a HEC-RAS unsteady flow file (.u##).

The minimum flow value prevents HEC-RAS from applying flows below this threshold during the simulation. It is a property of the Flow Hydrograph BC.

Behavior
  • Update path: if a Flow Hydrograph QMin= line already exists inside the matched boundary block, its value is overwritten in place.
  • Insert path: if no QMin line exists, a new line is inserted after Flow Hydrograph QMult= if present, otherwise after Stage Hydrograph TW Check=, otherwise before the first DSS metadata line, otherwise just before the first = line that follows the inline hydrograph data.
Target resolution

Provide exactly one of:

  • (river, reach, station) for a 1D river boundary.
  • (area_2d, bc_line) for a 2D BC line on a 2D Flow Area perimeter.
Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01") when a project-bound ras_object is available. qmin : float Minimum flow value (cfs or cms). Must be non-negative and finite. river, reach, station : str, optional 1D location selector. All three must be provided together. area_2d, bc_line : str, optional 2D location selector. Both must be provided together. ras_object : optional Custom RAS object. boundaries_df is refreshed after the write.

Returns

Dict[str, Any] Reviewable before/after metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): matched ``Boundary Location=`` value
- ``bc_type`` (str): always ``'Flow Hydrograph'``
- ``previous_qmin`` (float | None): prior QMin value, or ``None``
- ``new_qmin`` (float): QMin written
- ``updated_in_place`` (bool): True when existing line overwritten
- ``lines_inserted`` (int): 1 if new line inserted, else 0
- ``insert_anchor`` (str | None): keyword anchor for placement
- ``boundaries_df_refreshed`` (bool)
- ``block_before`` (str): boundary block text before edit
- ``block_after`` (str): boundary block text after edit
Raises

ValueError If qmin is non-numeric, non-finite, or negative; if target selectors are inconsistent; if matched block is not a Flow Hydrograph; or if no boundary matches the selectors. FileNotFoundError If the unsteady flow file does not exist.

Examples

Set a minimum flow on a 1D boundary:

from ras_commander import RasUnsteady result = RasUnsteady.set_flow_hydrograph_qmin( ... "project.u01", ... qmin=50.0, ... river="White", ... reach="Muncie", ... station="15696.24", ... ) result["new_qmin"] 50.0

See Also

set_flow_hydrograph_slope : Set energy-grade slope on Flow Hydrograph. update_flow_multiplier_by_station : Set QMult multiplier.

set_flow_hydrograph_slope staticmethod

Python
set_flow_hydrograph_slope(unsteady_file: Union[str, Path], eg_slope: float, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, area_2d: Optional[str] = None, bc_line: Optional[str] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Add or update the energy-grade Flow Hydrograph Slope= line on a Flow Hydrograph boundary in a HEC-RAS unsteady flow file (.u##).

Flow Hydrograph Slope= is the energy-grade slope HEC-RAS uses to distribute Flow Hydrograph inflow along a 2D Flow Area perimeter BC line (Tutorial 2, "Creating a Simple 2D Model"). It is a property of the Flow Hydrograph BC, not a generic boundary parameter; this writer therefore only operates on blocks that already declare a Flow Hydrograph=<count> keyword.

Behavior
  • Update path: if a Flow Hydrograph Slope= line already exists inside the matched boundary block, its value is overwritten in place and no other line is touched.
  • Insert path: if no slope line exists, a new line is inserted in the canonical position observed in HEC-RAS-emitted output: after Flow Hydrograph QMult= if present, otherwise after Stage Hydrograph TW Check= if present, otherwise immediately before the first DSS metadata line (DSS Path=, DSS File=, or Use DSS=), otherwise just before the first = line that follows the inline hydrograph data.

DSS path/file, Use DSS, Interval, Flow Hydrograph= count, and inline hydrograph data are never altered. The companion writers (set_boundary_dss_link, set_boundary_inline_hydrograph) can be used freely before or after this call.

Format conventions observed in real HEC-RAS .u## files

HEC-RAS emits the line as Flow Hydrograph Slope= <value> — note the single leading space after = and the single trailing space before the newline, matching the surrounding Flow Hydrograph QMult= line. This writer mirrors that spacing on both update and insert.

Target resolution

Provide exactly one of:

  • (river, reach, station) for a 1D river boundary.
  • (area_2d, bc_line) for a 2D BC line on a 2D Flow Area perimeter. bc_line is required: a Flow Hydrograph distribution slope is tied to a specific BC line, never area-wide.
Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01") when a project-bound ras_object is available. eg_slope : float Energy-grade slope (m/m or ft/ft). Must be in the inclusive range [1e-7, 1.0] and finite. river, reach, station : str, optional 1D location selector. All three must be provided together. area_2d, bc_line : str, optional 2D location selector. Both must be provided together. ras_object : optional Custom RAS object to use instead of the global one. When initialized for a project, boundaries_df is refreshed after the write.

Returns

Dict[str, Any] Reviewable before/after metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): the matched ``Boundary Location=``
  value (without the leading ``Boundary Location=``)
- ``bc_type`` (str): always ``'Flow Hydrograph'`` on success
- ``previous_eg_slope`` (float | None): prior slope value, or
  ``None`` if no ``Flow Hydrograph Slope=`` line existed
- ``new_eg_slope`` (float): slope written
- ``updated_in_place`` (bool): True when an existing slope line
  was overwritten without insertion
- ``lines_inserted`` (int): 1 if a new line was inserted, else 0
- ``insert_anchor`` (str | None): the keyword anchor used to
  place the new line (``'Flow Hydrograph QMult='``,
  ``'Stage Hydrograph TW Check='``, ``'DSS Path='``,
  ``'DSS File='``, ``'Use DSS='``, or ``'<inline-data-tail>'``);
  ``None`` on update path
- ``boundaries_df_refreshed`` (bool): True when ``ras_object``
  ``boundaries_df`` was refreshed after the write
- ``block_before`` (str): boundary block text before the edit
- ``block_after`` (str): boundary block text after the edit
Raises

ValueError If eg_slope is non-numeric, non-finite, or outside [1e-7, 1.0]; if the target selectors are inconsistent (both 1D and 2D, or neither); if a 1D selector is partial; if a 2D selector is missing bc_line; if the matched block is not a Flow Hydrograph (e.g., Normal Depth, Stage Hydrograph, Rating Curve, Gate Opening); or if no boundary in the file matches the selectors. FileNotFoundError If the unsteady flow file does not exist.

Examples

Update an existing 2D Flow Hydrograph distribution slope:

from ras_commander import RasUnsteady result = RasUnsteady.set_flow_hydrograph_slope( ... "BaldEagleDamBrk.u02", ... eg_slope=0.001, ... area_2d="BaldEagleCr", ... bc_line="Upstream Inflow", ... ) result["new_eg_slope"], result["updated_in_place"] (0.001, True)

Add a slope line to a Flow Hydrograph block that has none yet:

result = RasUnsteady.set_flow_hydrograph_slope( ... "project.u01", ... eg_slope=0.0007, ... area_2d="Upper 2D Area", ... bc_line="Upstream Q", ... ) result["lines_inserted"], result["insert_anchor"] (1, 'DSS Path=')

See Also

set_boundary_dss_link : Convert inline BC to DSS-linked. set_boundary_inline_hydrograph : Write inline hydrograph table.

set_gate_openings staticmethod

Python
set_gate_openings(unsteady_number_or_path, values: list, boundary_index: int = 0, gate_name: Optional[str] = None, interval: Optional[str] = None, ras_object=None) -> None

Write gate opening time series to a boundary location block.

Replaces the Gate Openings= count and all subsequent data lines for the gate at boundary_index. Optionally updates gate name and time interval.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or direct file path. values : list of float Opening heights per time step. boundary_index : int, optional 0-based index of the gate boundary to write (default 0). gate_name : str, optional New gate name. If None, the existing name is kept. interval : str, optional New time interval (e.g. "15MIN"). If None, kept. ras_object : optional RasPrj instance for path resolution.

set_gridded_precipitation staticmethod

Python
set_gridded_precipitation(unsteady_file: Union[str, Path], netcdf_path: Union[str, Path], interpolation: str = 'Bilinear', ras_object: Optional[Any] = None, dataset_name: Optional[str] = None, units: str = 'mm', value_type: str = 'rate', first_timestep_hours: Optional[float] = None, ratio: Optional[float] = None, historic: bool = False) -> None

Configure NetCDF gridded precipitation and update its native HDF.

The required evapotranspiration, air-density, and air-pressure mode records are completed without replacing explicit nonblank choices.

Parameters

unsteady_file : str or Path Unsteady-flow number or path. netcdf_path : str or Path Project-relative or absolute precipitation NetCDF path. interpolation : {"Bilinear", "Nearest"}, default "Bilinear" Spatial interpolation used by HEC-RAS. ras_object : optional Initialized project object; defaults to the global project. dataset_name : str, optional Precipitation variable. A common name is detected when omitted. units : str, default "mm" Source depth units, normally "mm" or "in". value_type : {"rate", "amount", "cumulative"}, default "rate" Temporal meaning of the input values. first_timestep_hours : float, optional Duration represented by a nonzero first rate/amount frame. ratio : float, optional Positive HEC-RAS precipitation multiplier. Non-unit values for design storms are allowed only when explicit. Omitting it rejects a retained non-unit text or HDF value. historic : bool, default False Set true for observed or analysis precipitation (MRMS, AORC, Stage IV, gauge-adjusted grids, or QPF analysis). With ratio=None this writes 1.0 to both the unsteady file and its HDF sidecar; a non-unit ratio raises.

Returns

None The established API intentionally retains its historical return contract. Use :meth:set_gridded_precipitation_geotiff or :meth:set_gridded_precipitation_grib when a structured ingestion result is required for those source formats.

Raises

ValueError A legacy area Precipitation Hydrograph boundary remains. HEC-RAS 6.6 rejected that boundary together with global gridded rainfall in consumer testing; the API conservatively rejects the conflict for all versions before modifying text or HDF. Review the intended forcing and explicitly remove a superseded boundary with stage_project(), inspect_boundary_blocks(), and delete_boundary() before retrying. No boundary is auto-deleted.

set_gridded_precipitation_geotiff staticmethod

Python
set_gridded_precipitation_geotiff(unsteady_file: Union[str, Path], geotiff_paths: Union[str, Path, Sequence[Union[str, Path]]], *, timestamps: Sequence[Any], units: str, value_type: str, first_timestep_hours: Optional[float] = None, bands: Optional[Union[Sequence[int], Sequence[Sequence[int]]]] = None, source_timezone: Optional[str] = None, model_timezone: Optional[str] = None, interpolation: str = 'Bilinear', ratio: Optional[float] = None, historic: bool = False, nodata_policy: str = 'error', cache_path: Optional[Union[str, Path]] = None, cache_policy: str = 'reuse', ras_object: Optional[Any] = None) -> GriddedPrecipitationImportResult

Configure gridded precipitation directly from GeoTIFF input.

GeoTIFF is a ras-commander ingestion format, not a native HEC-RAS precipitation source. The input is validated and normalized into a content-addressed project-local NetCDF, then that durable NetCDF and the equivalent native HDF payload are configured together. Later HEC-RAS saves and preprocessing therefore retain a vendor-supported GDAL source. The required evapotranspiration, air-density, and air-pressure mode records are completed without replacing explicit nonblank choices.

A single GeoTIFF may contain one or more selected bands. A sequence uses one band per file by default; pass one common band list or one band list per file for multiband sequences. Timestamps and units are always explicit; filenames and non-standard TIFF tags are never used to guess time. Amount and rate timestamps are interval-ending; the selected first-timestep duration places the start of the first interval.

Parameters

unsteady_file : str or Path Unsteady-flow number or path. geotiff_paths : path or sequence of paths One multiband GeoTIFF, or a sequence of single-band GeoTIFFs. timestamps : sequence One explicit timestamp per selected band, strictly increasing. units : str Source depth units, normally "mm" or "in". value_type : {"rate", "amount", "cumulative"} Temporal meaning of each input band. first_timestep_hours : float, optional Required for a nonzero first rate/amount frame so it is not dropped. bands : sequence of int or sequence of sequences, optional Selected bands applied to every file, or one selection per file. source_timezone, model_timezone : str, optional Explicit timezone localization/conversion before writing the timezone-naive timestamps HEC-RAS uses. interpolation : {"Nearest", "Bilinear"} HEC-RAS spatial interpolation method. ratio : float, optional HEC-RAS precipitation multiplier. Non-unit values for observed precipitation are rejected when historic=True. Omitting this value rejects a retained non-unit text or HDF ratio. historic : bool, default False Reset the text and HDF ratio to 1.0 for observed or analysis precipitation. nodata_policy : {"error", "zero"}, default "error" Fail on NoData by default; "zero" explicitly treats it as dry. cache_path : str or Path, optional Persistent NetCDF destination. The default is a semantic-hash path below Precipitation/_ras_commander_cache in the project. cache_policy : {"reuse", "refresh", "error"}, default "reuse" Existing-cache behavior. ras_object : optional Custom initialized RAS project.

Returns

GriddedPrecipitationImportResult Source hashes, persistent cache identity, HDF import result, grid, timestamps, units, and NoData audit information.

set_gridded_precipitation_grib staticmethod

Python
set_gridded_precipitation_grib(unsteady_file: Union[str, Path], grib_paths: Union[str, Path, Sequence[Union[str, Path]]], *, timestamps: Sequence[Any], units: str, value_type: str, first_timestep_hours: Optional[float] = None, bands: Optional[Union[Sequence[int], Sequence[Sequence[int]]]] = None, source_timezone: Optional[str] = None, model_timezone: Optional[str] = None, interpolation: str = 'Bilinear', ratio: Optional[float] = None, historic: bool = False, nodata_policy: str = 'error', cache_path: Optional[Union[str, Path]] = None, cache_policy: str = 'reuse', ras_object: Optional[Any] = None) -> GriddedPrecipitationImportResult

Configure projected GRIB/GRIB2 precipitation through a durable NetCDF.

Raster bands are read through GDAL/rasterio with caller-supplied interval-ending timestamps (for amounts/rates), depth units, and temporal semantics. The normalized cumulative cube is cached as HEC-RAS-compatible NetCDF and materialized into the unsteady HDF. This is also the safe route for GRIB encodings that GDAL can read but HEC-RAS cannot import directly.

WPC QPF GRIB2 remains a vendor-known special case through HEC-RAS 7.0.1. If the local GDAL stack cannot decode it, convert it to DSS with HEC-Vortex or HEC-MetVue and use :meth:configure_gridded_dss_precipitation.

Set historic=True for observed or analysis precipitation to write a unit ratio. A retained non-unit text or HDF ratio requires an explicit design choice, and a non-unit ratio with historic=True raises.

set_groundwater_interflow staticmethod

Python
set_groundwater_interflow(unsteady_number_or_path, values: list, boundary_index: int = 0, darcy_k: Optional[float] = None, darcy_k_per_day: Optional[float] = None, darcy_distance: Optional[float] = None, interval: Optional[str] = None, ras_object=None) -> None

Write groundwater interflow elevation data to a boundary block.

Replaces the inline elevation time series and optionally updates the three Darcy parameters for the GW interflow boundary at boundary_index.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "01") or direct file path. values : list[float] Groundwater elevation time series values. boundary_index : int, optional 0-based index of the GW interflow boundary to write (default 0). darcy_k : float, optional Hydraulic conductivity. If None, existing value is preserved. darcy_k_per_day : float, optional Conductivity per day. If None, existing value is preserved. darcy_distance : float, optional Darcy flow distance. If None, existing value is preserved. interval : str, optional Time interval (e.g. "1HOUR"). If None, preserved. ras_object : optional RasPrj instance for path resolution.

set_hydrograph_fixed_start_time staticmethod

Python
set_hydrograph_fixed_start_time(unsteady_number_or_path: Union[str, Path], use_fixed_start_time: bool, fixed_start_datetime: Optional[Union[str, Tuple[str, str], datetime, Timestamp]] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Set fixed-start timing for inline hydrograph boundary conditions.

HEC-RAS inline Flow/Stage/Lateral hydrographs are commonly stored as values relative to the simulation start. For warm-start continuation plans that begin after the original event start, the copied unsteady file needs Use Fixed Start Time enabled so the same hydrograph values remain aligned to the source-run clock.

Parameters:

Name Type Description Default
unsteady_number_or_path Union[str, Path]

Unsteady flow number or path to a .u## file.

required
use_fixed_start_time bool

Whether to enable fixed-start hydrograph timing.

required
fixed_start_datetime Optional[Union[str, Tuple[str, str], datetime, Timestamp]]

Fixed hydrograph start as a datetime, pandas Timestamp, (DDMMMYYYY, hhmm) pair, or "DDMMMYYYY,hhmm" string. Required when enabling fixed-start timing. Ignored when disabling.

None
ras_object Optional[Any]

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

None

Returns:

Type Description
Dict[str, Any]

Updated file path, target settings, and line counts.

Raises:

Type Description
ValueError

If enabling without a fixed start date/time, or if the unsteady file does not contain Use Fixed Start Time lines.

set_ic_from_output_profile staticmethod

Python
set_ic_from_output_profile(unsteady_number_or_path: Union[str, Path], source_plan_hdf: Union[str, Path], time_index: int = -1, include_1d: bool = True, include_storage: bool = True, ras_object: Optional[Any] = None) -> pd.DataFrame

Populate IC table from a completed simulation's output profile.

Reads flow at each 1D cross section and water-surface elevation at each storage area from the source HDF at the given time step, then writes the values as initial conditions in the target unsteady file.

This replicates the HEC-RAS GUI menu action Set Initial Conditions from Output File.

Parameters

unsteady_number_or_path : str or Path Target unsteady flow number or .u## file path. source_plan_hdf : str or Path Path to a completed plan HDF file containing results. time_index : int, default -1 Time step index to extract. -1 selects the last time step. include_1d : bool, default True Include 1D cross-section flow values. include_storage : bool, default True Include storage-area water-surface elevations. ras_object : RasPrj, optional RAS project object.

Returns

pd.DataFrame The IC entries that were written, with columns matching get_initial_conditions() output.

set_initial_conditions staticmethod

Python
set_initial_conditions(unsteady_number_or_path: Union[str, Path], ic_entries, ras_object: Optional[Any] = None, auto_set_method: bool = True) -> None

Write initial condition entries to a HEC-RAS unsteady flow file.

Replaces all existing Initial Flow Loc=, Initial Storage Elev=, and Initial RRR Elev= lines with the provided entries.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "03") or path to a .u## file. ic_entries : list[dict] or pd.DataFrame IC entries. Each row/dict must have:

Text Only
* ``type`` — ``'flow'``, ``'storage'``, or ``'rrr'``
* ``river``, ``reach``, ``station``, ``value`` (for flow/rrr)
* ``area_name``, ``value`` (for storage)

ras_object : RasPrj, optional RAS project object. If None, uses global ras. auto_set_method : bool, default True When True and entries are non-empty, automatically sets the IC method to initial_flow_distribution via set_initial_flow_method().

Examples

import pandas as pd ic_df = pd.DataFrame([ ... {'type': 'flow', 'river': 'White', 'reach': 'Muncie', ... 'station': 15696.24, 'value': 1500}, ... ]) RasUnsteady.set_initial_conditions("01", ic_df, ras_object=ras)

set_initial_flow_method staticmethod

Python
set_initial_flow_method(unsteady_file: Union[str, Path], method: str, restart_filename: Optional[str] = None, prior_ws_filename: Optional[str] = None, prior_ws_profile: Optional[str] = None, ras_object: Optional[Any] = None) -> None

Set the Initial Conditions method selection in an unsteady flow file.

Configures which IC approach HEC-RAS will use by writing the appropriate Use Restart value and optionally adding or removing associated lines.

Parameters

unsteady_file : str or Path Path to unsteady flow file or unsteady number. method : str One of: - 'restart_file' — enable restart mode (requires restart_filename) - 'prior_ws' — use prior water surface profile (requires prior_ws_filename; prior_ws_profile defaults to first profile) - 'initial_flow_distribution' — disable restart; existing IC lines are kept - 'none' — disable restart and remove all IC lines restart_filename : str, optional Required when method is 'restart_file'. prior_ws_filename : str, optional Plan file path (e.g. 'ProjectName.p01'). Required when method is 'prior_ws'. prior_ws_profile : str, optional Profile name within the prior steady plan. Defaults to empty string (HEC-RAS uses the first available profile). ras_object : optional RAS project object. If None, uses the global ras object.

Raises

ValueError If method is unknown or required arguments are missing.

set_initial_storage_elevation staticmethod

Python
set_initial_storage_elevation(unsteady_number_or_path: Union[str, Path], area_name: str, elevation: float, ras_object: Optional[Any] = None) -> None

Add or update a single storage/2D-area initial elevation.

Reads the current IC table, replaces the entry for area_name (or appends it if absent), and writes the table back.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number or path to a .u## file. area_name : str Storage area or 2D flow area name (as stored in the geometry). elevation : float Initial water-surface elevation for this area. ras_object : RasPrj, optional RAS project object.

set_lateral_inflow_hydrograph staticmethod

Python
set_lateral_inflow_hydrograph(unsteady_file: Union[str, Path], hydrograph_df: DataFrame, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, slope: Optional[float] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Write or replace a Lateral Inflow Hydrograph on a boundary condition.

If the matched boundary already has a Lateral Inflow Hydrograph= header and inline data, the existing data is replaced. Optionally updates Flow Hydrograph Slope= in the same call.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01"). hydrograph_df : pd.DataFrame DataFrame with a 'flow' column containing lateral inflow values. Must have at least 1 row. river, reach, station : str, optional 1D location selector. When all three are None the first Lateral Inflow Hydrograph boundary in the file is updated. slope : float, optional If provided, sets Flow Hydrograph Slope= for this boundary. Existing slope is updated or a new line is inserted. ras_object : optional Custom RAS object to use instead of the global one.

Returns

Dict[str, Any] Metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): matched ``Boundary Location=`` value
- ``value_count`` (int): number of flow values written
- ``flow_range`` (list): ``[min_flow, max_flow]``
- ``previous_value_count`` (int or None): prior count
- ``slope_written`` (float or None): slope value written
- ``boundaries_df_refreshed`` (bool): True when refreshed
Raises

ValueError If DataFrame is missing 'flow' column, is empty, or no matching boundary is found. FileNotFoundError If the unsteady flow file does not exist.

Examples

import pandas as pd from ras_commander import RasUnsteady flows = [1000 + i * 500 for i in range(25)] df = pd.DataFrame({'flow': flows}) result = RasUnsteady.set_lateral_inflow_hydrograph( ... "BaldEagleDamBrk.u01", df, slope=0.003, ... )

set_met_precipitation_mode staticmethod

Python
set_met_precipitation_mode(unsteady_file: Union[str, Path], mode: Optional[str], *, source: Optional[str] = None, constant_value: float = 1.0, constant_units: str = 'in/hr', dss_filename: Optional[Union[str, Path]] = None, dss_pathname: Optional[str] = None, gdal_filename: Optional[Union[str, Path]] = None, gdal_group: Optional[str] = None, gdal_folder: Optional[Union[str, Path]] = None, gdal_filter: Optional[str] = None, interpolation: str = 'Bilinear', point_interpolation: str = 'Thiessen Polygon', ras_object: Optional[Any] = None) -> None

Atomically configure precipitation meteorology keys in a .u## file.

The method rewrites the managed Precipitation Mode and Met BC=Precipitation|... state as a single block, removing stale mode/source keys from prior Constant, Point, DSS, GDAL, or legacy GDAL Datasetname states. Unrecognized precipitation keys such as Expanded View are preserved. Gridded mode also completes the required evapotranspiration, air-density, and air-pressure mode records without replacing explicit nonblank choices.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) or unsteady number. mode : {"Constant", "Gridded", "Point", "None"} Precipitation mode to write. None writes HEC-RAS mode None. source : {"DSS", "GDAL Raster File(s)"}, optional Required for gridded mode unless it can be inferred from supplied DSS or GDAL fields. constant_value : float, default 1.0 Constant precipitation rate written for Constant mode. constant_units : {"in/hr", "mm/hr"}, default "in/hr" Constant precipitation units. dss_filename, dss_pathname : optional Gridded DSS source fields. gdal_filename, gdal_group, gdal_folder, gdal_filter : optional Gridded GDAL source fields. Missing values are written as blank HEC-RAS keys so the GDAL state is complete from scratch. interpolation : {"Nearest", "Bilinear"}, default "Bilinear" Gridded interpolation method. point_interpolation : str, default "Thiessen Polygon" Point precipitation interpolation value. ras_object : optional Custom RAS object used to resolve an unsteady number.

Returns

None Modifies the .u## file in place via atomic replacement.

set_meteorological_station staticmethod

Python
set_meteorological_station(unsteady_file: Union[str, Path], name: str, x: float, y: float, longitude: Optional[float] = None, latitude: Optional[float] = None, height_m: Optional[float] = None, ras_object: Optional[Any] = None) -> None

Create or update a meteorological station definition in an unsteady flow file.

This writes the native HEC-RAS station metadata lines alongside the meteorological block. Existing precipitation settings are not modified.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) or unsteady number (e.g., "01"). name : str Meteorological station name. x, y : float Project coordinates for the station. longitude, latitude : float, optional Geographic coordinates for the station. height_m : float, optional Station height in meters. HEC-RAS requires this for wind, but not ET. ras_object : optional Custom RAS object to use instead of the global one.

set_navigation_dam staticmethod

Python
set_navigation_dam(unsteady_number_or_path, boundary_index: int = 0, params: Optional[str] = None, sft_flow: Optional[list] = None, sft_stage_open: Optional[list] = None, sft_stage_closed: Optional[list] = None, flow_monitor_rrr: Optional[str] = None, hinge_point_rrr: Optional[str] = None, cp_hinge_point: Optional[str] = None, cp_min_pool: Optional[str] = None, cp_max_pool: Optional[str] = None, ras_object=None) -> None

Write Navigation Dam BC data back to a .u## file.

Only provided (non-None) parameters are updated; others are preserved. If SFT table rows are provided, all three (flow, stage_open, stage_closed) must be provided together with equal length.

set_non_newtonian_clastic staticmethod

Python
set_non_newtonian_clastic(unsteady_number_or_path: Union[str, Path], clastic_method: Optional[Union[int, str]] = None, coulomb_phi: Optional[float] = None, voellmy_x: Optional[float] = None, hindered_fv: Optional[Union[int, str]] = None, fv_k: Optional[float] = None, ds: Optional[float] = None, high_c_transport: Optional[int] = None, ras_object: Optional[Any] = None) -> None

Set Clastic Grain-Flow and auxiliary Non-Newtonian parameters in a .u## file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. clastic_method : int or str, optional 0/"Coulomb" or 1/"Voellmy". coulomb_phi : float, optional Friction angle phi in degrees. Written as Coulomb Phi=. voellmy_x : float, optional Voellmy turbulence parameter Xi (only for Voellmy method). hindered_fv : int or str, optional 0/"No Hindered Settling" or 1/"User Specified K". fv_k : float, optional k power parameter for hindered settling equation. ds : float, optional Representative grain size in mm (O'Brien method). high_c_transport : int, optional High-concentration transport equation selector (0-2+). ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

set_non_newtonian_concentration staticmethod

Python
set_non_newtonian_concentration(unsteady_number_or_path: Union[str, Path], cv: Optional[float] = None, bulking_method: Optional[Union[int, str]] = None, max_cv: Optional[float] = None, ras_object: Optional[Any] = None) -> None

Set Non-Newtonian concentration and bulking parameters in a .u## file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. cv : float, optional Volumetric concentration in percent (e.g. 30.0 for 30%). bulking_method : int or str, optional 0/"Do Not Bulk" or 1/"Bulk Fluid Volume". max_cv : float, optional Maximum volumetric concentration in percent. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

set_non_newtonian_herschel_bulkley staticmethod

Python
set_non_newtonian_herschel_bulkley(unsteady_number_or_path: Union[str, Path], k: Optional[float] = None, n: Optional[float] = None, ras_object: Optional[Any] = None) -> None

Set Generalized Herschel-Bulkley parameters in a .u## file.

The HB model is: tau = tau_y + K * (du/dy)^n. When n=1 the model reduces to Bingham plastic.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. k : float, optional Consistency factor K. n : float, optional Power index n (n=1 is Bingham plastic). ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

set_non_newtonian_method staticmethod

Python
set_non_newtonian_method(unsteady_number_or_path: Union[str, Path], method: Union[int, str], ras_object: Optional[Any] = None) -> None

Set the Non-Newtonian method in an unsteady flow file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "03") or path to a .u## file. method : int or str Method to set. Accepts integer (0-4) or name string: 0/"Newtonian Assumptions", 1/"Bingham", 2/"O'Brien (Quadratic)", 3/"Clastic Grain-Flow", 4/"Generalized Herschel-Bulkley". ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Raises

ValueError If the method is not a valid integer (0-4) or recognized name.

set_non_newtonian_shear staticmethod

Python
set_non_newtonian_shear(unsteady_number_or_path: Union[str, Path], yield_method: Optional[Union[int, str]] = None, yield_coef: Optional[tuple] = None, user_yield: Optional[float] = None, visc_method: Optional[Union[int, str]] = None, obrien_b: Optional[float] = None, user_viscosity: Optional[float] = None, user_visc_ratio: Optional[float] = None, ras_object: Optional[Any] = None) -> None

Set Non-Newtonian yield stress and viscosity parameters in a .u## file.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number (e.g. "02") or path to a .u## file. yield_method : int or str, optional 0/"Exponential" or 1/"User Yield". yield_coef : tuple of (float, float), optional Exponential yield coefficients (a, b) for tau_y = a * exp(b * Cv). user_yield : float, optional User-specified constant yield stress in Pa. visc_method : int or str, optional 0/"Use Coulomb", 1/"Maron and Pierce", 2/"User Defined Viscosity", 3/"User Visc Ratio". obrien_b : float, optional O'Brien exponential viscosity B coefficient. user_viscosity : float, optional User-defined dynamic viscosity in Pa·s. user_visc_ratio : float, optional Viscosity ratio multiplier. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

set_normal_depth_boundary staticmethod

Python
set_normal_depth_boundary(unsteady_file: Union[str, Path], friction_slope: float, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, area_2d: Optional[str] = None, bc_line: Optional[str] = None, use_critical_fallback: bool = False, ras_object: Optional[Any] = None) -> Dict[str, Any]

Add or update a Normal Depth boundary condition for a target boundary in a HEC-RAS unsteady flow file (.u##).

The method writes a Friction Slope=<slope> line (or Friction Slope=<slope>,<flag> when a flag is required, see below) into the matching boundary block. If the block already has a Friction Slope= line it is updated in place; otherwise the line is inserted immediately after the Boundary Location= line, and any other inline-table BC header (Flow Hydrograph, Stage Hydrograph, Lateral Inflow, Uniform Lateral Inflow, Precipitation Hydrograph, Rating Curve, Gate Name) plus its inline data and any DSS metadata lines (Interval=, DSS File=, DSS Path=, Use DSS=) are stripped so the block ends up as a clean Normal Depth boundary.

The function ONLY edits a boundary that already exists in the .u## as a Boundary Location= block. If the matched-by-name location is absent, ValueError is raised. Authoring brand-new boundary blocks from geometry definitions (create-if-missing semantics with geometry-file validation) is tracked separately as a follow-up; see the See Also section.

Format conventions observed in real HEC-RAS .u## files

Both Friction Slope=<slope> and Friction Slope=<slope>,<flag> forms appear in HEC-RAS-emitted files. 2D Normal Depth boundaries (e.g. on 2D BC lines) are typically written without the flag, while 1D river Normal Depth boundaries usually include ,0. To stay compatible with both:

  • When updating an existing Friction Slope= line, the original flag presence is preserved unless use_critical_fallback=True forces the flag to be present and set to 1.
  • When inserting a new line (type conversion or the block had no recognized type), the flag is omitted by default, and only emitted (as ,1) when use_critical_fallback=True.
Target resolution

Provide exactly one of:

  • (river, reach, station) for a 1D river boundary, matched on the first three comma-separated fields of Boundary Location=.
  • (area_2d, bc_line) for a 2D BC line attached to a 2D Flow Area, matched on the Boundary Location= 2D Flow Area name (field index 5) and the BC line / SA name (field index 7). For Normal Depth, bc_line is required: a Normal Depth boundary must attach to a specific 2D Flow Area perimeter BC line, never to the area as a whole.
Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01") when a project-bound ras_object is available. friction_slope : float Energy slope for the Normal Depth boundary (m/m or ft/ft). Must be in the inclusive range [1e-7, 1.0]. river, reach, station : str, optional 1D location selector. All three must be provided together and only when the 2D selectors are not used. area_2d : str, optional 2D Flow Area name selector. Required for 2D targeting, and must be paired with bc_line. bc_line : str, optional BC line name on the 2D Flow Area perimeter. Required for 2D targeting; Normal Depth never applies area-wide. use_critical_fallback : bool, default False Forces the flag to be present and set to 1 on the Friction Slope= line. When False (the default), the flag is omitted from newly inserted lines and preserved as-was for in-place updates. True writes Friction Slope=<slope>,1. ras_object : optional Custom RAS object to use instead of the global one. When the object is initialized for a project, boundaries_df is refreshed after the write.

Returns

Dict[str, Any] Reviewable before/after metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): the matched ``Boundary Location=``
  line value (without the leading ``Boundary Location=``)
- ``previous_bc_type`` (str | None): boundary type before the edit,
  or ``None`` if the block had no recognized type keyword
- ``previous_friction_slope`` (float | None): prior slope value,
  or ``None`` if no Friction Slope line existed
- ``new_friction_slope`` (float): slope written
- ``flag`` (int | None): the integer flag written on the line
  (typically ``0`` or ``1``), or ``None`` when the line was
  written without a flag
- ``lines_removed`` (int): count of old type-header / inline-data /
  DSS-metadata lines stripped during a type conversion
- ``lines_inserted`` (int): 1 if a new ``Friction Slope=`` line was
  inserted, otherwise 0
- ``updated_in_place`` (bool): True when an existing
  ``Friction Slope=`` line was overwritten without insertion
- ``boundaries_df_refreshed`` (bool): True when ``ras_object``
  ``boundaries_df`` was refreshed after the write
- ``block_before`` (str): the boundary block text before the edit
- ``block_after`` (str): the boundary block text after the edit
Raises

ValueError If friction_slope is non-numeric, non-finite, or outside [1e-7, 1.0]; if the target selectors are inconsistent (both 1D and 2D selectors provided, or neither); if a 1D selector is partial; if a 2D selector is missing bc_line; or if no boundary in the file matches the selectors. FileNotFoundError If the unsteady flow file does not exist.

Examples

Set a Normal Depth boundary on a 2D BC line (writes Friction Slope=0.0003 with no flag, matching the 2D format emitted by HEC-RAS for examples like BaldEagleCrkMulti2D):

from ras_commander import RasUnsteady result = RasUnsteady.set_normal_depth_boundary( ... "project.u01", ... friction_slope=0.0003, ... area_2d="BaldEagleCr", ... bc_line="DSNormalDepth", ... ) result["new_friction_slope"], result["updated_in_place"] (0.0003, False)

Update an existing Normal Depth slope on a 1D downstream boundary (preserves the original ,<flag> form when present, e.g. Friction Slope=0.00064,0 becomes Friction Slope=0.001,0):

RasUnsteady.set_normal_depth_boundary( ... "project.u01", ... friction_slope=0.001, ... river="White", ... reach="Muncie", ... station="237.6455", ... )

See Also

set_boundary_dss_link : Convert inline BC to DSS-linked. set_boundary_inline_hydrograph : Write inline hydrograph table. ras_commander.RasPrj.get_boundary_conditions : Parse boundaries to boundaries_df.

Notes

1D applicability: Normal Depth is a downstream-only boundary condition for 1D reaches. HEC-RAS uses the Manning equation with the specified friction slope to compute the stage at the most downstream cross section. Do not apply this to upstream 1D boundaries — use Flow Hydrograph or Stage Hydrograph instead.

Follow-up scope (out of this function): validation that the selected boundary actually exists in the geometry file, and creating a brand-new Boundary Location= block when the boundary exists in geometry but is absent from the .u##. Tracked under a separate Linear ticket so the contracts for placement order, geometry discovery, and 1D-vs-2D field padding can be designed end-to-end.

set_point_evapotranspiration staticmethod

Python
set_point_evapotranspiration(unsteady_file: Union[str, Path], station_name: str, et_df: DataFrame, value_column: Optional[str] = None, time_column: Optional[str] = None, units: str = 'mm/day', interpolation: str = 'Nearest', x: Optional[float] = None, y: Optional[float] = None, longitude: Optional[float] = None, latitude: Optional[float] = None, height_m: Optional[float] = None, ras_object: Optional[Any] = None) -> None

Set point evapotranspiration mode and write station time-series data.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) or unsteady number (e.g., "01"). station_name : str Meteorological station name used by the ET time series. et_df : pandas.DataFrame ET time series. Provide either a DatetimeIndex, a datetime/time column, or an hour column. Values are detected from common ET column names or can be specified with value_column. value_column : str, optional ET value column. Defaults to common names such as evapotranspiration, potential_et, pet, et, or value. time_column : str, optional Datetime column name. Use "index" to force the DataFrame index. units : str, default "mm/day" ET units written to the meteorological block. interpolation : str, default "Nearest" Point interpolation method for the ET meteorological boundary condition. x, y, longitude, latitude, height_m : float, optional Station metadata. If x and y are provided, the station definition is created or updated before the ET series is written. ras_object : optional Custom RAS object to use instead of the global one.

set_precipitation_hyetograph staticmethod

Python
set_precipitation_hyetograph(unsteady_file: Union[str, Path], hyetograph_df: DataFrame, boundary_name: Optional[str] = None, ras_object: Optional[Any] = None) -> None

Set precipitation hyetograph in an unsteady flow file from a DataFrame.

This method writes hyetograph data directly to the "Precipitation Hydrograph=" section in HEC-RAS unsteady flow files (.u##). It automatically detects the time interval from the DataFrame and formats values in HEC-RAS fixed-width format.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) or unsteady number (e.g., "01") hyetograph_df : pd.DataFrame DataFrame with columns: - 'hour': Regular interval-end hours from the existing boundary start. Start at one interval, or include a zero-depth row at hour zero. - 'incremental_depth': Depth over the preceding interval (inches for a US-customary model, mm for an SI model; no unit conversion). - 'cumulative_depth': Cumulative sum of incremental depths in the same units. boundary_name : str, optional Exact, case-insensitive area name in Boundary Location field 5. Named selection is verified for 2D Flow Areas; Storage Area layouts require separate native verification. A supplied name must identify exactly one precipitation boundary. If None, updates the first Precipitation Hydrograph found. ras_object : optional Custom RAS object to use instead of the global one

Returns

None The function modifies the file in-place.

Raises

ValueError If data, timing, fixed-width range or the target inline boundary is invalid, or the source file mixes newline conventions FileNotFoundError If unsteady flow file not found

Example

from ras_commander import RasUnsteady, init_ras_project from ras_commander.precip import StormGenerator

Generate hyetograph

ddf = StormGenerator.download_from_coordinates(29.76, -95.37) hyeto = StormGenerator.generate_hyetograph( ... ddf_data=ddf, ... total_depth_inches=17.0, ... duration_hours=24, ... position_percent=50 ... )

Write to unsteady file

RasUnsteady.set_precipitation_hyetograph("project.u01", hyeto)

Notes

DataFrame Format: - All methods in ras-commander.precip return DataFrames with the required columns - Atlas14Storm, FrequencyStorm, ScsTypeStorm (from hms-commander) also use this format

Interval Detection: - Interval is calculated from hour column spacing (e.g., 1.0 → "1HOUR", 0.5 → "30MIN") - The unique Interval= line inside the selected boundary block is updated

Fixed-Width Format: - Values formatted as 8-character fixed-width fields (two decimals, ValueError if a value cannot fit) - 10 incremental-depth values per line - Count includes a zero-depth ordinate at the existing boundary start. - A value at time t is the depth over the preceding interval. - Existing fixed-start/simulation-start selection is preserved; cover the required simulation window and append explicit dry intervals as needed.

Depth Conservation: - Cumulative depths are rounded to 0.01, then differenced for serialization. - Total and interval-end cumulative depths differ by at most 0.005 depth units (floating-point tolerance aside); individual increments can differ by up to 0.01. This avoids accumulated independent-rounding error. - Native interval timing was checked on the HEC-RAS 7.0 Davis example; other versions, units and boundary-start configurations need their own solver-level check. This method does not establish hydraulic acceptance.

See Also

StormGenerator.generate_hyetograph : Generate design storm hyetograph Atlas14Storm.generate_hyetograph : HMS-equivalent hyetograph (from hms-commander)

set_prior_ws_filename staticmethod

Python
set_prior_ws_filename(unsteady_file: Union[str, Path], prior_ws_filename: str, prior_ws_profile: Optional[str] = None, ras_object: Optional[Any] = None) -> None

Write Prior WS Filename and Profile to an unsteady flow file.

Convenience wrapper around set_initial_flow_method(method='prior_ws'). Sets the IC method to prior water surface and writes the plan file reference and optional profile name.

Parameters

unsteady_file : str or Path Path to unsteady flow file or unsteady number. prior_ws_filename : str Plan file to use (e.g. 'ProjectName.p01'). prior_ws_profile : str, optional Profile name. Defaults to empty (HEC-RAS uses first profile). ras_object : optional RAS project object. If None, uses the global ras object.

set_rating_curve staticmethod

Python
set_rating_curve(unsteady_file: Union[str, Path], rating_curve_df: DataFrame, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Write or replace a Rating Curve table on a boundary condition.

If the matched boundary already has a Rating Curve= header and inline data, the existing data is replaced. If the boundary exists but has no rating curve data yet, a Rating Curve= header and data lines are inserted.

Rating Curves are static stage-discharge relationships and have no Interval= line. The data is stored as (stage, discharge) pairs in 8-character fixed-width format, 10 values per line (5 pairs).

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01") when a project-bound ras_object is available. rating_curve_df : pd.DataFrame DataFrame with columns ['stage', 'discharge']. Must have at least 2 rows and be sorted by ascending stage. river, reach, station : str, optional 1D location selector. When all three are None the first Rating Curve boundary in the file is updated. ras_object : optional Custom RAS object to use instead of the global one.

Returns

Dict[str, Any] Reviewable metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): matched ``Boundary Location=`` value
- ``pair_count`` (int): number of (stage, discharge) pairs written
- ``stage_range`` (list): ``[min_stage, max_stage]``
- ``discharge_range`` (list): ``[min_discharge, max_discharge]``
- ``previous_pair_count`` (int or None): prior pair count, or
  ``None`` if no Rating Curve data existed
- ``boundaries_df_refreshed`` (bool): True when ``ras_object``
  ``boundaries_df`` was refreshed after the write
Raises

ValueError If DataFrame is missing required columns, has fewer than 2 rows, or no matching boundary is found. FileNotFoundError If the unsteady flow file does not exist.

Examples

import pandas as pd from ras_commander import RasUnsteady rc = pd.DataFrame({ ... 'stage': [210, 220, 230, 240, 250], ... 'discharge': [0, 50000, 200000, 500000, 1000000], ... }) result = RasUnsteady.set_rating_curve( ... "Manning'snCalibra.u01", rc, ... river="Mississippi", reach="Lower Miss.", station="846", ... )

set_restart_settings staticmethod

Python
set_restart_settings(unsteady_file: str, use_restart: bool, restart_filename: Optional[str] = None, ras_object: Optional[Any] = None) -> None

Set restart-file usage in an unsteady flow file.

Alias for update_restart_settings() using setter-style naming. This method writes Use Restart and Restart Filename in the unsteady file. Restart output creation is configured separately on the plan file with RasPlan.set_restart_output_settings().

set_rules_bc staticmethod

Python
set_rules_bc(unsteady_number_or_path, boundary_index: int = 0, rule_lines: Optional[list] = None, gate_data: Optional[list] = None, description: Optional[str] = None, ras_object=None) -> None

Write Rule Operations BC data back to a .u## file.

This replaces the Rule Operation/Expression lines and optionally the gate data and description within the specified boundary block. Only provided (non-None) parameters are updated.

set_stage_flow_hydrograph staticmethod

Python
set_stage_flow_hydrograph(unsteady_file: Union[str, Path], stage_flow_df: DataFrame, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, ras_object: Optional[Any] = None) -> dict

Write observed stage/flow pairs to an internal boundary condition.

Creates or replaces the Observed Stage and Flow Hydrograph= block in a .u## file. Data is written as interleaved (stage, flow) pairs in 8-character fixed-width format, 10 values per line (5 pairs per line).

Parameters

unsteady_file : str or Path Path to unsteady flow file or unsteady number (e.g. "01"). stage_flow_df : pd.DataFrame DataFrame with columns ['stage', 'flow']. river : str, optional River name for location matching. reach : str, optional Reach name for location matching. station : str, optional River station for location matching. ras_object : optional RasPrj instance; falls back to the global ras object.

Returns

dict - pair_count (int): Number of stage/flow pairs written. - matched_location (str): Raw Boundary Location= value matched. - unsteady_file (str): Path to the written file. - boundaries_df_refreshed (bool): True when ras_object boundaries were refreshed after writing.

Raises

ValueError If DataFrame is missing required columns or is empty. FileNotFoundError If unsteady flow file not found.

See Also

get_stage_flow_hydrograph : Read stage/flow pairs from a .u## file.

set_stage_hydrograph_initial_stage staticmethod

Python
set_stage_hydrograph_initial_stage(unsteady_file: Union[str, Path], use_initial_stage: bool, *, area_2d: str, bc_line: str, ras_object: Optional[Any] = None) -> Dict[str, Any]

Set the initial-stage flag on one exact 2D stage hydrograph.

Writes Stage Hydrograph Use Initial Stage=0/1 in the selected unsteady file. This controls initialization from the prescribed stage; it does not change stage ordinates, flow forcing, geometry or units. Supply an owned child copy. Other boundary bytes and line endings are preserved. Returns the selected location and before/after flag values. Missing, ambiguous or non-stage boundaries raise before any write. unsteady_file accepts a path or a project-bound unsteady number. No engine is run and no hydraulic acceptance is inferred.

set_stage_hydrograph_tw_check staticmethod

Python
set_stage_hydrograph_tw_check(unsteady_file: Union[str, Path], tw_check: int, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, area_2d: Optional[str] = None, bc_line: Optional[str] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Add or update a Stage Hydrograph TW Check flag on a Flow Hydrograph boundary in a HEC-RAS unsteady flow file (.u##).

Despite the misleading keyword name Stage Hydrograph TW Check=, this field appears inside Flow Hydrograph boundary blocks in HEC-RAS-emitted .u## files. It controls whether HEC-RAS performs a tailwater check for the boundary (0 = disabled, 1 = enabled).

Behavior
  • Update path: if a Stage Hydrograph TW Check= line already exists in the matched boundary block, its value is overwritten in place.
  • Insert path: if no TW Check line exists, a new line is inserted in the canonical position: after Flow Hydrograph QMult= if present, otherwise after Flow Hydrograph Slope= if present, otherwise immediately before the first DSS metadata line (DSS Path=, DSS File=, Use DSS=), otherwise just before the first = line after the inline hydrograph data.
Target resolution

Provide exactly one of:

  • (river, reach, station) for a 1D river boundary.
  • (area_2d, bc_line) for a 2D BC line on a 2D Flow Area perimeter.
Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01") when a project-bound ras_object is available. tw_check : int Tailwater check flag. Must be 0 (disabled) or 1 (enabled). river, reach, station : str, optional 1D location selector. All three must be provided together. area_2d, bc_line : str, optional 2D location selector. Both must be provided together. ras_object : optional Custom RAS object. When initialized for a project, boundaries_df is refreshed after the write.

Returns

Dict[str, Any] Reviewable metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): the matched ``Boundary Location=``
- ``bc_type`` (str): always ``'Flow Hydrograph'``
- ``previous_tw_check`` (int | None): prior value, or ``None``
- ``new_tw_check`` (int): value written
- ``updated_in_place`` (bool): True if existing line overwritten
- ``lines_inserted`` (int): 1 if new line inserted, else 0
- ``insert_anchor`` (str | None): keyword anchor used for insert
- ``boundaries_df_refreshed`` (bool)
- ``block_before`` (str): boundary block text before edit
- ``block_after`` (str): boundary block text after edit
Raises

ValueError If tw_check is not 0 or 1; if selectors are invalid; if the matched block is not a Flow Hydrograph. FileNotFoundError If the unsteady flow file does not exist.

Examples

Enable TW check on a 2D Flow Hydrograph boundary:

result = RasUnsteady.set_stage_hydrograph_tw_check( ... "BaldEagleDamBrk.u02", ... tw_check=1, ... area_2d="BaldEagleCr", ... bc_line="Upstream Inflow", ... ) result["new_tw_check"] 1

See Also

set_flow_hydrograph_slope : Set distribution slope on Flow Hydrograph.

set_uniform_lateral_inflow_hydrograph staticmethod

Python
set_uniform_lateral_inflow_hydrograph(unsteady_file: Union[str, Path], hydrograph_df: DataFrame, river: Optional[str] = None, reach: Optional[str] = None, station: Optional[str] = None, slope: Optional[float] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Write or replace a Uniform Lateral Inflow Hydrograph on a boundary.

If the matched boundary already has a Uniform Lateral Inflow Hydrograph= header and inline data, the existing data is replaced. Optionally updates Flow Hydrograph Slope= in the same call.

Uniform lateral inflow is a reach-based BC type: the inflow is applied uniformly across a reach segment (between two river stations).

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##), or a 1-2 character unsteady number (e.g. "01"). hydrograph_df : pd.DataFrame DataFrame with a 'flow' column containing uniform lateral inflow values. Must have at least 1 row. river, reach, station : str, optional 1D location selector. When all three are None the first Uniform Lateral Inflow Hydrograph boundary in the file is updated. slope : float, optional If provided, sets Flow Hydrograph Slope= for this boundary. ras_object : optional Custom RAS object to use instead of the global one.

Returns

Dict[str, Any] Metadata with keys:

Text Only
- ``unsteady_file`` (str): absolute path written
- ``matched_location`` (str): matched ``Boundary Location=`` value
- ``value_count`` (int): number of flow values written
- ``flow_range`` (list): ``[min_flow, max_flow]``
- ``previous_value_count`` (int or None): prior count
- ``slope_written`` (float or None): slope value written
- ``boundaries_df_refreshed`` (bool): True when refreshed
Raises

ValueError If DataFrame is missing 'flow' column, is empty, or no matching boundary is found. FileNotFoundError If the unsteady flow file does not exist.

update_boundary_dss_paths staticmethod

Python
update_boundary_dss_paths(unsteady_file: Union[str, Path], updates: List[Dict[str, Any]], ras_object: Optional[Any] = None) -> int

Apply multiple DSS path and multiplier updates to boundary conditions.

This batch method processes multiple updates in a single file read/write cycle for efficiency. Each update can specify any combination of A-part change and/or multiplier change.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) updates : List[Dict[str, Any]] List of update dictionaries. Each dict can contain: - river_station: str (required) - partial match supported - new_a_part: str (optional) - new DSS A-part value - old_a_part: str (optional) - only replace if current A-part matches - new_multiplier: float (optional) - new QMult value ras_object : optional Custom RAS object to use instead of the global one

Returns

int Total number of updates applied

Example

from ras_commander import RasUnsteady updates = [ ... {'river_station': '23280.75', 'old_a_part': 'A1200000_2347_J', 'new_a_part': 'A120A'}, ... {'river_station': '12727.63', 'old_a_part': 'A120D1', 'new_a_part': 'A120C'}, ... {'river_station': '5714.48', 'new_multiplier': 0.75}, ... {'river_station': '29113.3', 'new_a_part': 'A120B', 'new_multiplier': 0.5}, ... ] count = RasUnsteady.update_boundary_dss_paths("project.u02", updates) print(f"Applied {count} updates")

Notes

This method reads the file once, applies all updates in memory, and writes once. This is more efficient than calling individual update methods for each boundary, especially when updating many boundaries.

update_dss_path_by_station staticmethod

Python
update_dss_path_by_station(unsteady_file: Union[str, Path], river_station: str, new_a_part: str, old_a_part: str = None, ras_object: Optional[Any] = None) -> int

Update the DSS Path A-part for boundary conditions at a specific river station.

This function modifies the DSS Path values in a .u## file, changing the A-part (first segment) from one value to another. Useful for mapping HMS subbasins to different DSS outputs.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) river_station : str River station identifier (partial match supported) new_a_part : str New A-part value (e.g., "A120A") old_a_part : str, optional Only replace if current A-part matches this value. If None, replaces regardless of current value. ras_object : optional Custom RAS object to use instead of the global one

Returns

int Number of DSS paths updated

Example

from ras_commander import RasUnsteady

Update A-part for boundary at specific station

count = RasUnsteady.update_dss_path_by_station( ... "project.u02", ... river_station="23280.75", ... old_a_part="A1200000_2347_J", ... new_a_part="A120A" ... ) print(f"Updated {count} DSS paths")

update_dss_run_identifier staticmethod

Python
update_dss_run_identifier(unsteady_file: Union[str, Path], old_run_id: str, new_run_id: str, ras_object: Optional[Any] = None) -> int

Update the DSS path run identifier (F-part) for all matching boundaries.

This function modifies the DSS Path values in a .u## file, changing the run identifier (Part F) from one value to another. This is useful when updating precipitation from TP40 to Atlas 14, where the run identifier indicates the storm scenario.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) old_run_id : str Current run identifier to replace (e.g., "RUN:1%_24HR") new_run_id : str New run identifier value (e.g., "RUN:1%_24HR_ATLAS14") ras_object : optional Custom RAS object to use instead of the global one

Returns

int Number of DSS paths updated

Example

from ras_commander import RasUnsteady

Update run identifier from TP40 to Atlas 14

count = RasUnsteady.update_dss_run_identifier( ... "project.u01", ... old_run_id="RUN:1%_24HR", ... new_run_id="RUN:1%_24HR_ATLAS14" ... ) print(f"Updated {count} DSS paths")

Notes

The DSS path format is: //A/B/C/D/E/F/ This function modifies Part F (run identifier) while preserving all other parts.

update_flow_multiplier_by_station staticmethod

Python
update_flow_multiplier_by_station(unsteady_file: Union[str, Path], river_station: str, new_multiplier: float, ras_object: Optional[Any] = None) -> bool

Update or insert Flow Hydrograph QMult for boundary at specific river station.

If the Flow Hydrograph QMult= line exists, it will be updated. If it doesn't exist, it will be inserted after the Flow Hydrograph line.

Parameters

unsteady_file : str or Path Path to the unsteady flow file (.u##) river_station : str River station identifier (partial match supported) new_multiplier : float New multiplier value (e.g., 0.5, 1.0) ras_object : optional Custom RAS object to use instead of the global one

Returns

bool True if multiplier was updated/inserted, False if boundary not found

Example

from ras_commander import RasUnsteady

Set flow multiplier to 0.75 for specific boundary

success = RasUnsteady.update_flow_multiplier_by_station( ... "project.u02", ... river_station="5714.48", ... new_multiplier=0.75 ... ) if success: ... print("Multiplier updated successfully")

Notes

The QMult line appears in unsteady files as: Flow Hydrograph QMult= 0.5

If this line doesn't exist, it will be inserted after the Flow Hydrograph line in the boundary block.

update_flow_title staticmethod

Python
update_flow_title(unsteady_file: str, new_title: str, ras_object: Optional[Any] = None) -> None

Update the Flow Title in an unsteady flow file (.u*).

The Flow Title provides a descriptive identifier for unsteady flow scenarios in HEC-RAS. It appears in the HEC-RAS interface and helps differentiate between different flow files.

Parameters:

Name Type Description Default
unsteady_file str

Path to the unsteady flow file or unsteady flow number

required
new_title str

New flow title (max 24 characters, will be truncated if longer)

required
ras_object optional

Custom RAS object to use instead of the global one

None

Returns:

Type Description
None

The function modifies the file in-place and updates the ras object's unsteady dataframe

Example

Clone an existing unsteady flow file

new_unsteady_number = RasPlan.clone_unsteady("02")

Get path to the new unsteady flow file

new_unsteady_file = RasPlan.get_unsteady_path(new_unsteady_number)

Update the flow title

new_title = "Modified Flow Scenario" RasUnsteady.update_flow_title(new_unsteady_file, new_title)

update_restart_settings staticmethod

Python
update_restart_settings(unsteady_file: str, use_restart: bool, restart_filename: Optional[str] = None, ras_object: Optional[Any] = None) -> None

Update the restart file settings in an unsteady flow file.

Restart files in HEC-RAS allow simulations to continue from a previously saved state, which is useful for long simulations or when making downstream changes. This method controls restart-file usage only. To configure a plan to write restart files, use RasPlan.set_restart_output_settings().

Parameters:

Name Type Description Default
unsteady_file str

Path to the unsteady flow file or unsteady number

required
use_restart bool

Whether to use a restart file (True) or not (False)

required
restart_filename str

Path to the restart file (.rst) Required if use_restart is True

None
ras_object optional

Custom RAS object to use instead of the global one

None

Returns:

Type Description
None

The function modifies the file in-place and updates the ras object's unsteady dataframe

Example

Enable restart file for an unsteady flow

unsteady_file = RasPlan.get_unsteady_path("03") RasUnsteady.update_restart_settings( unsteady_file, use_restart=True, restart_filename="model_restart.rst" )

update_unsteady_description staticmethod

Python
update_unsteady_description(unsteady_number_or_path: Union[str, Path], description: str, ras_object: Optional[Any] = None) -> bool

Update or insert the description in an unsteady flow file (.u##).

Parameters:

Name Type Description Default
unsteady_number_or_path Union[str, Path]

The unsteady number (e.g., '01') or path to the unsteady flow file.

required
description str

Description text to write.

required
ras_object optional

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

None

Returns:

Type Description
bool

True if successful, False otherwise.

Raises:

Type Description
ValueError

If the unsteady flow file is not found.

validate_initial_flow_stations staticmethod

Python
validate_initial_flow_stations(unsteady_number_or_path: Union[str, Path], geom_number_or_path: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Validate that Initial Flow Loc stations match cross sections in geometry.

Reads the IC table from the unsteady file and checks each flow entry against cross sections parsed from the geometry file. Reports matched, unmatched, and summary statistics.

Parameters

unsteady_number_or_path : str or Path Unsteady flow number or path to a .u## file. geom_number_or_path : str or Path, optional Geometry file number or path. If None, resolves via the plan that references this unsteady file. ras_object : RasPrj, optional RAS project object. If None, uses the global ras object.

Returns

dict valid (bool): True if all flow stations have matching XS. matched (list[dict]): Entries with matching geometry XS. unmatched (list[dict]): Entries with no matching geometry XS. ic_count (int): Total flow IC entries checked. geom_xs_count (int): Total XS in geometry. status (str): passed, failed, unavailable, or not_applicable. reason (str): Explicit outcome reason. Present flow ICs with missing or unreadable geometry are unavailable and valid=False. No flow IC entries is not_applicable and vacuously valid; this is not a completeness check for the boundary conditions or the plan.

write_table_to_file staticmethod

Python
write_table_to_file(unsteady_file: str, table_name: str, df: DataFrame, start_line: int, ras_object: Optional[Any] = None) -> None

Write an updated table back to an unsteady flow file in the required fixed-width format.

This function takes a modified DataFrame and writes it back to the unsteady flow file, preserving the 8-character fixed-width format that HEC-RAS requires.

Parameters:

Name Type Description Default
unsteady_file str

Path to the unsteady flow file

required
table_name str

Name of the table to update (e.g., 'Flow Hydrograph=')

required
df DataFrame

DataFrame containing the updated values with a 'Value' column

required
start_line int

Line number where the table data begins in the file

required
ras_object optional

Custom RAS object to use instead of the global one

None

Returns:

Type Description
None

The function modifies the file in-place

Example

Identify tables in the unsteady flow file

tables = RasUnsteady.identify_tables(lines) table_name, start_line, end_line = tables[0]

Parse and modify the table

table_df = RasUnsteady.parse_fixed_width_table(lines, start_line, end_line) table_df['Value'] = table_df['Value'] * 0.75 # Scale values to 75%

Write modified table back to the file

RasUnsteady.write_table_to_file(new_unsteady_file, table_name, table_df, start_line)

RasSteady

Static API for HEC-RAS steady flow files.

The writer emits the common HEC-RAS text structure used by .f## files: header, one River Rch & RM= flow-change block per station, one profile-specific Boundary for River Rch & Prof#= block per reach and profile, and optional DSS import metadata.

Numeric values (flows, known water surfaces, normal-depth slopes, and rating-curve points) are written into HEC-RAS 8-character fields. Values keep as many significant digits as fit, using HEC-RAS's own trimmed decimal convention (for example 2680.8, 268.1531, .0817947; no scientific notation). A value whose 8-character text would differ from it by more than FIXED_WIDTH_RELATIVE_TOLERANCE (relative), including magnitudes of 1e8 and above, raises ValueError before any file is written.

boundary staticmethod

Python
boundary(river: str, reach: str, profile: Optional[int] = None, upstream: Optional[Any] = None, downstream: Optional[Any] = None) -> dict[str, Any]

Build a steady boundary block.

If profile is omitted, profile-specific lists in upstream or downstream are expanded into one boundary block per profile during writing.

create_flow_file staticmethod

Python
create_flow_file(flow_file: Union[str, Number, Path], flow_title: Optional[str] = None, profile_names: Optional[Sequence[str]] = None, flow_changes: Optional[Sequence[Mapping[str, Any]]] = None, boundaries: Optional[Sequence[Mapping[str, Any]]] = None, program_version: str = '6.60', dss_import: Optional[Mapping[str, Any]] = None, ras_object: Optional[Any] = None, **kwargs: Any) -> Path

Create a new steady flow file from profile, flow, and boundary data.

title= is accepted as an alias for flow_title= for notebook ergonomics.

critical_depth staticmethod

Python
critical_depth() -> dict[str, Any]

Return a critical-depth boundary specification.

known_water_surface staticmethod

Python
known_water_surface(values: Any) -> dict[str, Any]

Return a known-water-surface boundary specification.

normal_depth staticmethod

Python
normal_depth(slopes: Any) -> dict[str, Any]

Return a normal-depth boundary specification.

rating_curve staticmethod

Python
rating_curve(points: Any) -> dict[str, Any]

Return a rating-curve boundary specification.

Tuple/list points use HEC-RAS steady-flow file order: (flow, water_surface). Mapping points may use flow plus stage, elevation, or wse keys.

read_flow_file staticmethod

Python
read_flow_file(flow_file: Union[str, Number, Path], ras_object: Optional[Any] = None) -> dict[str, Any]

Read a HEC-RAS steady flow file (.f##) into a structured dictionary.

Parameters:

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

Direct path to a .f## file or, when a project is initialized, a steady flow number such as "01".

required
ras_object Optional[Any]

Optional RAS project object. If omitted, direct paths are used as-is and flow numbers are resolved through the global project object.

None

Returns:

Type Description
dict[str, Any]

Dictionary with flow_title, program_version,

dict[str, Any]

profile_names, number_of_profiles, flow_changes,

dict[str, Any]

boundaries, and dss_import.

update_flow_file staticmethod

Python
update_flow_file(flow_file: Union[str, Number, Path], flow_title: Optional[str] = None, profile_names: Optional[Sequence[str]] = None, flow_changes: Optional[Sequence[Mapping[str, Any]]] = None, boundaries: Optional[Sequence[Mapping[str, Any]]] = None, program_version: Optional[str] = None, dss_import: Optional[Mapping[str, Any]] = None, ras_object: Optional[Any] = None) -> Path

Update selected sections of an existing steady flow file in place.

validate_flow_file_data staticmethod

Python
validate_flow_file_data(data: Mapping[str, Any]) -> bool

Validate steady flow data before writing.

Raises:

Type Description
ValueError

If profile counts, flow counts, or boundary value counts are inconsistent.

write_flow_file staticmethod

Python
write_flow_file(flow_file: Union[str, Number, Path], data: Mapping[str, Any], ras_object: Optional[Any] = None) -> Path

Write a structured steady flow dictionary to a HEC-RAS .f## file.

The input is validated before any file is written. Flow-value counts, profile names, and profile-specific boundary values must match the declared profile count. Every numeric value must be representable in an 8-character HEC-RAS field within FIXED_WIDTH_RELATIVE_TOLERANCE; otherwise ValueError is raised and the file is left unchanged.

Compatibility aliases: create → create_flow_file, known_ws → known_water_surface, parse_flow_file → read_flow_file, read → read_flow_file, update → update_flow_file, validate → validate_flow_file_data, write → write_flow_file, write_file → write_flow_file.

Utilities

RasUtils

A class containing utility functions for the ras-commander library. When integrating new functions that do not clearly fit into other classes, add them here.

backup_files staticmethod

Python
backup_files(files: List[Union[Path, str]], project_folder: Union[Path, str], operation_label: str = 'deleted') -> Optional[Path]

Move files to a timestamped Backup folder inside the project.

Creates {project_folder}/Backup/{YYYY-MM-DD_HHMMSS}_{operation_label}/ and moves each existing file into that folder. Non-existent files are silently skipped.

Parameters: files (List[Union[Path, str]]): File paths to back up (str or Path). project_folder (Union[Path, str]): Project root where Backup/ will be created. operation_label (str): Label appended to timestamp folder name (e.g., "deleted_p05").

Returns: Optional[Path]: Path to backup folder if any files were moved, None otherwise.

Example:

files = [Path("Muncie.p05"), Path("Muncie.p05.hdf")] backup_dir = RasUtils.backup_files(files, project_folder, "deleted_p05")

calculate_error_metrics staticmethod

Python
calculate_error_metrics(observed_values: ndarray, predicted_values: ndarray) -> Dict[str, float]

Compute a trio of error metrics: correlation, RMSE, and Percent Bias.

Parameters:

Name Type Description Default
observed_values ndarray

Actual observations time series.

required
predicted_values ndarray

Estimated/predicted time series.

required

Returns:

Type Description
Dict[str, float]

A dictionary containing correlation ('cor'), RMSE ('rmse'), and Percent Bias ('pb').

Example

observed = np.array([1, 2, 3]) predicted = np.array([1.1, 2.2, 2.9]) RasUtils.calculate_error_metrics(observed, predicted)

calculate_percent_bias staticmethod

Python
calculate_percent_bias(observed_values: ndarray, predicted_values: ndarray, as_percentage: bool = False) -> float

Calculate the Percent Bias between observed and predicted values.

Parameters:

Name Type Description Default
observed_values ndarray

Actual observations time series.

required
predicted_values ndarray

Estimated/predicted time series.

required
as_percentage bool

If True, return bias as a percentage. Defaults to False.

False

Returns:

Type Description
float

The calculated Percent Bias.

Example

observed = np.array([1, 2, 3]) predicted = np.array([1.1, 2.2, 2.9]) RasUtils.calculate_percent_bias(observed, predicted, as_percentage=True) 3.33333333

calculate_rmse staticmethod

Python
calculate_rmse(observed_values: ndarray, predicted_values: ndarray, normalized: bool = True) -> float

Calculate the Root Mean Squared Error (RMSE) between observed and predicted values.

Parameters:

Name Type Description Default
observed_values ndarray

Actual observations time series.

required
predicted_values ndarray

Estimated/predicted time series.

required
normalized bool

Whether to normalize RMSE to a percentage of observed_values. Defaults to True.

True

Returns:

Type Description
float

The calculated RMSE value.

Example

observed = np.array([1, 2, 3]) predicted = np.array([1.1, 2.2, 2.9]) RasUtils.calculate_rmse(observed, predicted) 0.06396394

check_file_access staticmethod

Python
check_file_access(file_path: Path, mode: str = 'r') -> None

Check if the file can be accessed with the specified mode.

Parameters: file_path (Path): Path to the file mode (str): Mode to check ('r' for read, 'w' for write, etc.)

Raises: FileNotFoundError: If the file does not exist PermissionError: If the required permissions are not met

clone_file staticmethod

Python
clone_file(template_path: Path, new_path: Path, update_function: Optional[Callable] = None, *args) -> None

Generic method to clone a file and optionally update it.

Parameters: template_path (Path): Path to the template file new_path (Path): Path where the new file will be created update_function (Optional[Callable]): Function to update the cloned file *args: Additional arguments to pass to the update_function

Raises: FileNotFoundError: If the template file doesn't exist

Example:

def update_content(lines, new_value): ... lines[0] = f"New value: {new_value}\n" ... return lines RasUtils.clone_file(Path("template.txt"), Path("new.txt"), update_content, "Hello")

consolidate_dataframe staticmethod

Python
consolidate_dataframe(dataframe: DataFrame, group_by: Optional[Union[str, List[str]]] = None, pivot_columns: Optional[Union[str, List[str]]] = None, level: Optional[int] = None, n_dimensional: bool = False, aggregation_method: Union[str, Callable] = 'list') -> pd.DataFrame

Consolidate rows in a DataFrame by merging duplicate values into lists or using a specified aggregation function.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to consolidate.

required
group_by Optional[Union[str, List[str]]]

Columns or indices to group by.

None
pivot_columns Optional[Union[str, List[str]]]

Columns to pivot.

None
level Optional[int]

Level of multi-index to group by.

None
n_dimensional bool

If True, use a pivot table for N-Dimensional consolidation.

False
aggregation_method Union[str, Callable]

Aggregation method, e.g., 'list' to aggregate into lists.

'list'

Returns:

Type Description
DataFrame

The consolidated DataFrame.

Example

df = pd.DataFrame({'A': [1, 1, 2], 'B': [4, 5, 6], 'C': [7, 8, 9]}) result = RasUtils.consolidate_dataframe(df, group_by='A') print(result) B C A
1 [4, 5] [7, 8] 2 [6] [9]

convert_to_dataframe staticmethod

Python
convert_to_dataframe(data_source: Union[DataFrame, Path], **kwargs: Any) -> pd.DataFrame

Converts input to a pandas DataFrame. Supports existing DataFrames or file paths (CSV, Excel, TSV, Parquet).

Parameters:

Name Type Description Default
data_source Union[DataFrame, Path]

The input to convert to a DataFrame. Can be a file path or an existing DataFrame.

required
**kwargs Any

Additional keyword arguments to pass to pandas read functions.

{}

Returns:

Type Description
DataFrame

The resulting DataFrame.

Raises:

Type Description
NotImplementedError

If the file type is unsupported or input type is invalid.

Example

df = RasUtils.convert_to_dataframe(Path("data.csv")) print(type(df)) <class 'pandas.core.frame.DataFrame'>

create_directory staticmethod

Python
create_directory(directory_path: Path, ras_object=None) -> Path

Ensure that a directory exists, creating it if necessary.

Parameters: directory_path (Path): Path to the directory ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Returns: Path: Path to the ensured directory

Example:

ensured_dir = RasUtils.create_directory(Path("output")) print(f"Directory ensured: {ensured_dir}")

decode_byte_strings staticmethod

Python
decode_byte_strings(dataframe: DataFrame) -> pd.DataFrame

Decodes byte strings in a DataFrame to regular string objects.

This function converts columns with byte-encoded strings (e.g., b'string') into UTF-8 decoded strings.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame containing byte-encoded string columns.

required

Returns:

Type Description
DataFrame

The DataFrame with byte strings decoded to regular strings.

Example

df = pd.DataFrame({'A': [b'hello', b'world'], 'B': [1, 2]}) decoded_df = RasUtils.decode_byte_strings(df) print(decoded_df) A B 0 hello 1 1 world 2

discover_ras_versions staticmethod

Python
discover_ras_versions() -> Dict[str, Path]

Discover installed HEC-RAS versions by scanning Windows Registry, filesystem, and Wine prefixes (on Linux).

Resolution order: 1. Windows Registry (HKLM, WOW6432Node, HKCU) -- Windows only 2. Standard filesystem paths (Program Files) -- Windows only 3. Native Linux installs (/opt/hecras/, /opt/HEC-RAS/, ~/hecras/, or $RAS_COMMANDER_LINUX_RAS_ROOT) -- Linux only 4. Wine prefix paths (~/.wine, /opt/hecras-wine, etc.) -- Linux only

Returns:

Type Description
Dict[str, Path]

Mapping of version string -> Path to the executable.

Dict[str, Path]

On Windows/Wine this is Ras.exe; for native Linux installs there

Dict[str, Path]

is no Ras.exe, so it maps to the RasUnsteady solver binary (use

Dict[str, Path]

.parent as ras_exe_dir for RasCmdr.compute_plan_linux).

Example

{"6.6": Path("C:/Program Files (x86)/HEC/HEC-RAS/6.6/Ras.exe")}

dos2unix staticmethod

Python
dos2unix(project_dir: Union[str, Path], extensions: Optional[List[str]] = None) -> int

Convert CRLF line endings to LF in HEC-RAS text files.

Processes .b## and .g## files by default (boundary and geometry text files that need LF endings for Linux HEC-RAS execution). Done in-place using pure Python (no shell dependency).

Attribution: Implementation pattern derived from ras-agent (https://github.com/gheistand/ras-agent) by Glenn Heistand / CHAMP — Illinois State Water Survey. See runner.py:_dos2unix_dir().

Parameters:

Name Type Description Default
project_dir Union[str, Path]

Path to the HEC-RAS project directory.

required
extensions Optional[List[str]]

Custom regex patterns for file extensions to process. Defaults to [r'.(b|g)\d+$'] which matches .b01, .g01, etc.

None

Returns:

Type Description
int

Number of files modified.

Example

from ras_commander import RasUtils count = RasUtils.dos2unix(Path("/project/dir")) print(f"Converted {count} files")

find_files_by_extension staticmethod

Python
find_files_by_extension(extension: str, ras_object=None) -> list

List all files in the project directory with a specific extension.

Parameters: extension (str): File extension to filter (e.g., '.prj') ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Returns: list: List of file paths matching the extension

Example:

prj_files = RasUtils.find_files_by_extension('.prj') print(f"Found {len(prj_files)} .prj files")

find_nearest_neighbors staticmethod

Python
find_nearest_neighbors(points: ndarray, max_distance: float = 2.0) -> np.ndarray

Creates a self KDTree for dataset points and finds nearest neighbors excluding self, with distances above max_distance set to -1.

Parameters:

Name Type Description Default
points ndarray

The dataset to build the KDTree from and query against itself.

required
max_distance float

The maximum distance threshold. Indices with distances greater than max_distance are set to -1. Defaults to 2.0.

2.0

Returns:

Type Description
ndarray

Array of indices representing the nearest neighbor in points for each point in points. Indices with distances > max_distance or self-matches are set to -1.

Example

points = np.array([[0, 0], [1, 1], [2, 2], [10, 10]]) result = RasUtils.find_nearest_neighbors(points) print(result) array([1, 0, 1, -1])

find_nearest_value staticmethod

Python
find_nearest_value(array: Union[list, ndarray], target_value: Union[int, float]) -> Union[int, float]

Finds the nearest value in a NumPy array to the specified target value.

Parameters:

Name Type Description Default
array Union[list, ndarray]

The array to search within.

required
target_value Union[int, float]

The value to find the nearest neighbor to.

required

Returns:

Type Description
Union[int, float]

The nearest value in the array to the specified target value.

Example

arr = np.array([1, 3, 5, 7, 9]) result = RasUtils.find_nearest_value(arr, 6) print(result) 5

find_valid_ras_folders staticmethod

Python
find_valid_ras_folders(search_path: Union[str, Path], max_depth: Optional[int] = None, return_project_info: bool = False, include_nested_projects: bool = False) -> Union[List[Path], List[Dict[str, Any]]]

Recursively search for valid HEC-RAS project folders.

A valid HEC-RAS project folder contains: 1. A .prj file with "Proj Title=" on the first line (HEC-RAS project file) 2. At least one .pXX file where XX is 01-99 (plan files)

This function does NOT require the global ras object to be initialized, making it suitable for discovery operations before project initialization.

Parameters:

Name Type Description Default
search_path Union[str, Path]

Root directory to search for HEC-RAS projects.

required
max_depth Optional[int]

Maximum folder depth to search. None means unlimited. Depth 0 = search_path only, 1 = immediate subdirectories, etc.

None
return_project_info bool

If True, return list of dicts with folder path, project name, prj file path, and plan count. If False, return list of Paths.

False
include_nested_projects bool

Continue scanning below a valid project folder. Defaults to False for backward compatibility. Enable this for delivered collections that intentionally nest independent projects.

False

Returns:

Type Description
Union[List[Path], List[Dict[str, Any]]]
  • If return_project_info=False: List of Path objects for valid HEC-RAS folders
  • If return_project_info=True: List of dicts with keys:
    • 'folder': Path to the project folder
    • 'project_name': Name extracted from .prj filename
    • 'prj_file': Path to the .prj file
    • 'plan_count': Number of plan files found
    • 'plan_numbers': List of plan numbers (e.g., ['01', '02', '15'])
Example

Find all valid HEC-RAS project folders

folders = RasUtils.find_valid_ras_folders("C:/Projects/Hydrology") for folder in folders: ... print(f"Found project: {folder}")

Get detailed info about each project

projects = RasUtils.find_valid_ras_folders( ... "C:/Projects", ... max_depth=3, ... return_project_info=True ... ) for proj in projects: ... print(f"{proj['project_name']}: {proj['plan_count']} plans")

Note

This function distinguishes HEC-RAS .prj files from ESRI projection files by checking for "Proj Title=" on the first line of the file.

get_file_modification_time staticmethod

Python
get_file_modification_time(file_path: Path, ras_object=None) -> Optional[float]

Get the last modification time of a file.

Parameters: file_path (Path): Path to the file ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Returns: Optional[float]: Last modification time as a timestamp, or None if the file does not exist

Example:

mtime = RasUtils.get_file_modification_time(Path("project.prj")) print(f"Last modified: {mtime}")

get_file_size staticmethod

Python
get_file_size(file_path: Path, ras_object=None) -> Optional[int]

Get the size of a file in bytes.

Parameters: file_path (Path): Path to the file ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Returns: Optional[int]: Size of the file in bytes, or None if the file does not exist

Example:

size = RasUtils.get_file_size(Path("project.prj")) print(f"File size: {size} bytes")

get_next_number staticmethod

Python
get_next_number(existing_numbers: list) -> str

Determine the next available number from a list of existing numbers.

Parameters: existing_numbers (list): List of existing numbers as strings

Returns: str: Next available number as a zero-padded string

Example:

RasUtils.get_next_number(["01", "02", "04"]) "05"

get_plan_path staticmethod

Python
get_plan_path(current_plan_number_or_path: Union[str, Number, Path], ras_object=None) -> Path

Get the path for a plan file with a given plan number or path.

Parameters: current_plan_number_or_path (Union[str, Number, Path]): The plan number (e.g., '01', 1, or 1.0) or full path to the plan file ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Returns: Path: Full path to the plan file

Raises: ValueError: If plan number is not between 1 and 99 TypeError: If input type is invalid FileNotFoundError: If the plan file does not exist

Example:

plan_path = RasUtils.get_plan_path(1) print(f"Plan file path: {plan_path}") plan_path = RasUtils.get_plan_path("01") print(f"Plan file path: {plan_path}") plan_path = RasUtils.get_plan_path("path/to/plan.p01") print(f"Plan file path: {plan_path}")

horizontal_distance staticmethod

Python
horizontal_distance(coord1: ndarray, coord2: ndarray) -> float

Calculate the horizontal distance between two coordinate points.

Parameters:

Name Type Description Default
coord1 ndarray

First coordinate point [X, Y].

required
coord2 ndarray

Second coordinate point [X, Y].

required

Returns:

Type Description
float

Horizontal distance.

Example

distance = RasUtils.horizontal_distance(np.array([0, 0]), np.array([3, 4])) print(distance) 5.0

ignore_windows_reserved staticmethod

Python
ignore_windows_reserved(directory: str | Path, contents: list[str]) -> set[str]

Ignore function for shutil.copytree that skips Windows reserved device names.

Windows lists virtual device names (NUL, CON, PRN, etc.) in directory listings even though they are not real files. shutil.copytree fails when it tries to copy them. This function filters them out.

Parameters:

Name Type Description Default
directory str | Path

The directory being copied (provided by copytree)

required
contents list[str]

List of names in the directory (provided by copytree)

required

Returns:

Type Description
set

Names to ignore (Windows reserved device names)

is_valid_ras_folder staticmethod

Python
is_valid_ras_folder(folder_path: Union[str, Path]) -> bool

Check if a single folder is a valid HEC-RAS project folder.

A valid HEC-RAS project folder contains: 1. A .prj file with "Proj Title=" on the first line 2. At least one .pXX file where XX is 01-99

This function does NOT require the global ras object to be initialized.

Parameters:

Name Type Description Default
folder_path Union[str, Path]

Path to the folder to check.

required

Returns:

Type Description
bool

True if the folder is a valid HEC-RAS project folder.

Example

if RasUtils.is_valid_ras_folder("C:/Projects/MyRASModel"): ... print("This is a valid HEC-RAS project folder") ... else: ... print("Not a valid HEC-RAS project folder")

is_windows_reserved_name staticmethod

Python
is_windows_reserved_name(name: str) -> bool

Check if a filename is a Windows reserved device name.

Parameters:

Name Type Description Default
name str

Filename to check

required

Returns:

Type Description
bool

True if the name is a reserved device name

normalize_ras_number staticmethod

Python
normalize_ras_number(ras_number: Union[str, int, float, Path, Number]) -> str

Normalize RAS file numbers to two-digit string format.

HEC-RAS uses two-digit file extensions for plans (.p01), geometries (.g02), flows (.f03), etc. This function standardizes various input formats to ensure consistent file path construction.

ras_number (Union[str, int, float, Path, Number]): Input number in various formats: - int: 1, 2, 3, etc. - str: "1", "01", "001", "p01", ".p01", "project.p01", etc. - float: 1.0, 2.0 (must be whole numbers) - Path: Path("project.p05") - extracts number from extension - Number: numpy.int64(1), etc.

Returns: str: Normalized two-digit format ("01", "02", ..., "99")

Raises: ValueError: If the number is not between 1 and 99, or cannot be converted TypeError: If the input type is invalid

Examples:

RasUtils.normalize_ras_number(1) '01' RasUtils.normalize_ras_number("1") '01' RasUtils.normalize_ras_number("01") '01' RasUtils.normalize_ras_number("001") '01' RasUtils.normalize_ras_number("p01") '01' RasUtils.normalize_ras_number(np.int64(5)) '05' RasUtils.normalize_ras_number(Path("project.p02")) '02'

Notes: - Used for plan numbers, geometry numbers, flow file numbers, etc. - Ensures consistent handling across all RAS file types - Prevents file path construction errors from unnormalized inputs

perform_kdtree_query staticmethod

Python
perform_kdtree_query(reference_points: ndarray, query_points: ndarray, max_distance: float = 2.0) -> np.ndarray

Performs a KDTree query between two datasets and returns indices with distances exceeding max_distance set to -1.

Parameters:

Name Type Description Default
reference_points ndarray

The reference dataset for KDTree.

required
query_points ndarray

The query dataset to search against KDTree of reference_points.

required
max_distance float

The maximum distance threshold. Indices with distances greater than this are set to -1. Defaults to 2.0.

2.0

Returns:

Type Description
ndarray

Array of indices from reference_points that are nearest to each point in query_points. Indices with distances > max_distance are set to -1.

Example

ref_points = np.array([[0, 0], [1, 1], [2, 2]]) query_points = np.array([[0.5, 0.5], [3, 3]]) result = RasUtils.perform_kdtree_query(ref_points, query_points) print(result) array([ 0, -1])

remove_prj_entry staticmethod

Python
remove_prj_entry(prj_file: Path, file_type: str, number: str, ras_object=None) -> None

Remove a file entry from the .prj file.

Parameters: prj_file (Path): Path to the project file file_type (str): Type of file entry ('Plan', 'Geom', 'Unsteady', or 'Flow') number (str): Two-digit number of the entry to remove (e.g., '05') ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Example:

RasUtils.remove_prj_entry(Path("project.prj"), "Plan", "05")

Removes the line "Plan File=p05" from the .prj file

remove_with_retry staticmethod

Python
remove_with_retry(path: Path, max_attempts: int = 5, initial_delay: float = 1.0, is_folder: bool = True, ras_object=None) -> bool

Attempts to remove a file or folder with retry logic and exponential backoff.

Parameters: path (Path): Path to the file or folder to be removed. max_attempts (int): Maximum number of removal attempts. initial_delay (float): Initial delay between attempts in seconds. is_folder (bool): If True, the path is treated as a folder; if False, it's treated as a file. ras_object (RasPrj, optional): Accepted for backward compatibility. The cleanup does not require an initialized RAS project, so it can be used before project extraction or during worker-folder cleanup.

Returns: bool: True if the file or folder was successfully removed, False otherwise.

Example:

success = RasUtils.remove_with_retry(Path("temp_folder"), is_folder=True) print(f"Removal successful: {success}")

rename_prj_entry staticmethod

Python
rename_prj_entry(prj_file: Path, file_type: str, old_number: str, new_number: str, ras_object=None) -> None

Rename a file entry in the .prj file.

Parameters: prj_file (Path): Path to the project file file_type (str): Type of file entry ('Plan', 'Geom', 'Unsteady', or 'Flow') old_number (str): Current two-digit number (e.g., '05') new_number (str): New two-digit number (e.g., '02') ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Example:

RasUtils.rename_prj_entry(Path("project.prj"), "Plan", "05", "02")

Changes "Plan File=p05" to "Plan File=p02" in the .prj file

rollback_geometry staticmethod

Python
rollback_geometry(geom_file: Union[str, Path], backup_path: Union[str, Path]) -> None

Restore geometry file from backup after failed modification.

This function restores a geometry file from a previously created backup, typically used when a modification operation fails or produces incorrect results.

Process
  1. Verify backup file exists
  2. Copy backup -> original (preserves backup for safety)
  3. Log restoration

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to the geometry file to restore.

required
backup_path Union[str, Path]

Path to the backup file created by safe_write_geometry().

required

Returns:

Type Description
None

None

Raises:

Type Description
FileNotFoundError

If backup file doesn't exist.

PermissionError

If write access is denied.

IOError

If copy operation fails.

Example

from ras_commander import RasUtils from pathlib import Path

Attempt modification

try: ... backup = RasUtils.safe_write_geometry(geom_file, modified_lines) ... # Run HEC-RAS to validate ... RasCmdr.compute_plan("01", clear_geompre=True) ... except Exception as e: ... # Modification failed - rollback ... if backup: ... RasUtils.rollback_geometry(geom_file, backup) ... print("Geometry file restored from backup") ... raise

Notes
  • This function copies the backup to original, preserving the backup.
  • Use shutil.copy2() to preserve file metadata (timestamps, permissions).
  • After successful rollback, you may want to delete the backup manually if no longer needed.
See Also
  • safe_write_geometry: Create backup and safely write modifications

safe_resolve staticmethod

Python
safe_resolve(path: Path) -> Path

Resolve path while preserving Windows drive letters.

On Windows with mapped network drives, Path.resolve() converts drive letters (H:) to UNC paths (\server\share). HEC-RAS cannot read from UNC paths, so we preserve the drive letter format.

This function: - On non-Windows: Uses standard resolve() - On Windows with local drives: Uses standard resolve() - On Windows with mapped drives: Falls back to absolute() to preserve drive letter

Parameters:

Name Type Description Default
path Path

Path to resolve

required

Returns:

Type Description
Path

Resolved path with drive letter preserved if applicable

Example

from pathlib import Path from ras_commander import RasUtils

Local drive - normal resolution

resolved = RasUtils.safe_resolve(Path("C:/Projects/Model.prj"))

Mapped drive - preserves H: instead of converting to UNC

resolved = RasUtils.safe_resolve(Path("H:/Projects/Model.prj"))

safe_write_geometry staticmethod

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

Atomically write geometry file with backup for safe file modification.

This function implements safe file modification for HEC-RAS geometry files, ensuring data integrity through atomic operations and optional backup creation.

Process
  1. Create timestamped backup: geom_file.YYYYMMDD_HHMMSS.bak
  2. Write to temp file: geom_file.tmp
  3. Basic validation (line count reasonable, file size reasonable)
  4. Atomic rename temp -> original (os.replace)
  5. Return backup path

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to the geometry file to write.

required
modified_lines List[str]

List of lines to write to the file. Each line should include newline characters if needed.

required
create_backup bool

If True, create timestamped backup before modification. Defaults to True for safety.

True

Returns:

Type Description
Optional[Path]

Path to backup file if create_backup=True and successful, None if create_backup=False or file didn't exist before.

Raises:

Type Description
FileNotFoundError

If the geometry file doesn't exist (for modification).

PermissionError

If write access is denied to the file or directory.

ValueError

If modified_lines is empty or validation fails.

IOError

If atomic rename fails.

Example

from ras_commander import RasUtils from pathlib import Path

Read geometry file

geom_file = Path("project/geometry.g01") with open(geom_file, 'r') as f: ... lines = f.readlines()

Modify HTAB parameters (example)

modified_lines = modify_htab_params(lines, starting_el=580.0)

Safe write with backup

backup_path = RasUtils.safe_write_geometry(geom_file, modified_lines) print(f"Backup created at: {backup_path}")

Notes
  • This function uses os.replace() for atomic rename, which is atomic on both Windows (NTFS) and Unix filesystems.
  • Backup files use format: filename.YYYYMMDD_HHMMSS.bak
  • If validation fails, temp file is deleted and original remains unchanged.
  • For rollback, use rollback_geometry() with the returned backup path.
See Also
  • rollback_geometry: Restore from backup after failed modification
  • .claude/rules/python/path-handling.md: Path handling patterns

save_to_excel staticmethod

Python
save_to_excel(dataframe: DataFrame, excel_path: Path, **kwargs: Any) -> None

Saves a pandas DataFrame to an Excel file with retry functionality.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to save.

required
excel_path Path

The path to the Excel file where the DataFrame will be saved.

required
**kwargs Any

Additional keyword arguments passed to DataFrame.to_excel().

{}

Raises:

Type Description
IOError

If the file cannot be saved after multiple attempts.

Example

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) RasUtils.save_to_excel(df, Path('output.xlsx'))

update_file staticmethod

Python
update_file(file_path: Path, update_function: Callable, *args) -> None

Generic method to update a file.

Parameters: file_path (Path): Path to the file to be updated update_function (Callable): Function to update the file contents *args: Additional arguments to pass to the update_function

Raises: Exception: If there's an error updating the file

Example:

def update_content(lines, new_value): ... lines[0] = f"New value: {new_value}\n" ... return lines RasUtils.update_file(Path("example.txt"), update_content, "Hello")

update_plan_file staticmethod

Python
update_plan_file(plan_number_or_path: Union[str, Path], file_type: str, entry_number: int, ras_object=None) -> None

Update a plan file with a new file reference.

Parameters: plan_number_or_path (Union[str, Path]): The plan number (1 to 99) or full path to the plan file file_type (str): Type of file to update ('Geom', 'Flow', or 'Unsteady') entry_number (int): Number (from 1 to 99) to set ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Raises: ValueError: If an invalid file_type is provided FileNotFoundError: If the plan file doesn't exist

Example:

RasUtils.update_plan_file(1, "Geom", 2) RasUtils.update_plan_file("path/to/plan.p01", "Geom", 2)

update_project_file staticmethod

Python
update_project_file(prj_file: Path, file_type: str, new_num: str, ras_object=None) -> None

Update the project file with a new entry.

Parameters: prj_file (Path): Path to the project file file_type (str): Type of file being added (e.g., 'Plan', 'Geom') new_num (str): Number of the new file entry ras_object (RasPrj, optional): RAS object to use. If None, uses the default ras object.

Example:

RasUtils.update_project_file(Path("project.prj"), "Plan", "02")

validate_geometry_file_basic staticmethod

Python
validate_geometry_file_basic(geom_file: Union[str, Path], min_lines: int = 10, required_patterns: Optional[List[str]] = None) -> bool

Perform basic validation on a geometry file.

This function checks that a geometry file meets basic structural requirements, useful for pre-modification validation or post-write verification.

Parameters:

Name Type Description Default
geom_file Union[str, Path]

Path to the geometry file to validate.

required
min_lines int

Minimum number of lines expected. Defaults to 10.

10
required_patterns Optional[List[str]]

List of strings that must appear somewhere in the file. Defaults to ["River Reach="] for HEC-RAS geometry.

None

Returns:

Type Description
bool

True if validation passes, False otherwise.

Example

if RasUtils.validate_geometry_file_basic(geom_file): ... print("Geometry file appears valid")

Custom validation

if RasUtils.validate_geometry_file_basic( ... geom_file, ... required_patterns=["River Reach=", "Type RM Length"] ... ): ... print("Geometry file has cross sections")

Notes
  • This is a basic structural check, not a full HEC-RAS validation.
  • For comprehensive validation, use HEC-RAS geometric preprocessor.

Method Categories

File Operations
Method Description
create_directory(path) Ensure directory exists, create if needed
find_files_by_extension(folder, ext) Find all files with given extension
get_file_size(path) Get file size in bytes
get_file_modification_time(path) Get file modification timestamp
clone_file(src, dest) Copy file to new location
update_file(path, content) Write content to file
remove_with_retry(path, retries=3) Delete file with retry logic
check_file_access(path, mode) Verify file access permissions
Plan/Project Helpers
Method Description
normalize_ras_number(number) Convert "1", "01", "p01" to "01" format
get_plan_path(plan_number) Get full path to plan file
get_next_number(folder, prefix) Find next available plan/geom number
update_plan_file(path, key, value) Update single key in plan file
update_project_file(prj_path, updates) Batch update .prj file
Data Conversion
Method Description
convert_to_dataframe(path) Load CSV/Excel to DataFrame
save_to_excel(df, path, sheet) Save DataFrame to Excel
decode_byte_strings(data) Decode HDF byte strings to Python strings
consolidate_dataframe(df, group_by) Group and aggregate DataFrame rows
Statistical Analysis
Method Description
calculate_rmse(observed, predicted) Root Mean Square Error
calculate_percent_bias(obs, pred) Percent bias metric
calculate_error_metrics(obs, pred) All metrics (RMSE, NSE, PBIAS, R²)
Python
from ras_commander import RasUtils
import numpy as np

observed = np.array([100, 120, 140, 160, 180])
predicted = np.array([105, 125, 135, 165, 175])

metrics = RasUtils.calculate_error_metrics(observed, predicted)
print(f"RMSE: {metrics['rmse']:.2f}")
print(f"NSE: {metrics['nse']:.3f}")
print(f"PBIAS: {metrics['pbias']:.1f}%")
Spatial Operations
Method Description
perform_kdtree_query(points, query, max_dist) Find nearest points using KDTree
find_nearest_neighbors(points, max_dist) Find nearest neighbor for each point
find_nearest_value(array, target) Find value closest to target
horizontal_distance(p1, p2) Calculate 2D distance between points
Python
from ras_commander import RasUtils
import numpy as np

# Find nearest mesh cell for a list of query points
mesh_centroids = np.array([[0, 0], [10, 10], [20, 20]])
query_points = np.array([[5, 5], [15, 15]])

indices = RasUtils.perform_kdtree_query(
    mesh_centroids,
    query_points,
    max_distance=10.0
)
# Returns [1, 2] - nearest cell indices

RasExamples

A class for quickly loading HEC-RAS example projects for testing and development of ras-commander. All methods are class methods, so no initialization is required.

Storage Locations: - ZIP files and CSV cache: User data directory (writable without admin) - Windows: %LOCALAPPDATA%/ras-commander/examples - macOS: ~/Library/Application Support/ras-commander/examples - Linux: ~/.local/share/ras-commander/examples - Extracted projects: Current working directory / example_projects (or output_path)

This design ensures RasExamples works in system-wide conda environments without requiring administrator privileges.

clean_projects_directory classmethod

Python
clean_projects_directory()

Remove all extracted projects from the example_projects directory.

download_fema_ble_model classmethod

Python
download_fema_ble_model(huc8, output_dir=None)

Download a FEMA Base Level Engineering (BLE) model for a given HUC8.

Parameters:

Name Type Description Default
huc8 str

The 8-digit Hydrologic Unit Code (HUC) for the desired watershed.

required
output_dir str

The directory to save the downloaded files. If None, uses the current working directory.

None

Returns:

Type Description
str

The path to the downloaded and extracted model directory.

Note

This method downloads the BLE model from the FEMA website and extracts it to the specified directory.

download_sciencebase_model classmethod

Python
download_sciencebase_model(model_key: str, output_path: Union[str, Path] = None, required_only: bool = False, extract: bool = True, show_progress: bool = False, signed_download_urls: Optional[dict[str, str]] = None) -> Path

Download a reviewed ScienceBase archive through RasExamples.

Archives are stored below output_path/<model-slug>. If output_path is omitted, :attr:projects_dir is used. ScienceBase routes some large S3-backed archives through a public browser CAPTCHA; no ScienceBase account is required. For those entries this method raises an ScienceBaseInteractiveDownloadRequired message containing the official CAPTCHA page and exact placement path unless a temporary URL is supplied through signed_download_urls.

Parameters:

Name Type Description Default
model_key str

Registry slug, common alias, or DOI suffix.

required
output_path Union[str, Path]

Parent directory for the downloaded model folder.

None
required_only bool

Skip optional metadata and result products.

False
extract bool

Extract ZIP archives after download.

True
show_progress bool

Display download progress when true.

False
signed_download_urls Optional[dict[str, str]]

Optional mapping of attachment filename to a temporary URL issued by ScienceBase after its public CAPTCHA.

None

Returns:

Type Description
Path

Path to the ScienceBase model directory.

extract_project classmethod

Python
extract_project(project_names: Union[str, List[str]], output_path: Union[str, Path] = None, suffix: Optional[str] = None) -> Union[Path, List[Path]]

Extract one or more specific HEC-RAS projects from the zip file.

Parameters:

Name Type Description Default
project_names Union[str, List[str]]

Single project name as string or list of project names

required
output_path Union[str, Path]

Optional path where the project folder will be placed. Can be a relative path (creates subfolder in current directory) or an absolute path. If None, uses default 'example_projects' folder.

None
suffix Optional[str]

Optional suffix to append to folder name using format "{project_name}_{suffix}". If None (default), uses original project name. Useful for extracting the same project multiple times with different configurations. Suffix is sanitized to remove special characters. Example: suffix="aep_30yr" with project "Davis" → "Davis_aep_30yr"

None

Returns:

Type Description
Path

Single Path object if one project extracted

List[Path]

List of Path objects if multiple projects extracted

get_example_projects classmethod

Python
get_example_projects(version_number='7.0')

Download and extract HEC-RAS example projects for a specified version.

Downloads the ZIP file to the user data directory, which is writable without administrator privileges: - Windows: %LOCALAPPDATA%/ras-commander/examples - macOS: ~/Library/Application Support/ras-commander/examples - Linux: ~/.local/share/ras-commander/examples

Parameters:

Name Type Description Default
version_number str

HEC-RAS version (default: '7.0')

'7.0'

Returns:

Type Description
Path

Directory where projects will be extracted

get_sciencebase_model_info classmethod

Python
get_sciencebase_model_info(model_key: str) -> dict

Return registry metadata for a ScienceBase model slug or alias.

inspect_sciencebase_model classmethod

Python
inspect_sciencebase_model(model_key: str, base_dir: Union[str, Path], *, project_file: Union[str, Path, None] = None, ras_version: Optional[str] = None) -> dict

Inspect a local ScienceBase candidate before promotion.

is_project_extracted classmethod

Python
is_project_extracted(project_name)

Check if a specific project is already extracted.

list_categories classmethod

Python
list_categories()

List all categories of example projects.

list_projects classmethod

Python
list_projects(category=None)

List all projects or projects in a specific category.

Note: Special projects are also available but not listed in categories as they are downloaded separately.

list_sciencebase_models classmethod

Python
list_sciencebase_models()

List validated HEC-RAS archives in the ScienceBase catalog.

This catalog is intentionally separate from :meth:list_projects. It returns archives explicitly promoted as runnable after portable-path inspection. Promotion normally follows a fresh verified compute; any curator-accepted exception retains its incomplete-compute evidence in the returned metadata. Candidate and rejected releases remain available only through the lower-level curator API.

Returns:

Type Description
list[ModelMetadata]

Records from the reviewed ScienceBase registry. No network request or large download is performed.

organize_ebfe_model classmethod

Python
organize_ebfe_model(model_key: str, output_path: Union[str, Path, None] = None, *, downloaded_folder: Union[str, Path, None] = None, **kwargs) -> Path

Organize a public FEMA eBFE/BLE delivery through its source adapter.

This convenience method is deliberately separate from :meth:extract_project: extract_project remains limited to the official HEC example release archive. output_path is the parent directory; the eBFE registry selects the model-specific output name.

validate_sciencebase_model classmethod

Python
validate_sciencebase_model(model_key: str, base_dir: Union[str, Path], plan_number: str, output_dir: Union[str, Path], *, project_file: Union[str, Path, None] = None, ras_version: Optional[str] = None, num_cores: int = 4) -> dict

Run a fresh verified plan and return its promotion report.

RasMap

See the RASMapper API section for the complete task-grouped reference for display, classification authoring, and geometry completion. Meshing, Results Queries, and Stored Maps have dedicated reference pages.

Full method reference: RasMap.

RASMapper Layer Discovery

The layer-list methods read the .rasmap file and return one dataframe row per layer. Use these when a workflow needs discoverable layer names and resolved paths instead of the compact, list-valued ras.rasmap_df project summary.

Python
from ras_commander import RasMap

terrain_layers = RasMap.list_terrain_layers(project_path)
terrain_display = RasMap.list_terrain_display_settings(project_path)
landcover_layers = RasMap.list_landcover_layers(project_path)
soils_layers = RasMap.list_soils_layers(project_path)
infiltration_layers = RasMap.list_infiltration_layers(project_path)

list_land_classification_layers() is the broad parser for RASMapper Type="LandCoverLayer" entries. The land-cover, soils, and infiltration methods are filtered convenience wrappers around that catalog.

Classification Polygon Overrides

RasMap.list_land_classification_polygons() provides read-only extraction for land-classification sidecars. For HEC-RAS 6.x and 7.0.x LC Type=LandCover sidecars, add_land_classification_polygon(), update_land_classification_polygon(), and delete_land_classification_polygon() persist one polygon through the native RASMapper feature-layer API. The selected class must already exist; these methods do not remap raster classifications or create/remove classes.

Polygon input must contain one effective polygon. A one-member MultiPolygon is normalized, while true multipart input and interior rings are rejected before mutation. HEC-RAS 6.0 through 7.0.1 persists native polygon holes but its land-cover classification resampler flattens them; accepting them would therefore misrepresent their hydraulic effect. Model an exclusion by splitting the intended coverage into explicit, non-overlapping hole-free polygons. GeoPandas inputs must use the sidecar CRS; raw Shapely and GeoJSON coordinates are assumed to already use that CRS. Every supported mutation creates a durable backup, saves through RASMapper, and validates a fresh reload.

HEC-RAS 5.x, soils/infiltration polygon mutation, and remove_unused_class=True fail with migration guidance. Geometry Manning regions remain the supported 5.x override route, while soils and infiltration sidecars should be rebuilt through their native authoring APIs when their classification structure changes.

This is separate from polygon inputs accepted by restrict_to_extent: those inputs define a single buffered processing extent and remain supported.

Terrain Display Settings

RasMap.list_terrain_display_settings(), RasMap.get_terrain_display_settings(), and RasMap.set_terrain_display_settings() expose RASMapper terrain display controls persisted in .rasmap XML. They cover hillshade display and Z factor, contour display and interval, and terrain stitch-edge plot options such as Plot stitch TIN edges.

Python
RasMap.set_terrain_display_settings(
    project_path,
    terrain_name="TerrainWithChannel",
    hillshade_enabled=True,
    hillshade_z_factor=2.0,
    contour_enabled=True,
    contour_interval=5.0,
    stitch_edges_enabled=True,
)

CLB-272 owns these terrain display toggles. CLB-253 remains the separate terrain-modification gap for generating terrain changes such as channel modifications and interpolated cross-section terrain products.

Geometry HDF Layer Associations

RasMap.get_hdf_geometry_association() reads /Geometry association attributes from geometry HDFs and plan/result HDFs without mutation. RasMap.associate_geometry_layers() delegates association changes to the selected HEC-RAS generation's native geometry-association API and validates the native readback.

Python
association = RasMap.get_hdf_geometry_association("MyModel.g01.hdf")
print(association["terrain_hdf_path"])

RasMap.associate_geometry_layers(
    project_path,
    "MyModel.g01.hdf",
    terrain_hdf_path="Terrain/ExistingTerrain.hdf",
    landcover_hdf_path="Land Classification/LandCover.hdf",
    infiltration_hdf_path="Land Classification/Infiltration.hdf",
)

Compiled HDF only

associate_geometry_layers() updates an existing .g##.hdf through HEC-RAS. It does not compile plain-text .g## geometry into HDF or create missing geometry datasets.

To exclude infiltration from a derived child, call RasMap.clear_geometry_infiltration("Child.g02.hdf") on a cloned geometry. It removes only the compiled geometry's infiltration filename, layer name, and file-date attributes, verifies the association is absent, and returns the resolved Path. It accepts str or Path, is idempotent, and rejects filenames other than .gNN.hdf before opening them. Terrain, land-cover, and other attributes are preserved. Existing infiltration property tables remain stale; rebuild native geometry/property tables before using the child. The method requires a directly linked /Geometry group owned by the supplied HDF; external links, soft links, and non-group objects are rejected before writable access. It writes a byte-exact backup in the same directory and flushes it before editing the original in place. It verifies all three attributes are absent and validates the association reader's result. On deletion, validation, or final-flush failure, it truncates and writes the backup bytes into the same original file, then flushes and synchronizes that file before removing the backup. Success also removes the backup. The original file object is never replaced or renamed: its ACL/security descriptor, owner, mode, hard-link count, and identity are preserved on success and rollback. An absent association leaves the file byte-identical. The directory must allow backup creation and removal; the original must be writable. Windows backups receive the source access-control entries before content is copied, without additional inherited grants; POSIX backups are restricted to the current user. On POSIX, writes can clear set-ID mode bits; the method reapplies them to the original object before its final flush. It refuses before mutation if the current user cannot restore the original set-ID mode.

Use exclusive access while calling this method. Other readers can observe the in-place edit before validation or rollback; concurrent writers are unsupported. This guarantee covers exceptions when restoration I/O succeeds, not process crashes or power loss. A crash between editing and restoration leaves .<stem>-infiltration-backup-<random>.hdf.bak beside the geometry, for example .Child.g02-infiltration-backup-<random>.hdf.bak. For recovery, close HDF users and truncate and copy the backup bytes into the original file, then flush and synchronize it; do not replace or rename over the original. If restoration itself fails, the method retains the backup and reports its path in a RuntimeError. The method does not edit a RAS Mapper file or plan.

RasProcess

See stored maps and geometry completion for the full method reference.

Full method reference: RasProcess.

RasProcess Details

RasProcess.exe CLI

RasProcess.exe is an undocumented command-line interface bundled with HEC-RAS that enables headless automation of RASMapper operations. The RasProcess class wraps this CLI for programmatic access.

Geometry Association Validator

validate_geometry_association_cli() runs the native RasProcess.exe SetGeometryAssociation command and compares the resulting /Geometry attributes against ras-commander's expected HEC-RAS-style attributes.

Python
from ras_commander import RasProcess

result = RasProcess.validate_geometry_association_cli(
    "MyModel.g01.hdf",
    terrain_hdf_path="Terrain/ExistingTerrain.hdf",
    landcover_hdf_path="Land Classification/LandCover.hdf",
    ras_version="7.0",
)

print(result["passed"])
print(result["return_code"])
print(result["mismatches"])

The returned dictionary includes the native command arguments, return code, stdout/stderr, before/after attributes, expected attributes, mismatch list, and passed.

In-place mutation

This method mutates the supplied HDF. It exists as a native reference validator for disposable copies or intentional validation runs. Normal workflows should call RasMap.associate_geometry_layers().

Supported Map Types
Parameter XML Type Display Name Default
wse elevation WSE True
depth depth Depth True
velocity velocity Velocity True
froude froude Froude False
shear_stress Shear Shear Stress False
depth_x_velocity depth and velocity D * V False
depth_x_velocity_sq depth and velocity squared D * V² False
Profile Selection

The profile parameter accepts:

  • "Max" - Maximum values across all timesteps (default)
  • "Min" - Minimum values across all timesteps
  • Specific timestamp string from get_plan_timestamps() (e.g., "10SEP2018 02:30:00")
Basic Usage
Python
from ras_commander import init_ras_project, RasProcess

# Initialize project
init_ras_project("path/to/project", "7.0")

# Generate default maps (WSE, Depth, Velocity)
results = RasProcess.store_maps(
    plan_number="01",
    profile="Max",
    wse=True,
    depth=True,
    velocity=True
)

# Results is a dict: {'wse': [Path(...)], 'depth': [...], ...}
for map_type, files in results.items():
    print(f"{map_type}: {len(files)} file(s)")
Batch Processing
Python
# Generate maps for ALL plans with HDF results
all_results = RasProcess.store_all_maps(
    profile="Max",
    wse=True,
    depth=True,
    velocity=True,
    froude=True
)

for plan_num, files in all_results.items():
    print(f"Plan {plan_num}: {sum(len(f) for f in files.values())} files")
Timestep Maps
Python
# Get available timestamps
timestamps = RasProcess.get_plan_timestamps("01")
print(f"Available: {timestamps[:3]}...")  # ['10SEP2018 00:00:00', ...]

# Generate map for specific time
results = RasProcess.store_maps(
    plan_number="01",
    profile=timestamps[10],  # 10th timestep
    wse=True
)
Steady Profile Batch

RasProcess.store_maps_at_steady_profiles() configures all requested profile products in one .rasmap update and invokes aggregate StoreAllMaps exactly once. profiles=None selects all HDF profiles; exact names and zero-based indexes can be mixed. One inundation boundary for the final selected profile is included by default. Supported profile rasters are wse, depth, velocity, froude, shear_stress, depth_x_velocity, depth_x_velocity_sq, and flow.

Python
frame = RasProcess.store_maps_at_steady_profiles(
    "01",
    profiles=None,
    map_types=("depth",),
    output_path="steady_maps",
)

Rows carry status (generated or missing). When a requested product is missing, generated products are preserved and StoredMapProductsIncompleteError is raised with the full frame in error.frame (raise_on_missing=False returns the frame instead).

Use RasMap.store_all_maps(mode="steady_profiles", ...) when a directly JSON-serializable project summary is preferred.

Georeferencing Fix

RasProcess.exe has a known bug where generated TIFs may lack proper CRS information. Set fix_georef=True (default) to automatically apply the CRS from the project's projection file using rasterio.

Custom Output Path

By default, RasProcess.exe writes to <project_folder>/<Plan ShortID>/. Use the output_path parameter to redirect output to any directory:

Python
# Output to custom location
results = RasProcess.store_maps(
    plan_number="01",
    output_path="C:/Exports/FloodMaps",
    depth=True, wse=True
)
# Files moved to C:/Exports/FloodMaps/ after generation

How output_path Works

The default StoreAllMaps command hardcodes output to <Plan ShortID>/. When output_path is specified, individual StoreMap XML commands are used instead, with an absolute OutputBaseFilename that bypasses the ShortID prefix via C#'s Path.Combine() behavior. Relative paths are resolved against the project folder.

Mapping

Static namespace for optional triangulated and horizontal FIM methods.

All methods are static; do not instantiate.

prepare_one_d_model staticmethod

Python
prepare_one_d_model(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Union[Dict[str, Union[str, int]], Sequence[Union[str, int]]]] = None, allow_unqualified: bool = False, max_working_mib: int = 1024) -> 'FimPreparedOneDModel'

Stage lossless global 1D TIN/normalized M and obstruction receipts.

Diagnostic scope: stored unsteady/explicit steady XS profiles and disjoint storage pools in projected US survey feet. Mixed 2D/pipe geometry, blocked polygons and actual encroachment features remain refused. Native 7.0.1 preparation semantics remain unqualified for general use.

map_one_d_profiles staticmethod

Python
map_one_d_profiles(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Union[Dict[str, Union[str, int]], Sequence[Union[str, int]]]] = None, allow_unqualified: bool = False, bbox: Optional[Sequence[float]] = None, polygon: Any = None, aoi_crs: Any = None, polygon_layer: Optional[str] = None, engine_path: Optional[PathLike] = None, threads: int = 1, max_working_mib: int = 1024, timeout: Optional[float] = None, raise_on_failure: bool = True, final_format: Optional[Dict[str, Any]] = None) -> pd.DataFrame

Map canonical stored 1D surfaces with the clipped diagnostic Rust method.

Use allow_unqualified=True explicitly. Call the prepared model's map_profiles method to reuse preparation. AOIs retain all global geometry and original terrain tile history. threads caps the render and DEFLATE workers an advertising engine may use. final_format has the :meth:map_sloping_profiles contract: the engine writes each Depth/WSE GeoTIFF once, with no Rasterio fallback.

prepare_coupled_model staticmethod

Python
prepare_coupled_model(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Union[Dict[str, Union[str, int]], Sequence[Union[str, int]]]] = None, allow_unqualified: bool = False, max_working_mib: int = 1024, engine_path: Optional[PathLike] = None, threads: int = 1, grid_contract: Optional[str] = None) -> 'FimPreparedCoupledModel'

Prepare receipt-bound global mixed XS/2D inputs for diagnostic mapping.

Explicit allow_unqualified=True is required. Scope is unsteady plain corner sloping Depth/WSE without pipe geometry. Storage areas are staged as level pools when the engine is ras-commander-fast-map 0.18.0 or later; storage areas that physically overlap a 2D flow area, storage with grid_contract and older engines refuse. grid_contract="rasmapper-stored-tile-grid/1" explicitly selects native stored tile sampling and derived delivery framing while retaining the original terrain identity. None retains source-grid delivery.

map_coupled_profiles staticmethod

Python
map_coupled_profiles(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Union[Dict[str, Union[str, int]], Sequence[Union[str, int]]]] = None, allow_unqualified: bool = False, bbox: Optional[Sequence[float]] = None, polygon: Any = None, aoi_crs: Any = None, polygon_layer: Optional[str] = None, engine_path: Optional[PathLike] = None, threads: int = 1, max_working_mib: int = 1024, timeout: Optional[float] = None, raise_on_failure: bool = True, grid_contract: Optional[str] = None) -> pd.DataFrame

Compose actual physical 2D coverage over global stored XS surfaces.

The default qualification gate refuses. AOIs mask final composition; dry and terrain-nodata 2D cells still suppress the XS component. Storage areas compose through coupled schema /2 on Fast-Map 0.18.0+; results remain qualified=False. grid_contract selects the explicit native stored tile layout during path-based preparation. Prepared models inherit their sealed layout and refuse overrides.

prepare_corner_elevations staticmethod

Python
prepare_corner_elevations(hdf_path: PathLike, output_folder: PathLike, *, rasmap_path: PathLike, terrain_name: str, hecras_version: str = '7.0.1') -> dict

Prepare a fresh native corner-ground cache for depth-weighted mapping.

Windows/HEC-RAS 7.0.1 only; uses the exact registered terrain, including its modifications. Copies stored property-table elevations when present, otherwise invokes native terrain corner sampling with obstructions. It does not run hydraulics or modify the source HDF/rasmap. The output folder must be new/empty. Returns cache path, preparation seconds and a provenance receipt. Preparation is explicit and outside mapping clocks. Ordinary Rust mapping never loads HEC-RAS assemblies.

Parameters:

Name Type Description Default
hdf_path PathLike

Computed 2D-only plan HDF.

required
output_folder PathLike

New or empty folder for the cache and receipt.

required
rasmap_path PathLike

Model rasmap containing the registered terrain.

required
terrain_name str

Exact registered terrain layer name.

required
hecras_version str

Qualified native runtime version, currently 7.0.1.

'7.0.1'

Returns:

Type Description
dict

Dictionary containing postprocessing_hdf, receipt_path,

dict

elapsed_seconds, per-mesh operations and source provenance.

Raises:

Type Description
ValueError

Unsupported model, runtime, terrain or input binding.

FileExistsError

Output folder contains existing files.

RuntimeError

Native preparation fails or changes a source input.

map_catalog staticmethod

Python
map_catalog(jobs: Sequence[Dict[str, Any]], output_folder: PathLike, *, threads: int = 4, max_workers: int = 1, strategy: str = 'reuse', max_memory_mib: int = 8192, max_working_mib: int = 2048, max_prepared_mib: int = 1024, memory_headroom_mib: int = 256, max_profiles_per_batch: int = 64, writer_threads: int = 1, max_inflight_profiles: int = 1, window_cache_mib: int = 64, hydraulic_cache_mib: int = 64, validation_cache_mib: int = 8, product_writer: str = 'rasterio', engine_path: Optional[PathLike] = None, timeout: Optional[float] = None, cancel_event: Any = None, raise_on_failure: bool = True, final_format: Optional[Dict[str, Any]] = None) -> pd.DataFrame

Map ordered reach/timestep groups under shared CPU/memory budgets.

Each job is a mapping with job_id, hdf_path, terrain_path, timesteps (saved zero-based indices or "Max"), and polygon or bbox. Optional polygon_layer, aoi_crs and reach_id follow the existing AOI contract. interpolation defaults to "sloping"; "horizontal" selects cell-constant mapping. Sloping jobs also accept render_mode, reduce_shallow_to_horizontal, use_depth_weighted_faces, postprocessing_hdf, corner_elevation_source and invalid_cells. Unknown fields raise.

Cache controls follow :meth:prepare_sloping_model and are shared within each actor's prepared model. final_format (with product_writer="native") has the :meth:map_sloping_profiles contract and applies to every job. product_writer="native" opts into terrio LZW output on engines advertising native_geotiff_outputs; it currently requires sloping jobs. The default is "rasterio". Native compression uses one worker. Output masks and float32 values are unchanged by the writer.

Batch known timesteps per reach. Compatible jobs share prepared inputs and a serialized native session within each bounded selector union. max_profiles_per_batch limits both request occurrences and staged unique selectors per source group; larger lists create additional preparation waves. Requested order and duplicate selectors are retained as separate ordinal output files. Complete hydraulic topology remains available outside the output AOI; no depth postprocessing is added.

threads is the global logical-CPU affinity budget (at most 64). max_workers=1 favors reuse; strategy="reuse" combines compatible source groups, while "parallel" keeps jobs as independent work units. The latter can duplicate model state and should be timed on the caller's workload. Additional workers are opt-in and each owns a CPU partition that also contains its compression work. Memory admission reserves max_working_mib + max_prepared_mib + memory_headroom_mib per worker before launch. The scheduler reduces worker count to fit CPU/memory admission. Each worker's native pool is bounded by its partition; writer_threads must fit that partition. Windows/Linux process affinity is required. Sloping requires an engine advertising persistent sessions; polygons require the global-lattice mask capability. No numerical fallback or engine installation occurs.

Sampled aggregate worker/descendant RSS and private memory trigger an abort when exceeding max_memory_mib; low available host memory also aborts. Admission and sampling are not hard OS memory limits and exclude the caller's existing memory. timeout applies to each native batch. cancel_event accepts an object with is_set(). Cancellation or a failed job stops admission, terminates owned workers/native children, removes uncommitted products and retains acknowledged products/receipts.

output_folder must be new or empty. Returns the declared fim_catalog_manifest DataFrame in original job/timestep order. attrs contain performance, catalog status and the JSON receipt path. Failures raise FimMappingError with that DataFrame as manifest; raise_on_failure=False returns it instead. No HEC-RAS execution is performed. Terrain preparation, velocity, polygonization and supplied WSEL tables remain separate operations.

Parameters:

Name Type Description Default
jobs Sequence[Dict[str, Any]]

Ordered mappings describing model, terrain, AOI and times.

required
output_folder PathLike

New or empty catalog destination (str or Path).

required
threads int

Shared logical-CPU budget for owned worker processes.

4
max_workers int

Upper bound on simultaneous prepared workers.

1
strategy str

Source reuse, or independent parallel job units.

'reuse'
max_memory_mib int

Aggregate planned/sampled worker memory budget.

8192
max_working_mib int

Per-worker native request admission limit.

2048
max_prepared_mib int

Per-worker retained input admission limit.

1024
memory_headroom_mib int

Reserved per-worker overhead and minimum available host memory required while running.

256
max_profiles_per_batch int

Maximum request occurrences and staged unique selectors per preparation wave.

64
writer_threads int

Compression workers within each CPU partition.

1
max_inflight_profiles int

Requested native profile concurrency.

1
engine_path Optional[PathLike]

Optional explicit native mapping executable.

None
timeout Optional[float]

Optional per-native-batch timeout in seconds.

None
cancel_event Any

Optional object exposing is_set().

None
raise_on_failure bool

Raise with partial results, or return them.

True

Returns:

Type Description
DataFrame

Ordered fim_catalog_manifest rows with status,

DataFrame

product paths and catalog performance/receipt attrs.

Raises:

Type Description
ValueError

Invalid controls, job fields or destination.

FimUnsupportedError

Unsupported engine, platform or admission.

FimMappingError

Execution failed or was cancelled; manifest contains acknowledged results when raise_on_failure is True.

prepare_sloping_model staticmethod

Python
prepare_sloping_model(hdf_path: PathLike, terrain_path: PathLike, *, profiles: Optional[Dict[str, Union[str, int]]] = None, wsel_profiles: Optional[DataFrame] = None, invalid_cells: str = 'repair', render_mode: str = 'sloping', reduce_shallow_to_horizontal: bool = False, use_depth_weighted_faces: bool = False, postprocessing_hdf: Optional[PathLike] = None, corner_elevation_source: str = 'auto', engine_path: Optional[PathLike] = None, threads: int = 1, max_working_mib: int = 1024, max_prepared_mib: int = 1024, native_session: bool = True, window_cache_mib: int = 64, hydraulic_cache_mib: int = 64, validation_cache_mib: int = 8, terrain_crs_fnv1a64: Optional[str] = None) -> 'FimPreparedSlopingModel'

Prepare fixed 2D sloping inputs for repeated reach/AOI requests.

profiles maps names to Max or stored timestep indices, as in :meth:map_sloping_profiles. Geometry, spatial index and complete staged mesh/WSE inputs are reused. Repeated selectors share files. Alternatively pass wsel_profiles as documented by :meth:map_sloping_profiles, leaving profiles=None. Values and keys are copied and staged during preparation; later caller edits do not change the prepared profiles. max_prepared_mib also admits the planned caller-vector snapshot. info records its provenance. Rendering options and threads are fixed for the context's lifetime. postprocessing_hdf optionally supplies a prepared native corner cache. corner_elevation_source is auto, geometry or mapping_cache; cache-only use requires the adjacent native preparation receipt. native_session=True retains one serialized native process when the engine advertises persistent sessions (0.9+). It reuses geometry, stencils, terrain blocks and bounded window/plain-weight caches. False, or an older engine, starts a fresh CLI per request. Capable engines share reconstructed timestep state across reaches. No depth cutoff is added. window_cache_mib and hydraulic_cache_mib are retained native cache ceilings (default 64 each; 0 disables), admitted inside the working budget. Configurable windows require multi_window_cache; older engines disable hydraulic caching and record zero. validation_cache_mib (default 8) retains passed checks for identical immutable cell subsets, reserving at most one eighth of the prepared budget. Each cache accepts integer MiB from 0 to 4096.

Use the returned context in a with block or call close(). Changes to HDF, terrain, engine or resolved source-text geometry size/mtime invalidate and close it. Calls are serialized; timestep parallelism is controlled per request with max_inflight_profiles. max_prepared_mib admits estimated retained geometry plus actual staged bytes, independently of the per-request max_working_mib. Persistent requests admit both native cache ceilings, and the prepared budget reserves validation retention. Neither is a hard RSS limit; decoder and preparation allocations are outside retained admission. Numeric profile staging uses native-HDF slabs of at most 8 MiB source values, with a bounded float32 conversion buffer. terrain_crs_fnv1a64 explicitly pins the native reader's WKT identity after independent verification of the original terrain/model CRS. It never reprojects coordinates; the default retains strict CRS matching.

Returns:

Type Description
FimPreparedSlopingModel

Owned inputs with map_profiles,

'FimPreparedSlopingModel'

info, closed and idempotent close. Its mapping method

'FimPreparedSlopingModel'

accepts an optional ordered subset of prepared names, bbox or

'FimPreparedSlopingModel'

polygon, and the ordinary delivery/concurrency controls.

invalid_cells is fixed at preparation and handled as in :meth:map_sloping_profiles; info["invalid_cells"] lists the affected cells. With "raise", preparation succeeds and each request refuses only when its AOI (or the whole mesh, without one) intersects an invalid cell.

terrain_crs_fnv1a64 is also fixed at preparation and validated as in :meth:map_sloping_profiles.

compare_inundation_boundaries staticmethod

Python
compare_inundation_boundaries(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, terrain_hdf: PathLike, profiles: Optional[Dict[str, Union[str, int]]] = None, interpolation: str = 'sloping', native_boundaries: Optional[Dict[str, PathLike]] = None, native_performance: Optional['StoreMapPerformanceOptions'] = None, plan_number: Optional[str] = None, terrain_name: Optional[str] = None, ras_object: Any = None, ras_version: Optional[str] = None, bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, engine_path: Optional[PathLike] = None, threads: int = 1, max_inflight_profiles: int = 1, max_working_mib: int = 1024, max_prepared_mib: int = 1024, timeout: Optional[float] = None, terrain_crs_fnv1a64: Optional[str] = None, method: str = 'deterministic', allow_unqualified: bool = False, preserve_raw_geometry: bool = False) -> 'pd.DataFrame'

Compare selected Rust boundary polygons with native stored polygons.

deterministic compares the 2D contour method. native_serial compares native source/tile/stitch ordering and admitted canonical 2D, cross-section, storage-area or mixed model inputs; it requires allow_unqualified=True. Support does not establish native parity.

Parameters:

Name Type Description Default
hdf_path PathLike

Computed plan HDF admitted by the selected method.

required
terrain_path PathLike

Original single-source TIFF for deterministic; first original TIFF in native terrain order for native_serial.

required
output_folder PathLike

New or empty comparison/evidence folder.

required
terrain_hdf PathLike

Associated original terrain HDF. Native ordering uses every original source's masks/perimeters and one global stitch TIN; no flattening is applied. A modified single-source terrain is read from its stored-map effective terrain.

required
profiles Optional[Dict[str, Union[str, int]]]

Output names mapped to Max or source profile indices, interpreted by canonical model preparation.

None
interpolation str

horizontal or plain corner sloping for 2D. Cross-section surfaces require sloping.

'sloping'
native_boundaries Optional[Dict[str, PathLike]]

Optional profile-to-vector-file references. Retain their runtime, profile, terrain and rendering-policy provenance. When absent, generate references through RasProcess.store_maps.

None
native_performance Optional['StoreMapPerformanceOptions']

Optional native execution policy, including native_polygon_serial=True, required when generating native_serial references. Omit with retained references.

None
plan_number Optional[str]

Plan for native reference generation.

None
terrain_name Optional[str]

Native terrain registration, if selection is needed.

None
ras_object Any

Initialized RasPrj for native generation.

None
ras_version Optional[str]

Native HEC-RAS version for reference generation.

None
bbox Optional[Sequence[float]]

Optional AOI bounds. Both geometries use the same unrounded final GIS intersection; verified native candidate delivery is not clipped a second time.

None
polygon Any

Optional polygon AOI or vector source.

None
polygon_layer Optional[str]

Polygon file layer.

None
aoi_crs Any

AOI CRS. Bounds default to model CRS; a Shapely geometry requires an explicit CRS.

None
engine_path Optional[PathLike]

Explicit Fast-Map executable, if needed.

None
threads int

Shared Rust worker count.

1
max_inflight_profiles int

Bounded Rust timestep concurrency.

1
max_working_mib int

Planned working-array budget.

1024
max_prepared_mib int

Geometry and staging budget.

1024
timeout Optional[float]

Per-engine/native-call timeout in seconds.

None
terrain_crs_fnv1a64 Optional[str]

Optional caller-verified terrain WKT identity.

None
method str

deterministic or explicitly selected native_serial. Native serial describes reference ordering; Rust workers may still run concurrently while preserving that order.

'deterministic'
allow_unqualified bool

Required for native_serial until its declared model/terrain scope is qualified. Defaults to False.

False
preserve_raw_geometry bool

Explicit full-extent native_serial diagnostic opt-in. Finite, closed topology-invalid artifacts are retained unchanged; FimGeometryError carries an aborted diagnostic receipt. No repair or ordinary completed product/comparison is returned on refusal.

False

Returns:

Type Description
'pd.DataFrame'

Full geometry/topology difference metrics and timing receipt.

'pd.DataFrame'

coordinates_equal compares unrounded stored vertices while

'pd.DataFrame'

ignoring ring start, orientation and part order; collinear vertices

'pd.DataFrame'

remain significant. geometry_equal checks topology, while

'pd.DataFrame'

quantized_coordinates_equal is a separate 0.001-unit diagnostic.

'pd.DataFrame'

Ordered original-source identities and hashes remain bound through

'pd.DataFrame'

comparison and are recorded in the candidate manifest and receipt.

'pd.DataFrame'

Native generation, Rust batch mapping and comparison scans have

'pd.DataFrame'

separate clocks in attrs["performance"]. No post-depth filter is

'pd.DataFrame'

applied. Native Max polygons may vary between identical exports.

Raises:

Type Description
FimUnsupportedError

Unsupported CRS, geometry or input scope.

FimGeometryError

Invalid topology; optional raw evidence is diagnostic only.

FimEngineError

Failed native or Rust execution.

ValueError

Invalid controls or reference selection.

map_inundation_boundaries staticmethod

Python
map_inundation_boundaries(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, terrain_hdf: PathLike, profiles: Optional[Dict[str, Union[str, int]]] = None, interpolation: str = 'sloping', bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, engine_path: Optional[PathLike] = None, threads: int = 1, max_inflight_profiles: int = 1, max_working_mib: int = 1024, max_prepared_mib: int = 1024, timeout: Optional[float] = None, terrain_crs_fnv1a64: Optional[str] = None, method: str = 'deterministic', allow_unqualified: bool = False, preserve_raw_geometry: bool = False) -> 'pd.DataFrame'

Generate zero-depth contour polygons using a selected Rust method.

The default 2D method preserves holes with a deterministic NonZero union. native_serial targets native source/tile/stitch ordering for admitted canonical 2D, cross-section, storage-area and mixed model inputs. It requires explicit unqualified opt-in. Compare complete topology and unrounded coordinates before making a native parity claim.

Parameters:

Name Type Description Default
hdf_path PathLike

Computed plan HDF. The deterministic method requires 2D; native_serial admits canonical cross-section/storage/mixed preparation where supported and refuses unsupported variants.

required
terrain_path PathLike

Original unmodified Float32 terrain TIFF. The deterministic method requires a single source. For native ordering, supply the first original source in native terrain order; every source must retain its original 256-pixel tiles and the actual projected model CRS in US survey feet.

required
output_folder PathLike

New or empty product folder.

required
terrain_hdf PathLike

Original associated terrain HDF containing level-zero masks, perimeters and optional global stitch TIN. Native ordering retains every original mosaic source and stages the global TIN once. Complete source priorities determine stable ascending order; otherwise native group order is retained. Unsupported ambiguous ordering refuses. A modified single-source terrain maps on its stored-map effective terrain (build_effective_terrain(..., basis="stored_map")) passed as terrain_path; other terrain modifications refuse.

required
profiles Optional[Dict[str, Union[str, int]]]

Output names mapped to Max or source profile indices, interpreted by canonical model preparation.

None
interpolation str

horizontal or plain corner sloping for 2D. Cross-section surfaces require sloping.

'sloping'
bbox Optional[Sequence[float]]

Optional bounds in aoi_crs. Native ordering retains all source tiles and hydraulic geometry, then clips validated full vectors by an unrounded final GIS intersection.

None
polygon Any

Optional Polygon/MultiPolygon, GeoDataFrame or file path.

None
polygon_layer Optional[str]

Layer name for a polygon file.

None
aoi_crs Any

AOI CRS. Bounds default to model CRS; a Shapely geometry requires an explicit CRS.

None
engine_path Optional[PathLike]

Explicit matching Fast-Map executable, if needed.

None
threads int

Shared native worker count, 1 through 64.

1
max_inflight_profiles int

Bounded timestep concurrency.

1
max_working_mib int

Planned engine allocation budget; not hard RSS.

1024
max_prepared_mib int

Retained geometry/staged-input budget.

1024
timeout Optional[float]

Engine execution timeout in seconds.

None
terrain_crs_fnv1a64 Optional[str]

Optional caller-verified native-reader WKT identity, after checking the original terrain CRS independently.

None
method str

deterministic retains the established 2D contour method. native_serial selects native ordering and supported canonical cross-section/storage composition. Its serial ordering does not require a single Rust worker.

'deterministic'
allow_unqualified bool

Explicit opt-in while native-order model qualification is in progress. Defaults to False.

False
preserve_raw_geometry bool

Explicit full-extent native_serial diagnostic opt-in. Finite, closed topology-invalid artifacts are retained unchanged; FimGeometryError carries an aborted diagnostic receipt. No repair or ordinary completed product/comparison is returned on refusal.

False

Returns:

Type Description
'pd.DataFrame'

Product manifest with GeoJSON paths and polygon statistics.

'pd.DataFrame'

Timing and provenance are in attrs and boundary_manifest.json.

'pd.DataFrame'

Native delivery records ordered original-source SHA256 identities,

'pd.DataFrame'

terrain-source and model preparation receipts, and any exact AOI

'pd.DataFrame'

clipping receipt. Native vector parity remains unqualified until

'pd.DataFrame'

scoped reference comparisons establish it.

Raises:

Type Description
FimUnsupportedError

Unsupported terrain/model or resource limits.

FimGeometryError

Invalid topology; optional raw evidence is diagnostic only.

FimEngineError

Missing capability or unsuccessful mapping.

ValueError

Invalid controls or incompatible AOIs.

map_sloping_profiles staticmethod

Python
map_sloping_profiles(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Dict[str, Union[str, int]]] = None, wsel_profiles: Optional[DataFrame] = None, render_mode: str = 'sloping', reduce_shallow_to_horizontal: bool = False, use_depth_weighted_faces: bool = False, postprocessing_hdf: Optional[PathLike] = None, corner_elevation_source: str = 'auto', bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, engine_path: Optional[PathLike] = None, threads: int = 1, writer_threads: int = 1, product_writer: str = 'rasterio', row_stream_rows: int = 0, final_format: Optional[Dict[str, Any]] = None, max_working_mib: int = 1024, timeout: Optional[float] = None, max_inflight_profiles: int = 1, write_floodplain: bool = False, template_raster: Optional[PathLike] = None, terrain_hdf: Optional[PathLike] = None, velocity: bool = False, invalid_cells: str = 'repair', terrain_crs_fnv1a64: Optional[str] = None, storage_areas: bool = False, velocity_depth: str = 'rendered', derived_products: Sequence[str] = (), shear_stress: bool = False, shear_depth: str = 'rendered') -> pd.DataFrame

Map 2D HDF WSE with the Rust sloping engine.

profiles maps output names to "Max" or zero-based stored timestep indices; omitted selects {"Max": "Max"}. Geometry, terrio ownership and terrain are reused across profiles. threads bounds native reconstruction and pixel workers (1 through 64).

Alternatively supply wsel_profiles and leave profiles=None. This wide DataFrame has mesh_name, integer cell_id, and one real numeric column per named profile. Include every cell of every HDF mesh, including ghost cells, exactly once. Row order is arbitrary; IDs are zero-based HDF cell IDs, local to each exact mesh name. Missing, duplicate, extra or unknown IDs are errors. NaN explicitly means dry and is staged as finite float32 minimum. Other values cast to float32 without aggregation or decimal rounding; infinity and overflow are errors. Finite stored dry sentinels remain unchanged. Values are absolute elevations in the same vertical units and datum as the original HDF and selected terrain; no conversion is inferred. hdf_path binds identities and hydraulic geometry. Optional table attrs fim_source_hdf and crs must match when present. Matching numeric IDs alone cannot prove a caller used the right source model. Do not mutate the input during the call. Prepared contexts own their staged snapshot after construction.

A supplied aggregate or healed terrain does not acquire native parity from selector-equivalence tests. The selected rendering options remain explicit, and the manifest records caller-vector hashes and scope.

Defaults to plain cell-corner sloping. render_mode="slopingPretty" includes cell faces and accepts the shallow/depth-weighting flags. Neither mode adds depth postprocessing. It preserves the native float32 plot tolerance. Plain-mode native 7.0.1 Max products were qualified on Davis pipes and Bald Eagle bridge/dam examples, and two Davis timesteps. Bounded Spring River/Spring Creek comparisons retain the complete mesh. Models containing 1D river or cross-section elements are rejected before mapping. Standalone storage-area surfaces outside the 2D mesh are not mapped unless storage_areas=True.

terrain_path must be a same-CRS float32 square-pixel GeoTIFF with declared nodata. bbox or polygon constrains output pixels; polygon masks require the engine's global-terrain-lattice/1 capability (0.10.1+). AOI edge inclusion uses global source pixel coordinates with lower-y/left endpoints included, upper-y/right excluded, and northward y. No geometric epsilon is applied. This intentionally replaces crop-dependent legacy boundary ties. Hydraulic connectivity uses the complete mesh. Polygon constraints accept the same geometry/frame/file forms as :meth:resolve_aoi.

Outputs require a new or empty folder. The returned fim_product_manifest DataFrame includes performance evidence in attrs["performance"]; the JSON manifest retains the same evidence. max_working_mib is planned admission, not an enforced RSS ceiling. timeout covers the engine stream including product writes. A missing or incompatible engine raises; no arithmetic fallback runs.

Parameters:

Name Type Description Default
hdf_path PathLike

Computed 2D plan-results HDF, as a string or Path.

required
terrain_path PathLike

Same-CRS, single-band float32 GeoTIFF with declared nodata and north-up square pixels.

required
output_folder PathLike

New or empty directory for products and manifest.

required
profiles Optional[Dict[str, Union[str, int]]]

Output names mapped to "Max" or nonnegative zero-based stored timestep indices. Defaults to Max.

None
wsel_profiles Optional[DataFrame]

Optional complete cell-keyed WSEL table, mutually exclusive with profiles. Requires physical and ghost rows in every mesh. See fim_cell_wsel_profiles schema and above.

None
render_mode str

"sloping" for corners or "slopingPretty" for corners and faces. Defaults to plain sloping.

'sloping'
reduce_shallow_to_horizontal bool

Native connectivity-based horizontal rendering for shallow cells; requires slopingPretty.

False
use_depth_weighted_faces bool

Rebalance donated corner/face weights by native depth; requires slopingPretty and stored corner elevations.

False
postprocessing_hdf Optional[PathLike]

Optional native corner cache. Cache-only input requires the adjacent receipt from prepare_corner_elevations.

None
corner_elevation_source str

auto compares supplied layouts and refuses conflicts; geometry or mapping_cache explicitly selects one.

'auto'
bbox Optional[Sequence[float]]

Optional output bounds in aoi_crs or the model CRS.

None
polygon Any

Optional polygon geometry, frame or vector-file AOI.

None
polygon_layer Optional[str]

Layer name when the AOI file has multiple layers.

None
aoi_crs Any

Coordinate reference system of the AOI.

None
engine_path Optional[PathLike]

Matching engine executable, otherwise environment/PATH.

None
threads int

Bounded Rust worker count, 1 through 64.

1
writer_threads int

GeoTIFF compression workers, 1 through 64. Defaults to one and can overlap native preparation of later profiles; budget both pools. Compression and raster layout are unchanged. Overrides GDAL_NUM_THREADS during writes and restores it after success or failure, including when the default is used.

1
max_working_mib int

Planned engine memory admission budget in MiB; HDF/Python preparation and polygonization also use memory.

1024
max_inflight_profiles int

Maximum concurrent timestep/profile maps, 1 through 64. Defaults to sequential processing. Effective concurrency is capped by threads, profile count and planned memory admission, and recorded in the engine report. Requests greater than one require engine concurrency support. All maps share the same Rust worker pool, terrain and geometry.

1
timeout Optional[float]

Engine stream lifetime in seconds, including output writes.

None
product_writer str

"rasterio" (default), or "native" for direct terrio LZW GeoTIFF output on a capable engine. Native output preserves the requested CRS/grid and float32 results, uses one compression worker, and excludes templates, floodplain polygonization and velocity.

'rasterio'
row_stream_rows int

Zero (default) keeps full-array rendering. An integer from 1 through 4096 opts into bounded raster row batches with a capable engine and product_writer="native". Requires plain sloping without velocity or storage areas. Ownership and terrain remain resident for the full window.

0
final_format Optional[Dict[str, Any]]

None (default) or a dict asking a capable engine (native_final_format) to write Depth and WSE once in their delivery form: tiled DEFLATE (predictor 1) with a numeric nodata value. Requires product_writer="native"; arrays are not streamed to Python and Rasterio writes nothing, so there is no fallback. Keys: nodata (required; finite and exact in float32), block_size (default 256; multiple of 16, 16 through 4096), zlevel (default 6; 1 through 9), overviews (default []; consecutive powers of two such as [2, 4], GDAL average) and grid: "window" (default, the mapped window), "terrain" (the whole terrain grid) or [col, row, width, height] terrain pixels containing the mapped window; pixels outside the window are nodata. Product names are unchanged and manifest rows describe the delivered grid. A valid value that is infinite or would read as the nodata value is refused rather than masked.

None
write_floodplain bool

Also polygonize positive retained depth pixels.

False
template_raster Optional[PathLike]

Optional float32 GeoTIFF defining the delivered grid, nodata and storage profile. Must share the terrain pixel lattice and contain the processing window. Values are written once, with nodata padding and no resampling. Offsets in the returned manifest then refer to this template grid.

None
terrain_hdf Optional[PathLike]

Optional registered terrain HDF. When given, terrain_path must be its unmodified priority-1 source TIFF (:meth:top_priority_terrain_source), mapped directly without a RAS Mapper terrain export. The level-0 mask is staged as the request's terrain_scope. Pixels outside that source's footprint are accepted only in cells that fail the wet gate; otherwise the engine refuses and FimUnsupportedError is raised so callers can map on an exported terrain. Plain sloping only; terrains with modifications and plans with storage areas are refused. Requires engine top-priority-source-footprint/1.

None
velocity bool

Also render velocity magnitude (rasmapper-sloping-velocity/0) and add velocity_tif (12_<profile>_velocity.tif, float32, NaN nodata, model velocity units) to each row. Max uses Maximum Face Velocity with Maximum Water Surface; a timestep index uses Face Velocity at that output time. Face normals use face polyline lengths. RAS Mapper's velocity values do not depend on the render mode; it clips them with the active mode's depth. Drawn where the velocity_depth depth is > 0. sloping and slopingPretty with HDF profiles; refuses wsel_profiles, template_raster and storage-area plans. slopingPretty needs an engine advertising it in velocity_render_modes; with reduce_shallow_to_horizontal or use_depth_weighted_faces the engine must also advertise velocity_with_faces (rasmapper-with-faces-velocity-derived/1) listing that option, and the mask is the depth rendered with the same options.

False
velocity_depth str

"rendered" (default) clips velocity with this request's rendered depth. "horizontal" clips it with the horizontal cell-constant depth, reproducing RAS Mapper's horizontal-mode velocity; the WSE/depth products stay sloping.

'rendered'
derived_products Sequence[str]

Per-profile products from the clipping depth and velocity: "depth_x_velocity", "depth_x_velocity_squared" and "froude" (13_<profile>_<product>.tif, added to each row as <product>_tif). Requires velocity=True and an engine advertising rasmapper-depth-velocity-products/1. For Max, use :meth:map_derived_max: RAS Mapper's Max of these products is the per-time product's maximum, not Max d x Max v.

()
invalid_cells str

Pixel ownership for physical cells whose face polylines do not form a valid polygon (for example, a face that crosses back over another face of the same cell). HEC-RAS computes such cells; strict polygon assembly refuses them. "repair" (default) polygonizes the cell's noded face polylines, removes area owned by valid cells and keeps the largest part. "hull" uses the face-point convex hull with the same overlap removal. "omit" leaves the cell unmapped. "raise" keeps the strict refusal, but only when the AOI (or the whole mesh, without one) intersects an affected cell. Overlapping neighbours of an invalid cell are resolved by ascending cell ID; split cells keep every piece and fully overlapped cells own no pixels. Hydraulic connectivity, corners and interpolation stencils always use the complete HDF topology. Horizontal, whole-simulation and comparison mapping apply the same policy when strict assembly refuses the mesh. fim_manifest.json and attrs["invalid_cells"] record each cell, the reason and the action taken.

'repair'
terrain_crs_fnv1a64 Optional[str]

Engine WKT hash to accept when the engine cannot identify the terrain EPSG code, as in :meth:map_profiles. Check the terrain with ras2fim-batch terrain-info first; the hash must equal the engine's crs_wkt_fnv1a64. The terrain and results CRS must still agree under rasterio and resolve to an EPSG code. Ignored when the engine reports an EPSG code. The manifest records the accepted identity as terrain_crs_identity.

None
shear_stress bool

Also render RAS Mapper's Max shear stress (rasmapper-face-shear-max/1) and add shear_stress_tif (15_<profile>_shear_stress.tif, float32, NaN nodata, lb/ft2 or N/m2) to the row. RAS Mapper's Max shear is a face quantity: at every stored output time each face's shear k*|V|*V*n^2/R^(1/3) is computed from least-squares facepoint velocities, the Faces Area Elevation hydraulic radius at the sloping face water surface and the face's Manning's n (k = 28.258362 US, 9810 SI); each face keeps its largest magnitude, facepoints average their faces, and the plain sloping weights paint them. The values do not depend on the render mode; shear_depth sets the mask. Max only: profiles must be one name selecting "Max" (default {"Max": "Max"}). Plain sloping with HDF profiles; refuses wsel_profiles, prepared models, storage-area plans, native products, row streaming and template_raster. Stages every stored output time's cell Water Surface and Face Velocity. Requires an engine advertising the method; see :meth:supports_shear_stress. attrs["shear_stress"] records the rule and the engine's face pass.

False
shear_depth str

"rendered" (default) draws shear where this request's rendered Max depth is > 0; "horizontal" uses the horizontal cell-constant Max depth, reproducing RAS Mapper's horizontal-mode Shear Stress (Max).

'rendered'
storage_areas bool

Also draw the plan's standalone storage areas as RAS Mapper level pools (storage-area-level-pool/1): every pixel whose centre is inside a storage-area polygon gets that area's WSE (Maximum Water Surface for Max, the stored Water Surface for a timestep), visible where float32 wse >= terrain + 0.001, depth wse - terrain. The window grows to cover the storage areas. The same in every render mode; qualified against native HEC-RAS 7.0.1 stored maps on BaldEagleCrkMulti2D storage-area plans. Storage areas overlapping 2D cells or each other, and with terrain_hdf any storage-area pixel outside the priority-1 source footprint, are refused (FimUnsupportedError). Not available with wsel_profiles, velocity or prepared models. Requires an engine advertising storage_area_surfaces; see :meth:supports_storage_areas. attrs["storage_areas"] records the areas and their mapped pixel count.

False

Returns:

Type Description
DataFrame

fim_product_manifest rows with timing evidence in

DataFrame

attrs["performance"] and the JSON manifest. mapping_scope

DataFrame

and model_scope attributes identify the included model elements.

DataFrame

Supplied vectors add attrs["profile_source"] with canonical

DataFrame

per-mesh/profile hashes for rendered requests. terrain_hdf adds

DataFrame

attrs["terrain_scope"]; velocity adds attrs["velocity"].

Raises:

Type Description
FimUnsupportedError

Unsupported model, geometry, AOI or terrain.

FimEngineNotFoundError

The optional executable is unavailable.

FimEngineError

Engine failure, inconsistent output or changed input.

MeshCellPolygonError

invalid_cells="raise" and an invalid cell intersects the requested output.

ValueError

Invalid profile selectors, supplied identities/values, source metadata or resource options.

TypeError

wsel_profiles is not a pandas DataFrame.

FileExistsError

The output directory is not empty.

supports_shear_stress staticmethod

Python
supports_shear_stress(engine_path: Optional[PathLike] = None) -> bool

Whether the installed engine renders RAS Mapper's Max shear stress.

True when the engine's sloping method advertises shear_stress = rasmapper-face-shear-max/1, so shear_stress=True can be passed to :meth:map_sloping_profiles. False when the engine is older or missing; never raises for a missing engine. Engine execution or metadata errors propagate.

Parameters:

Name Type Description Default
engine_path Optional[PathLike]

Engine executable, otherwise environment/PATH.

None

Returns:

Type Description
bool

Max shear stress is available.

supports_storage_areas staticmethod

Python
supports_storage_areas(engine_path: Optional[PathLike] = None) -> bool

Whether the installed engine draws storage-area level pools.

True when the engine's sloping, horizontal and whole_simulation methods all advertise storage-area-level-pool/1, so storage_areas can be passed to :meth:map_sloping_profiles, :meth:map_horizontal_profiles and :meth:map_whole_simulation. False when the engine is older or missing; never raises for a missing engine. Engine execution or metadata errors propagate instead of being reported as absent support.

Parameters:

Name Type Description Default
engine_path Optional[PathLike]

Engine executable, otherwise environment/PATH.

None

Returns:

Type Description
bool

Storage-area surfaces are available.

map_derived_max staticmethod

Python
map_derived_max(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, products: Sequence[str] = ('depth_x_velocity', 'depth_x_velocity_squared', 'froude'), render_mode: str = 'sloping', velocity_depth: str = 'rendered', bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, engine_path: Optional[PathLike] = None, threads: int = 1, max_inflight_profiles: int = 1, reduce_shallow_to_horizontal: bool = False, use_depth_weighted_faces: bool = False, postprocessing_hdf: Optional[PathLike] = None, max_working_mib: int = 2048, timeout: Optional[float] = None, terrain_hdf: Optional[PathLike] = None, invalid_cells: str = 'repair', terrain_crs_fnv1a64: Optional[str] = None) -> pd.DataFrame

Map RAS Mapper's Max D x V, D x V^2 and Froude in one time-series pass.

RAS Mapper computes these Max products per stored output time from that time's rendered depth and velocity, then keeps the pixelwise maximum; the valid area is the union over all times. That is not Max depth times Max velocity. This method stages every stored output time and lets the engine reduce them (reduce_max/1) without writing per-time products.

Parameters:

Name Type Description Default
hdf_path PathLike

Computed 2D plan-results HDF.

required
terrain_path PathLike

Terrain GeoTIFF, as for :meth:map_sloping_profiles.

required
output_folder PathLike

New or empty directory.

required
products Sequence[str]

Subset of depth_x_velocity, depth_x_velocity_squared and froude.

('depth_x_velocity', 'depth_x_velocity_squared', 'froude')
render_mode str

"sloping" or "slopingPretty".

'sloping'
velocity_depth str

"rendered" or "horizontal" (RAS Mapper's horizontal mode: horizontal depth and its velocity clip).

'rendered'
reduce_shallow_to_horizontal bool

slopingPretty shallow reduction, as in :meth:map_sloping_profiles. Use the project's RAS Mapper setting: RasProcess.store_maps(render_mode="slopingPretty") turns it on. Needs an engine advertising velocity_with_faces with this option.

False
use_depth_weighted_faces bool

slopingPretty depth-weighted faces, as in :meth:map_sloping_profiles; needs stored corner elevations and an engine advertising velocity_with_faces with this option.

False
postprocessing_hdf Optional[PathLike]

Optional PostProcessing.hdf with native corner elevations, as in :meth:map_sloping_profiles.

None
bbox Optional[Sequence[float]]

Optional output bounds in aoi_crs or the model CRS.

None
polygon Any

Optional polygon geometry, frame or vector-file AOI.

None
polygon_layer Optional[str]

Layer name when the AOI file has multiple layers.

None
aoi_crs Any

Coordinate reference system of the AOI.

None
engine_path Optional[PathLike]

Matching engine executable.

None
threads int

Rust worker count, 1 through 64.

1
max_inflight_profiles int

Concurrent output times.

1
max_working_mib int

Planned engine memory admission budget.

2048
timeout Optional[float]

Engine lifetime in seconds.

None
terrain_hdf Optional[PathLike]

Optional registered terrain HDF for the priority-1 source TIFF, as for :meth:map_sloping_profiles.

None
invalid_cells str

Invalid-cell ownership policy.

'repair'
terrain_crs_fnv1a64 Optional[str]

Engine WKT hash, as for :meth:map_profiles.

None

Returns:

Type Description
DataFrame

DataFrame with one row per product (product, tif,

DataFrame

valid_pixels); attrs["max_derived"] and the JSON manifest

DataFrame

hold the evidence, attrs["velocity"] the method.

Raises:

Type Description
FimUnsupportedError

Unsupported model, engine capability or scope.

FimEngineError

Engine failure or inconsistent output.

ValueError

Invalid products or options.

top_priority_terrain_source staticmethod

Python
top_priority_terrain_source(terrain_hdf: PathLike, *, rasmap_path: Optional[PathLike] = None) -> Dict[str, Any]

Identify the priority-1 source TIFF of a registered terrain HDF.

RAS Mapper writes stored maps per terrain source, on the source's own grid; inside the highest-priority source's footprint the effective terrain is that source's original TIFF. Priority is read from the source groups' integer Priority attributes (0 highest) or, when no source carries one, from the terrain's own VRT beside the HDF, which lists sources highest priority first. Both must agree when present.

Parameters:

Name Type Description Default
terrain_hdf PathLike

Registered terrain HDF.

required
rasmap_path Optional[PathLike]

Optional rasmap; its terrain layer's elevation modification layers are then also reported, and the RAS Mapper gate is applied: HEC-RAS 6.6 and 7.0.1 apply the HDF modifications only when the terrain layer has an ElevationModificationGroup named exactly Modifications. Without one, modified is False.

None

Returns:

Type Description
dict

tif (Path of the priority-1 source TIFF), source_count,

Dict[str, Any]

terrain_hdf, modified (terrain modifications RAS Mapper

Dict[str, Any]

applies), source, sources (file names in priority order),

Dict[str, Any]

priority_basis, mask_dataset, mask_shape,

``modifications``, ``rasmap_checked`` and ``rasmap_warnings``

a

Dict[str, Any]

list of {"code", "group", "layers", "message"} records, with

Dict[str, Any]

code "modification_group_misnamed" for each modification

Dict[str, Any]

group under another name (RAS Mapper ignores it; rename it to

Dict[str, Any]

Modifications) and "modification_group_missing" when the

Dict[str, Any]

HDF has modifications but the terrain layer has no group. Neither

Dict[str, Any]

file is changed.

Raises:

Type Description
FimUnsupportedError

Priority cannot be proven (missing, partial, duplicate or conflicting declarations), the source TIFF or its level-0 Mask is missing, or the rasmap does not register it.

supports_effective_terrain staticmethod

Python
supports_effective_terrain(engine_path: Optional[PathLike] = None) -> bool

Whether the installed engine builds RAS Mapper's effective terrain.

True when ras2fim-batch method advertises rasmapper-effective-terrain/1 or /2 (as its method ID or a compatible ID). Modified terrains also need /2 with a modifications record. Never raises for a missing engine. Engine execution or metadata errors propagate.

Parameters:

Name Type Description Default
engine_path Optional[PathLike]

Engine executable, otherwise environment/PATH.

None

Returns:

Type Description
bool

:meth:build_effective_terrain is available.

build_effective_terrain staticmethod

Python
build_effective_terrain(terrain_hdf: PathLike, output_path: PathLike, *, rasmap_path: Optional[PathLike] = None, engine_path: Optional[PathLike] = None, threads: int = 1, max_working_mib: int = 4096, timeout: Optional[float] = None, terrain_crs_fnv1a64: Optional[str] = None, hecras_version: Optional[str] = None, ras_object: Any = None, basis: str = 'export') -> Dict[str, Any]

Build RAS Mapper's effective terrain in Rust, with qualified modifications.

Writes the float32 grid RasTerrain.export_rasmapper_terrain( downsample_factor=1, rasterize_modifications=False) obtains from RasMapperLib, without HEC-RAS: stitch TIN first, then the sources in proven priority order (Priority attributes or the terrain VRT), each answering where its four surrounding pixel centres are valid and in its level-0 footprint, rounded to binary32 and 1/32 as RAS Mapper stores terrain. Output: 256 x 256 tiled DEFLATE GeoTIFF, nodata -9999, on the finest source's lattice over the union of the source extents, plus <output>.json (the returned receipt).

Qualified against HEC-RAS 7.0.1 exports: Bald Eagle Terrain50 (two sources, 197,179,058 valid px) has an identical valid mask and 8 values differ, all in stitch-TIN corners where RAS Mapper's own exports are unstable; synthetic one-to-three-source terrains are bit-identical on 4 of 5 (5 stitch-TIN corner px on the fifth).

Parameters:

Name Type Description Default
terrain_hdf PathLike

Registered terrain HDF.

required
output_path PathLike

New .tif path (replaced if it exists).

required
rasmap_path Optional[PathLike]

Optional rasmap; a modification layer registered there but not stored in the terrain HDF is refused. RAS Mapper's export applies every HDF modification whatever its Checked state.

None
engine_path Optional[PathLike]

Engine executable, otherwise environment/PATH.

None
threads int

Engine worker threads (1-64).

1
max_working_mib int

Engine memory admission; the output is held in memory (4 bytes/px plus a 1-bit TIN map).

4096
timeout Optional[float]

Engine timeout in seconds.

None
terrain_crs_fnv1a64 Optional[str]

Caller-verified WKT hash when the engine does not identify the EPSG code of a source CRS that rasterio identifies by EPSG. It cannot replace the EPSG code itself. A CRS without one (for example ESRI:102630) needs an engine that advertises crs_any (Fast-Map 0.20+), which takes the CRS as verbatim GeoKey tags: the source's own, or, for RAS Mapper sources that carry no CRS, GDAL's tags for the terrain HDF's Projection (checked by a GDAL round trip). Older engines refuse it; use the RAS Mapper export.

None
hecras_version Optional[str]

HEC-RAS release whose export the modifications reproduce (for example "6.6", "6.7 Beta 5" or "7.0.2"). None resolves the project's version: ras_object's HEC-RAS version, else the newest Program Version of the plan and geometry files beside rasmap_path or the terrain's project folder, else 7.0.1 when no version is found. The release maps to an engine rule through the engine's advertised hecras_versions table (Fast-Map 0.18.0 has none: 6.6 and 6.7 take the 6.6 rule; 7.0, 7.0.1 and 7.0.2 take 7.0.1). A modified terrain from any other release (6.5 and earlier, after 7.0.2) is refused with reason "unqualified_hecras_version".

None
ras_object Any

Optional initialized RAS project whose HEC-RAS version selects hecras_version.

None
basis str

"export" (default): RAS Mapper's terrain export, as above. "stored_map": the terrain RAS Mapper's stored maps read (rule rasmapper-stored-map-terrain/1; engines that list it in the method record's bases, see :meth:supports_effective_terrain_basis). The two differ in RAS Mapper itself: the export never answers a source's last cell row and column and rounds every value to 1/32, while stored maps are written per source on the source's own grid from its own cells with the modifications unrounded. The stored-map basis is the single source's cells on its own GeoTIFF grid (unmodified: the source TIFF bit for bit), then the modifications rasterized as for the export, without rounding. Map on it to match RAS Mapper's stored maps. Multi-source terrains need an engine that composes sources on one lattice (rasmapper-stored-map-composition/1); otherwise they are refused before the engine runs. Composed terrains can differ from RAS Mapper's stored maps on source seams, where RAS Mapper composes per-source depth maps: on Helena split into 2 and 3 aligned sources (HEC-RAS 7.0.1), 27 and 68 of 6,865,021 wet pixels, all on seams, and no modified pixel. Qualified on Helena (one source, two channel ground lines, HEC-RAS 7.0.1 and 6.6 stored maps): Depth equals float32(WSE - terrain) on every wet pixel.

'export'

Returns:

Type Description
dict

Receipt with basis and basis_rule_id, method_id (the method the engine reports:

Dict[str, Any]

/2 from current engines for every request, /1 from older

Dict[str, Any]

engines), hecras_version (None for

Dict[str, Any]

an unmodified terrain), hecras_version_basis,

Dict[str, Any]

sources_in_priority_order, priority_basis,

``rasmap_warnings`` (as for

meth:top_priority_terrain_source),

Dict[str, Any]

seconds and the engine engine_report.

Terrain modifications (engine rasmapper-effective-terrain/2 with a modifications record): ground lines (high ground and channels, any elevation type including Add, named systems, control points, NaN templates and negative slopes), polygons (constant, or boundary elevations from perimeter control points or a stored profile, interior control points) and ellipses (any rotation) are rasterized as RAS Mapper's rasterize_modifications=True export does, layers in descending Priority (Priority 0 last). Ground-line profiles are densified in the project's unit system (SI Units in the .prj beside rasmap_path means meters). Qualified against HEC-RAS 6.6, 6.7 (Beta 4 and 5), 7.0, 7.0.1 and 7.0.2 exports. The engine refuses the remaining forms (boundary elevations sampled from the terrain, shape-Z polygons, polygons with more than one ring (holes or several parts; refused before the engine runs, reason multi_ring_polygon), named ground lines with control points or a NaN template, named ground lines under 6.6 or 6.7, other RAS layer types), so the caller uses the RAS Mapper export. An engine advertising only /1 refuses every modified terrain. Layer types RAS Mapper ignores (for example Type=Channel from older ras-commander writers) are skipped, and when rasmap_path is given without an ElevationModificationGroup named Modifications under the terrain (none, or only under another name), no modification is applied, as in RAS Mapper, and the receipt's rasmap_warnings says why.

Raises:

Type Description
FimUnsupportedError

Unqualified terrain modifications, unproven priority, missing masks, an engine without the method, a source CRS with no EPSG code, or an engine refusal (sources in different CRSs, non-square cells).

FimEngineNotFoundError

The optional executable is unavailable.

FimEngineError

Engine failure.

supports_effective_terrain_basis staticmethod

Python
supports_effective_terrain_basis(basis: str, engine_path: Optional[PathLike] = None) -> bool

Whether :meth:build_effective_terrain accepts basis with this engine.

"export" is available wherever the method is; "stored_map" needs an engine whose effective_terrain record lists it in bases. Never raises for a missing engine.

Parameters:

Name Type Description Default
basis str

"export" or "stored_map".

required
engine_path Optional[PathLike]

Engine executable, otherwise environment/PATH.

None

Returns:

Type Description
bool

The basis is available.

read_terrain_modifications staticmethod

Python
read_terrain_modifications(terrain_hdf: PathLike, *, rasmap_path: Optional[PathLike] = None, ras_object: Any = None, hecras_version: Optional[Any] = None, length_units: Optional[str] = None, strict: bool = False, engine_path: Optional[PathLike] = None) -> Dict[str, Any]

Read a terrain's modification layers as rasmapper-effective-terrain/2 stages them.

Returns the modification_layers that :meth:build_effective_terrain sends to the engine for this terrain, together with the HEC-RAS version and unit system they were staged for, without running the engine. Use it to decide, before any terrain work, whether a modified terrain can take the native effective-terrain route or must use the RAS Mapper export. The layers are the same objects the request carries; this method does not change them.

The reader follows RAS Mapper's load rules for HEC-RAS 6.6, 6.7 (Beta 4 and 5), 7.0, 7.0.1 and 7.0.2. It stages ground lines (HDF Type=Levee, subtypes Levee and Channel), polygons (Type=Polygon) and ellipses (Type=Circle). Layer types RAS Mapper ignores (for example Type=Channel from older ras-commander writers) and layers without an Attributes table are skipped with a log warning, as are polygon and ellipse features whose Elevation Value is NaN. The .rasmap ElevationModificationGroup gate is not applied here: :meth:top_priority_terrain_source reports whether RAS Mapper applies the modifications at all (modified). With rasmap_path, the record's warnings report registration problems, including layers the rasmap lists that the HDF does not store.

The call is logged through @log_call (entry and exit at DEBUG, exceptions with the method name).

Parameters:

Name Type Description Default
terrain_hdf PathLike

Registered terrain HDF. Links are resolved before the project folder is searched, as in :meth:build_effective_terrain.

required
rasmap_path Optional[PathLike]

Optional project rasmap. It selects the project file for the unit system and the folder searched for plan and geometry Program Version lines, and its terrain layer is checked for the warnings field.

None
ras_object Any

Optional initialized RAS project. Its HEC-RAS version and project file take precedence over rasmap_path.

None
hecras_version Optional[Any]

HEC-RAS release whose export the layers reproduce, for example "6.6", "6.60", "6.7 Beta 5", "7.0.2" or (6, 6, 0). HEC-RAS 7.0, 7.0.1 and 7.0.2 map to the engine's "7.0.1" rule, 6.6 to "6.6" and the 6.7 betas to "6.7" (engines that advertise it) or "6.6" (Fast-Map 0.18.0). Any other release (6.5 and earlier, later than 7.0.2) is refused with refusal_reason "unqualified_hecras_version". None resolves the project's version: ras_object's HEC-RAS version, else the newest Program Version of the plan and geometry files beside rasmap_path or in the terrain's project folder, else 7.0.1 when no version is found at all.

None
length_units Optional[str]

RAS Mapper unit system, "feet" or "meters". None reads it from the project file (SI Units means meters; feet when no project file states units), as :meth:build_effective_terrain does. An explicit value applies to this reader only: it shows the layers staged for that unit system, and :meth:build_effective_terrain, which has no such argument, still uses the project's units.

None
strict bool

Raise :class:FimUnsupportedError for a refusal instead of returning a "refused" record.

False
engine_path Optional[PathLike]

Optional engine executable whose advertised hecras_versions table maps the release to a rule, as :meth:build_effective_terrain does. Otherwise the engine is found as there (environment, PATH, installed wheel); without one, or with an engine that advertises no table, the Fast-Map 0.18.0 mapping applies.

None

Returns:

Type Description
dict

A ras-commander-terrain-modifications/1 record with the

Dict[str, Any]

fields listed below.

Record fields:

  • schema (str): "ras-commander-terrain-modifications/1".
  • terrain_hdf (str): The terrain HDF read (links resolved).
  • method_id (str): The engine method the layers are staged for, "rasmapper-effective-terrain/2".
  • status (str): "staged" (the HDF stores one or more layers, all in forms the engine stages), "none" (no layer to stage: no /Modifications group, or only layers and features RAS Mapper skips) or "refused". status describes the HDF layers only, not whether RAS Mapper applies them: it applies none unless the rasmap terrain layer has an ElevationModificationGroup named Modifications. Use :meth:top_priority_terrain_source ["modified"] before treating layers as applied, or pass rasmap_path and check warnings: modification_group_missing means nothing is applied; modification_group_misnamed means that group's entries are ignored, and nothing is applied only when no group is named Modifications.
  • refusal (str or None): For "refused", the reason the terrain cannot take the native route, naming the layer and feature; otherwise None.
  • refusal_reason (str or None): The stable reason code of the refusal, copied from the reason attribute of the reader's :class:FimUnsupportedError (for example "multi_ring_polygon" or "unqualified_hecras_version"); None when the refusal has no code or there is no refusal. Match on this code rather than on the refusal text.
  • hecras_version (str or None): The engine rule, "7.0.1", "6.6" or "6.7"; None when the version could not be resolved or has no qualified rule (refusal_reason "unqualified_hecras_version").
  • hecras_version_basis (str or None): "argument", "ras_object.ras_version <label>", "ras_object.ras_exe_path <folder>", "Program Version <label> in <folder>" or "default".
  • length_units (str or None): "feet" or "meters"; None when the unit system could not be resolved: project files that state different units, on a terrain with no layer to stage (status "none"; with layers to stage it is a refusal).
  • length_units_basis (str or None): "argument", "project" (a project file states the units) or "default" (no project file states units; feet assumed).
  • warnings (list of dict): {"code", "group", "layers", "message"} rasmap registration records, empty without rasmap_path: "modification_group_misnamed" and "modification_group_missing" (as in :meth:top_priority_terrain_source; RAS Mapper ignores a misnamed group, and applies no modification when there is no group named Modifications), "rasmap_layer_not_in_hdf" (the Modifications group lists layers the HDF does not store; :meth:build_effective_terrain refuses the terrain) and "rasmap_not_checked" (the rasmap cannot be read or does not register this terrain). Warnings do not change status.
  • layers (list of dict): Engine request layers in HDF order (empty unless "staged"). Layer priority is the HDF Priority (0 is applied last and wins). Coordinates are in the terrain CRS; elevations, widths, reaches and tolerances in the project's vertical/horizontal length units; slopes as horizontal:vertical ratios; transition_percent in percent; ellipse rotation in degrees. NaN template values are None. By kind:

  • "ground_line": name, priority, subtype ("levee" or "channel"), length_units, optional control_points ({"x", "y", "elevation"} dicts; a NaN elevation is None) and features with elevation_type (SetValue, SetIfHigher, SetIfLower, Add), top_width, left_slope, right_slope, max_reach, points ([x, y]), profile ([station, elevation]), system_name, transition_percent and elev_pt_tolerance.

  • "polygon": name, priority, length_units, optional control_points and features with elevation_type (as ground lines), elevation, rings ([[x, y], ...] per part), generate_boundary, use_shape_z, profile, elev_pt_tolerance and, with use_shape_z, vertex_z.
  • "ellipse": name, priority and features with elevation_type (SetValue, SetIfHigher, SetIfLower), elevation, center ([x, y]), radius_x, radius_y and rotation.

Refusal reasons (the first one met is reported; each is a form the engine also refuses or whose order or export is unproven): RAS layer types the engine does not reproduce (Rectangle, Triangle, Encroachment Polygon, Levee1, Pier, Tree); a missing or shared Priority; an unknown ground-line subtype or an unqualified elevation type; ground lines with no stored profile and no control points; a NaN Top Width with a finite Max Reach; named ground lines with control points, a NaN template or under HEC-RAS 6.6 or 6.7; multi-part ground lines; polygon features with more than one ring (holes or separate/overlapping parts), refused up front with reason="multi_ring_polygon" because RAS Mapper's joining and triangulation of such rings is not reproducible as a rule; polygon boundary elevations sampled from the terrain (no control point outside the ring within Elev Pt Tolerance and no stored profile; under 6.6 any boundary elevations without such a point); a HEC-RAS release without a qualified rule ("unqualified_hecras_version"); shape-Z polygons without boundary elevations; invalid geometry or control points; and project files in the folder that state different units when there are layers to stage. An engine can still refuse a staged terrain; compare the layers with the engine's modifications capability record.

Raises:

Type Description
FimUnsupportedError

With strict=True, for a refusal; its reason attribute carries the reason code when one is assigned.

ValueError

length_units is not "feet" or "meters".

OSError

The terrain HDF does not exist or cannot be opened.

map_whole_simulation staticmethod

Python
map_whole_simulation(hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, *, products: Sequence[str] = ('arrival_time', 'percent_inundated'), threshold: float, allow_unqualified: bool = False, terrain_hdf: Optional[PathLike] = None, threads: int = 1, writer_threads: int = 1, max_working_mib: int = 1024, timeout: Optional[float] = None, engine_path: Optional[PathLike] = None, invalid_cells: str = 'repair', storage_areas: bool = False, terrain_crs_fnv1a64: Optional[str] = None) -> pd.DataFrame

Map arrival time, percent time inundated and (opt-in) duration.

Uses the engine's native-whole-simulation-horizontal/1 method: every stored output time of the plan is rendered over the physical 2D cells and accumulated per pixel. A pixel is wet at an output time when its rendered depth is strictly greater than threshold and its cell passes RAS Mapper's thresholded gate wse > cell minimum + threshold (float32). These are RAS Mapper's definitions:

  • arrival_time: first wet output time in hours since the plan's simulation start (Plan Information/Simulation Start Time), float32;
  • percent_inundated: 100 * wet output times / all output times;
  • duration (qualified with an engine advertising duration_rule rasmapper-backward-window-recession/1; older engines need allow_unqualified=True): hours from arrival to RAS Mapper's recession time, found by its backward search over the monotone windows between the cell's water-surface extrema.

Never-wet pixels are NaN. Arrival time and percent inundated are qualified against RAS Mapper output: pixel conformance with native HEC-RAS 7.0.1 stored maps on Davis p02 and BaldEagleCrkMulti2D bridges p05 at a 0.5 ft threshold. RAS Mapper produces the same products in horizontal and sloping render modes on those models. Duration with the native recession rule matches the same references in every pixel; irregular output intervals are refused unless allow_unqualified.

Scope: pure 2D plans. Plans with 1D elements are refused. Plans with storage areas are refused unless storage_areas=True (use RAS Mapper for them otherwise).

Parameters:

Name Type Description Default
hdf_path PathLike

Computed 2D plan-results HDF.

required
terrain_path PathLike

Same-CRS float32 GeoTIFF (a RAS Mapper terrain export, or with terrain_hdf the priority-1 source TIFF).

required
output_folder PathLike

New or empty folder for <product>.tif and fim_manifest.json.

required
products Sequence[str]

Any of arrival_time, percent_inundated, duration. Defaults to the two qualified products.

('arrival_time', 'percent_inundated')
threshold float

Wet depth threshold in model vertical units (RAS Mapper's arrival depth; 0.5 is a half foot only in feet models).

required
allow_unqualified bool

Required for irregular intervals, and for duration on engines without the native recession rule.

False
terrain_hdf Optional[PathLike]

Optional registered terrain HDF whose unmodified priority-1 source TIFF is terrain_path. Horizontal rendering refuses any mapped pixel outside that source's footprint (FimUnsupportedError); map on an export instead.

None
threads int

Rust worker count, 1 through 64.

1
writer_threads int

GeoTIFF compression workers, 1 through 64.

1
max_working_mib int

Planned engine admission budget in MiB.

1024
timeout Optional[float]

Engine lifetime in seconds, or None.

None
engine_path Optional[PathLike]

Engine executable, otherwise environment/PATH.

None
terrain_crs_fnv1a64 Optional[str]

Explicitly verified engine terrain WKT hash, as for :meth:map_sloping_profiles. Model and terrain CRS must still agree; this never relabels or transforms coordinates.

None
invalid_cells str

Pixel ownership for cells whose face polylines do not form a valid polygon, as in :meth:map_sloping_profiles (default "repair"). Applied only when strict assembly refuses the mesh; valid meshes are unchanged. There is no AOI, so "raise" refuses whenever the plan has such a cell.

'repair'
storage_areas bool

Also accumulate the plan's standalone storage areas as level pools (storage-area-level-pool/1): at each output time a storage-area pixel is wet when the stored storage-area Water Surface minus terrain is strictly greater than threshold (native float32 plot test first); a level pool has no cell gate. Overlaps with 2D cells or other storage areas, and with terrain_hdf any storage-area pixel outside the priority-1 source footprint, are refused. Requires an engine advertising storage_area_surfaces on its whole-simulation method (:meth:supports_storage_areas).

False

Returns:

Type Description
DataFrame

fim_whole_simulation_manifest rows (one per product)

DataFrame

with tif paths. attrs hold performance,

DataFrame

time_reference, model_scope, unqualified case counts,

DataFrame

invalid_cells (fim-invalid-cells/1, also in

DataFrame

fim_manifest.json) and, with terrain_hdf, terrain_scope.

Raises:

Type Description
MeshCellPolygonError

invalid_cells="raise" and the plan has a cell whose face polylines do not form a valid polygon.

FimUnsupportedError

Duration without allow_unqualified, storage areas, 1D elements, unprovable or modified terrain, engine refusals, or an engine without the method.

FimEngineNotFoundError

The engine executable is unavailable.

FimEngineError

Engine failure, inconsistent output or changed input.

ValueError

Invalid products, threshold or resource options.

FileExistsError

The output directory is not empty.

map_horizontal_profiles staticmethod

Python
map_horizontal_profiles(cells: 'gpd.GeoDataFrame', terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Sequence[str]] = None, profile_prefix: str = DEFAULT_PROFILE_PREFIX, bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, min_depth: float = 0.0, backend: str = 'rust', engine_path: Optional[PathLike] = None, threads: int = 1, writer_threads: int = 1, timeout: Optional[float] = None, max_working_mib: int = 1024, write_floodplain: bool = True, raise_on_failure: bool = True, hdf_path: Optional[PathLike] = None, terrain_hdf: Optional[PathLike] = None, invalid_cells: str = 'repair', storage_areas: Optional[Dict[str, Union[str, int]]] = None) -> pd.DataFrame

Map cell-constant horizontal WSE using a shared terrain-lattice grid.

This explicit horizontal method fills each cell with its own WSE. It uses the Rust engine by default; NumPy is an explicit reference backend. It does not fall back from a failed engine run, interpolate between cells, or reproject the output. Cell ownership and terrain are prepared once and reused across every requested profile.

Parameters:

Name Type Description Default
cells GeoDataFrame

Valid non-overlapping cell Polygons with unique integer cell_idx and numeric WSE columns. NaN marks a dry cell. Not modified. A MultiPolygon row is accepted only for a split cell recorded by :meth:get_cells_from_plan_hdf (see invalid_cells).

required
terrain_path PathLike

Single-band float32 terrain GeoTIFF in the cells' CRS, with north-up square pixels and declared nodata. Its nodata pixels stay dry.

required
output_folder PathLike

New or empty folder for rasters and the manifest.

required
profiles Optional[Sequence[str]]

Profile columns; defaults to profile_prefix matches.

None
profile_prefix str

Prefix for selecting profile columns.

DEFAULT_PROFILE_PREFIX
bbox Optional[Sequence[float]]

Output constraint in aoi_crs or the terrain CRS.

None
polygon Any

Polygon, MultiPolygon, frame or vector file constraint.

None
polygon_layer Optional[str]

Layer name for a multi-layer vector file.

None
aoi_crs Any

CRS of the constraint; see :meth:resolve_aoi.

None
min_depth float

Optional strict positive depth cutoff after native visibility, in model elevation units. Zero adds no cutoff. Native visibility uses float32 WSE >= float32(terrain + 0.001), preserving operation order. Positive cutoffs filter both products; 0.5 is a half-foot filter only when elevation units are feet.

0.0
backend str

"rust" (default) or explicit "numpy" reference arithmetic.

'rust'
engine_path Optional[PathLike]

Optional executable path for the Rust backend.

None
threads int

Rust pixel worker count, 1 through 64.

1
writer_threads int

GeoTIFF compression workers, 1 through 64. Can overlap native work on the next profile; budget both pools. Overrides caller GDAL_NUM_THREADS during writes, including the default of one; restores it afterwards.

1
timeout Optional[float]

Rust subprocess/pipe lifetime in seconds, or None. Includes consumer product-writing backpressure; no automatic retry.

None
max_working_mib int

Planned array admission budget, not an RSS cap. Includes planned terrain-cache/decoder terms; excludes polygonization and unaccounted runtime overhead. Large windows fail before terrain or ownership arrays load.

1024
write_floodplain bool

Write product 11 from retained depth pixels.

True
raise_on_failure bool

Raise after writing the manifest if any profile failed; otherwise return the failed rows too.

True
hdf_path Optional[PathLike]

Source model HDF for the 2D-only scope check. Tables from get_cells_from_plan_hdf retain this provenance automatically. Standalone tables must contain only 2D cell polygons; without model provenance the model's other elements cannot be inspected.

None
terrain_hdf Optional[PathLike]

Optional registered terrain HDF. When given, terrain_path must be its unmodified priority-1 source TIFF (see :meth:top_priority_terrain_source); the level-0 mask is staged as terrain_scope and no terrain export is needed. Horizontal rendering has no cell minimum, so the engine refuses any mapped pixel outside the source footprint; the refusal is raised as FimUnsupportedError so callers can map on an exported terrain instead. Requires the Rust backend and an engine advertising top-priority-source-footprint/1.

None
invalid_cells str

Policy for cells whose face polylines do not form a valid polygon, as in :meth:map_sloping_profiles (default "repair"). Ownership is fixed when :meth:get_cells_from_plan_hdf extracts the table; pass the same value here (another value raises ValueError). Each piece of a split cell owns its pixels with the cell's WSE. "raise" refuses when the AOI (or the whole table, without one) intersects an affected cell. Tables without a record are mapped strictly. fim_manifest.json and attrs["invalid_cells"] hold the fim-invalid-cells/1 record.

'repair'
storage_areas Optional[Dict[str, Union[str, int]]]

Optional mapping of every mapped profile column to "Max" or a zero-based stored timestep index of the source plan HDF. The plan's standalone storage areas are then drawn as RAS Mapper level pools (storage-area-level-pool/1): each pixel whose centre is inside a storage-area polygon gets that area's WSE (Maximum Water Surface for Max, the stored Water Surface otherwise), visible where float32 wse >= terrain + 0.001, with the same min_depth cutoff. The window grows to cover the storage areas. Needs model provenance (hdf_path or a table from :meth:get_cells_from_plan_hdf), the Rust backend and an engine advertising storage_area_surfaces. Storage areas overlapping 2D cells or each other are refused (FimUnsupportedError). Use :meth:supports_storage_areas to detect the capability. attrs["storage_areas"] records the areas and their mapped pixel count.

None

Returns:

Type Description
DataFrame

fim_product_manifest rows. Offsets refer to the terrain grid, shared by all profiles. Product names match :meth:map_profiles; no nudge is performed in this method.

Raises:

Type Description
MeshCellPolygonError

invalid_cells="raise" and an affected cell intersects the requested output.

FimUnsupportedError

Invalid or overlapping cells, grid/CRS mismatch, unsupported terrain or an over-budget window.

FimMappingError

A failed profile or a changed input file.

FileExistsError

The output folder is not empty.

Notes

Shared polygon edges use rasterio centre ownership, with the higher sorted cell index written last. This is a horizontal 2D-cell method; it does not reproduce native sloping, 1D or structure-specific rendering. Finite input WSE must already reflect the caller's cell wet/dry policy. WSE is cast to float32 before native plotting visibility and subtraction. The intrinsic 0.001 plotting tolerance is compared in elevation space, not after depth subtraction. Positive optional cutoffs compare in float32. Product names are layout conventions, not method identifiers.

compare_with_rasmapper staticmethod

Python
compare_with_rasmapper(plan_number: str, terrain_path: PathLike, output_folder: PathLike, *, cells: Optional['gpd.GeoDataFrame'] = None, profiles: Optional[Dict[str, str]] = None, mesh_name: Optional[str] = None, bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, min_depth: float = 0.0, engine_path: Optional[PathLike] = None, threads: int = 1, writer_threads: int = 1, max_working_mib: int = 1024, postprocess_reference: bool = False, native_performance: Optional['StoreMapPerformanceOptions'] = None, terrain_name: Optional[str] = None, ras_object: Optional['RasPrj'] = None, ras_version: Optional[str] = None, timeout: int = 1800, invalid_cells: str = 'repair') -> pd.DataFrame

Generate native horizontal stored maps and compare with Rust mapping.

Native execution goes through :meth:RasProcess.store_maps. The original .rasmap bytes are verified and restored on success or failure under the same project lock. Work on a staged project: native mapping can generate other project-side caches. No solver is run.

Parameters:

Name Type Description Default
plan_number str

Computed plan in the initialized project.

required
terrain_path PathLike

Float32 export of the exact registered native terrain, including modifications. Matching terrain is the caller's responsibility; this function does not export or resample it.

required
output_folder PathLike

New or empty comparison folder.

required
cells Optional['gpd.GeoDataFrame']

Optional cell polygons and WSE columns. When omitted, use the plan's cell maximum results for the selected mesh or "*".

None
profiles Optional[Dict[str, str]]

Mapping from WSE column to "Max" or an exact native timestamp. Required with cells; caller ensures matching WSE.

None
mesh_name Optional[str]

Required for automatic extraction from multi-mesh plans; use "*" to map all physical 2D cells with globally unique row IDs.

None
bbox Optional[Sequence[float]]

Optional comparison/output bounds in aoi_crs.

None
polygon Any

Optional polygon constraint, mutually exclusive with bbox.

None
polygon_layer Optional[str]

Layer in a multi-layer polygon file.

None
aoi_crs Any

Constraint CRS; defaults to the cells' CRS.

None
min_depth float

Zero (default) preserves all native-visible pixels. Positive optional cutoffs apply independently to both products in model elevation units; 0.5 means half a foot only in feet.

0.0
engine_path Optional[PathLike]

Explicit Rust engine executable, or normal discovery.

None
threads int

Rust pixel workers (1 through 64).

1
writer_threads int

Delivery GeoTIFF compression workers (1 through 64) for Rust and optional filtered native products; same resource policy as map_horizontal_profiles.

1
max_working_mib int

Horizontal array admission budget, not RSS.

1024
postprocess_reference bool

Write thresholded native depth/WSE LZW products and time this postprocessing separately. Raw native products are preserved. Defaults to True.

False
native_performance Optional['StoreMapPerformanceOptions']

Optional native StoreMap execution policy. Default preserves aggregate StoreAllMaps. Independent helpers require a sole registered terrain; their requested policy is recorded. Useful for Davis's intermittent aggregate WSE output.

None
terrain_name Optional[str]

Exact registered terrain selected for native mapping.

None
ras_object Optional['RasPrj']

Initialized project object for multi-project use.

None
ras_version Optional[str]

Installed native mapping runtime version.

None
timeout int

Native per-profile mapping/lock timeout in seconds.

1800
invalid_cells str

Policy for cells whose face polylines do not form a valid polygon, passed to :meth:get_cells_from_plan_hdf for automatic extraction and to :meth:map_horizontal_profiles (default "repair"). Explicit cells must have been extracted with the same value. "raise" refuses before native mapping when the AOI (or the whole table) intersects an affected cell. The JSON report records invalid_cells.

'repair'

Returns:

Type Description
DataFrame

fim_comparison metrics and raster paths. The JSON report retains native runtime, original/restored rasmap hashes, strict threshold and batch timing. result.attrs["performance"] additionally returns Rust batch, native mapping/postprocessing, and comparison timings. Candidate per-profile time is NaN for shared batches. A CSV is also written. Ratios are withheld for AOIs, unestablished full coverage or native storage-area surfaces.

Raises:

Type Description
FimUnsupportedError

Unsupported or misaligned grids, unavailable products, or ambiguous native terrain mosaics.

ValueError

Invalid profiles, threshold or plan selection.

RuntimeError

Native mapping or configuration restoration failed.

Notes

The whole source model must be 2D-only: any river centerline/reach or cross section is rejected before native execution, even with an explicitly selected 2D mesh. Pipe networks are permitted. Equality is evaluated only inside the selected 2D cell footprint and AOI, on matching lattice pixels without reference resampling. Missing WSE is counted separately. This is qualification evidence, not automatic acceptance of hydraulic accuracy. Timing includes different preparation stages and is not a controlled speed benchmark.

compare_rasters staticmethod

Python
compare_rasters(candidate_depth: PathLike, candidate_wse: PathLike, reference_depth: PathLike, reference_wse: PathLike, *, cells: 'gpd.GeoDataFrame', min_depth: float = 0.0, terrain_path: Optional[PathLike] = None) -> Dict[str, Any]

Compare existing depth/WSE rasters on a physical 2D cell footprint.

Positive cutoffs apply the same strict float32 depth filter independently to both products. Zero preserves every valid pixel, including native-valid zero depths. Exact fractions compare float32 bits. Files are not changed; no maps are generated and references are never resampled. Inputs must share a CRS, resolution and integer-offset north-up lattice; cells must use that CRS. Missing WSE is counted separately from jointly finite WSE differences. Optional terrain supplies native implied-terrain residuals. Returns the numerical metrics used by compare_with_rasmapper, without generation timings.

Reuse qualified raw native maps to demonstrate varying postprocessing cutoffs. Candidate inputs must retain all depths needed by the cutoff; filtering cannot recover pixels already removed by a higher cutoff. Model provenance on cells is checked for the 2D-only scope. A numeric comparison does not establish the provenance of caller-supplied files.

canonicalize_terrain_crs staticmethod

Python
canonicalize_terrain_crs(terrain_path: PathLike, output_path: PathLike) -> Path

Copy float32 terrain with equivalent canonical EPSG GeoTIFF keys.

Use explicitly when a native reader cannot interpret custom CRS keys, such as the Davis HARN terrain. This is metadata encoding, with no reprojection, resampling or elevation change. The source stays read-only. Requires an equivalent EPSG CRS and nodata, rejects dataset/alpha masks, and verifies all output pixel bits and the grid. Both output_path and its .json receipt must be new. Returns the prepared path; raises on unsupported input, existing outputs or failed verification. Preparation is separate from mapping performance timing.

inspect_model_scope staticmethod

Python
inspect_model_scope(hdf_path: PathLike, *, geom_path: Optional[PathLike] = None) -> 'FimModelScope'

Inspect compiled geometry and source reach declarations without mapping.

Returns immutable dimensional metadata for 1D, 2D, mixed 1D/2D or storage-only models. Candidate method keys describe dimensional applicability, not installed capabilities or numerical qualification. No engine or HEC-RAS runtime is loaded. Missing or malformed inputs raise instead of implying a supported mapping route.

validate_2d_model staticmethod

Python
validate_2d_model(hdf_path: PathLike, *, geom_path: Optional[PathLike] = None) -> Dict[str, Any]

Require compiled 2D cells and reject any 1D river/reach or cross section.

Inspect the whole model, even when mapping a selected 2D mesh. Pipes, conduits, storage areas and SA/2D connections are permitted. This check establishes dimensional scope, not structure-rendering equivalence. Source geometry is checked when supplied or resolved from the HDF. Returns a scope dictionary; raises FimUnsupportedError for 1D/mixed geometry. Unreadable or missing inputs raise instead of passing.

find_engine staticmethod

Python
find_engine(engine_path: Optional[PathLike] = None) -> Path

Return the path of the ras2fim-batch engine executable.

Resolution order: engine_path, then the RAS_COMMANDER_FIM_ENGINE environment variable, ras2fim-batch on PATH, then the installed ras-commander-fast-map distribution's script. The optional fim extra installs that external wheel on qualified platforms.

Raises:

Type Description
FimEngineNotFoundError

No executable was found. The engine is never built or installed by a runtime mapping call.

get_capabilities staticmethod

Python
get_capabilities(engine_path: Optional[PathLike] = None) -> 'FimCapabilities'

Return an immutable view of advertised methods and qualification.

A stable API contract describes versioned request semantics; it does not establish native parity or production model preparation. Inspect each method's intended use and numerical qualification separately. Metadata absent from an older engine remains undeclared. Missing or broken engines and malformed capability records raise the existing FIM engine exceptions; no engine is installed or substituted.

get_engine_info staticmethod

Python
get_engine_info(engine_path: Optional[PathLike] = None) -> Dict[str, Any]

Return the engine path and its method record (ras2fim-batch method).

get_cells_from_results_gpkg staticmethod

Python
get_cells_from_results_gpkg(results_gpkg: PathLike, layer: str = RAS2FIM_CELLS_LAYER) -> 'gpd.GeoDataFrame'

Read a ras2fim-2D hydraulic-results cell layer.

The ras2fim-2D layer 02_cells_wsel_ar holds one polygon per cell with cell_idx and WSE profile columns (wsel_*), NaN where the cell is dry for that profile. The file is opened read-only.

Returns:

Type Description
GeoDataFrame

The layer as stored.

get_cell_centers staticmethod

Python
get_cell_centers(hdf_path: PathLike, cell_ids: Optional[Iterable[int]] = None, *, mesh_name: Optional[str] = None) -> 'gpd.GeoDataFrame'

Return HEC-RAS 2D cell centres for the FIM method.

Centres are the computational cell centres (HdfMesh.get_mesh_cell_points), not polygon centroids.

Parameters:

Name Type Description Default
hdf_path PathLike

Plan or geometry HDF that contains the 2D mesh geometry.

required
cell_ids Optional[Iterable[int]]

Zero-based cell indices to return. None returns every cell. Duplicates are removed and the result is sorted by cell_idx.

None
mesh_name Optional[str]

2D flow area name. Required when the HDF has more than one.

None

Returns:

Type Description
GeoDataFrame

Cell indices and point geometries.

Raises:

Type Description
FimUnsupportedError

No mesh, an ambiguous or unknown mesh, or a requested cell that is not in the mesh.

get_cells_from_plan_hdf staticmethod

Python
get_cells_from_plan_hdf(hdf_path: PathLike, *, mesh_name: Optional[str] = None, profile_name: str = 'wsel_max', min_depth: float = 0.0, invalid_cells: str = 'repair') -> 'gpd.GeoDataFrame'

Build a one-profile cell table from a plan HDF's maximum results.

Uses HdfMesh.get_mesh_cell_polygons(strict=True), HdfResultsMesh.get_mesh_max_ws and HdfResultsMesh.get_mesh_max_depth. A cell is wet when its maximum depth is greater than min_depth; dry cells get NaN. This is the cell wet/dry policy; mapping's pixel min_depth independently filters the resulting terrain-based depths. Models with 1D river/reach elements are rejected. mesh_name="*" combines all meshes and assigns global positional cell_idx values; a single mesh retains its original cell IDs. Source-HDF provenance is retained in the returned frame's attrs for later mapping scope checks.

invalid_cells applies only when strict assembly refuses the mesh because a cell's face polylines do not form a valid polygon. The policy is that of :meth:map_sloping_profiles (default "repair"); the ownership it fixes is used by :meth:map_horizontal_profiles and :meth:compare_with_rasmapper, which must be called with the same value. A cell split by overlap resolution is one MultiPolygon row; omitted and consumed cells have no row. "raise" refuses later, when the mapping AOI (or the whole mesh, without one) intersects an affected cell. attrs["fim_invalid_cells"] records the policy and cells. Valid meshes are unchanged and carry no record. :meth:map_profiles (Step 05) refuses tables with affected cells.

Returns:

Type Description
GeoDataFrame

Cell indices, profile WSE and polygon geometries. Frames from plans on the same geometry can be joined on cell_idx to map a batch of profiles.

resolve_aoi staticmethod

Python
resolve_aoi(bbox: Optional[Sequence[float]] = None, polygon: Any = None, *, polygon_layer: Optional[str] = None, aoi_crs: Any = None, default_crs: Any = None) -> Optional[FimAoi]

Validate a bounding box OR polygon area of interest.

Parameters:

Name Type Description Default
bbox Optional[Sequence[float]]

(xmin, ymin, xmax, ymax). Its CRS is aoi_crs, else default_crs.

None
polygon Any

A Shapely Polygon/MultiPolygon (needs aoi_crs), a GeoDataFrame, or a vector file path (GeoJSON, GeoPackage, ...). Holes and multiple parts are kept; features are unioned.

None
polygon_layer Optional[str]

Layer of a multi-layer polygon file.

None
aoi_crs Any

CRS of the AOI. Must agree with a frame or file CRS.

None
default_crs Any

CRS used for a bbox without aoi_crs.

None

Returns:

Type Description
Optional[FimAoi]

FimAoi, or None when neither bbox nor polygon is given.

Raises:

Type Description
FimAoiError

Both or invalid AOIs, a missing or conflicting CRS, invalid or empty geometry.

prepare_profile staticmethod

Python
prepare_profile(cells, centers, profile: str, pixel_size: float, lattice_origin: Optional[Sequence[float]] = None) -> FimPreparedProfile

Prepare the global interpolation samples and axes for one profile.

This is the preparation map_profiles sends to the engine, exposed for inspection and qualification. It always uses every wet cell. Inputs are not modified. lattice_origin (a terrain pixel corner (x, y)) gives the grid_anchor="terrain" query axes.

map_profiles staticmethod

Python
map_profiles(cells, terrain_path: PathLike, output_folder: PathLike, *, profiles: Optional[Sequence[str]] = None, profile_prefix: str = DEFAULT_PROFILE_PREFIX, centers=None, hdf_path: Optional[PathLike] = None, mesh_name: Optional[str] = None, output_crs: Any = 'EPSG:3857', output_resolution: float = 3.0, bbox: Optional[Sequence[float]] = None, polygon: Any = None, polygon_layer: Optional[str] = None, aoi_crs: Any = None, aoi: Optional[FimAoi] = None, engine_path: Optional[PathLike] = None, threads: Optional[int] = None, profiles_per_request: int = 4, max_inflight_profiles: int = 1, max_cache_mib: int = 64, max_profile_mib: int = 1024, nudge_method: str = 'lookup', grid_anchor: str = 'ras2fim', coplanar: str = 'error', terrain_crs_fnv1a64: Optional[str] = None, write_floodplain: bool = True, keep_work: bool = False, timeout: Optional[float] = None, raise_on_failure: bool = True) -> pd.DataFrame

Map a batch of cell WSE profiles to depth and WSE rasters.

This is the triangulated ras2fim-2D Step 05 method. It can produce different wet extents from native horizontal cell filling. Use :meth:map_horizontal_profiles when cell-constant horizontal WSE is the intended mapping method; changing a grid anchor does not change triangulation into cell filling.

Every profile shares one terrain and one engine session per request of profiles_per_request profiles. Sample preparation, Delaunay topology, query axes and the wet mask always use every wet cell of a profile. An AOI only selects pixels of the final output grid, so an AOI product equals the crop of the full product. The preparation cost therefore does not shrink with the AOI.

Parameters:

Name Type Description Default
cells GeoDataFrame

Cell polygons with cell_idx and WSE profile columns (NaN = dry), in the terrain CRS. Not modified.

required
terrain_path PathLike

Single-band terrain GeoTIFF, same CRS as cells. Its pixel width is the interpolation pixel size.

required
output_folder PathLike

New or empty folder for products and the manifest.

required
profiles Optional[Sequence[str]]

Profile columns to map. Default: columns starting with profile_prefix.

None
centers GeoDataFrame

Unique integer cell_idx and centre points. Give either centers or hdf_path.

None
hdf_path Optional[PathLike]

Plan or geometry HDF; centres are read through :meth:get_cell_centers.

None
mesh_name Optional[str]

2D flow area for hdf_path (required for several).

None
output_crs Any

CRS of the final grid. One without an EPSG code needs an engine whose step05_r2 advertises crs_any (sent as WKT).

'EPSG:3857'
output_resolution float

Final pixel size in output_crs units.

3.0
bbox Optional[Sequence[float]]

Bounding box; without aoi_crs it is in output_crs.

None
polygon Any

Polygon area of interest; see :meth:resolve_aoi.

None
polygon_layer Optional[str]

Layer name for a polygon file.

None
aoi_crs Any

CRS of the area of interest.

None
aoi Optional[FimAoi]

A :class:FimAoi from :meth:resolve_aoi (instead of the bbox/polygon arguments).

None
engine_path Optional[PathLike]

Engine executable; see :meth:find_engine.

None
threads Optional[int]

Engine threads. Default min(cpu_count - 1, 16).

None
profiles_per_request int

Profiles prepared and run per engine call. This bounds the prepared inputs on disk at one time.

4
max_inflight_profiles int

Profiles the engine evaluates concurrently within one call (default 1). Concurrent profiles share one decoded-terrain cache and the threads pool; each counts against max_profile_mib.

1
max_cache_mib int

Engine decoded-terrain cache budget.

64
max_profile_mib int

Engine per-profile working-set budget; a profile whose planned peak exceeds it fails before allocation.

1024
nudge_method str

"lookup" (one full-grid index warp, AOI pixels gathered from it) or "full_warp".

'lookup'
grid_anchor str

"ras2fim" (default, the upstream grids: query axes from the wet-union bounds, final origin snapped to a multiple of output_resolution) or "terrain": both grids on the terrain pixel lattice, so each pixel takes the terrain pixel it lies on and products stack with the terrain. Needs a north-up terrain with square pixels, output_crs equal to the results CRS and output_resolution equal to the terrain pixel size. Not the upstream Step 05 grid.

'ras2fim'
coplanar str

"error" (default) fails a profile whose samples include points Qhull reports as coplanar or duplicate; "ignore" maps it without them, as upstream griddata does, and records the count in the manifest.

'error'
terrain_crs_fnv1a64 Optional[str]

Engine WKT hash to accept when the engine cannot identify the terrain EPSG code.

None
write_floodplain bool

Write product 11.

True
keep_work bool

Keep the engine requests and raw outputs in output_folder/.fim_work for review.

False
timeout Optional[float]

Seconds allowed per engine call (default no limit).

None
raise_on_failure bool

Raise :class:FimMappingError when any profile fails (default). The manifest is written first either way.

True

Returns:

Type Description
DataFrame

DataFrame with one row per profile (fim_product_manifest

DataFrame

schema). status is complete, no_flooded_pixels,

DataFrame

empty_aoi, failed, or not_run (a fatal engine error

DataFrame

stopped the batch sequence). The manifest is also written to

DataFrame

fim_manifest.json before any error is raised.

Raises:

Type Description
FimEngineNotFoundError

No engine executable.

FimEngineError

The engine rejected a request or crashed.

FimUnsupportedError

Input outside the engine contract.

FimAoiError

Invalid area of interest.

FimMappingError

One or more profiles failed.

FileExistsError

output_folder is not empty.

map_ras2fim_results staticmethod

Python
map_ras2fim_results(results_gpkg: PathLike, hdf_path: PathLike, terrain_path: PathLike, output_folder: PathLike, **kwargs) -> pd.DataFrame

Map every wsel_* profile of a ras2fim-2D hydraulic-results GeoPackage.

Reads layer 02_cells_wsel_ar, takes cell centres from hdf_path, and calls :meth:map_profiles with kwargs.

FimCapabilities dataclass

Read-only engine identity and method registry, including the untouched raw record.

supports

Python
supports(key: str, *, flag: Optional[str] = None) -> bool

Query advertised presence or a truthy flag, without implying qualification.

Parameters:

Name Type Description Default
key str

Engine registry key, such as sloping.

required
flag Optional[str]

Optional field in that method's raw flags. Missing, false or empty flags return False; nonempty structured controls count as advertised.

None

Returns:

Type Description
bool

Whether the requested method/flag is advertised. Inspect

bool

api_contract and numerical_qualification separately.

FimMethodSupport dataclass

An advertised method; its presence does not establish native parity.

Legacy engines can omit a method ID, CLI/schema declarations or stability. Such fields remain None/empty/not_declared rather than being guessed. All nested metadata is copied into read-only mappings and tuples.

qualification_status property

Python
qualification_status: str

Return the explicitly normalized numerical status, independent of API stability.

qualified_scope property

Python
qualified_scope: Tuple[str, ...]

Return declared textual scopes; this is not a universal qualification claim.

FimModelScope dataclass

Dimensional evidence, without executing a mapping method.

methods lists candidate engine registry keys for the dimension. It does not establish installed capabilities, preparation support or qualification.

to_dict

Python
to_dict()

Return detached JSON-friendly evidence, including legacy count keys.

A validated bounding-box or polygon area of interest.

Attributes:

Name Type Description
kind str

"bbox" or "polygon".

geometry Any

Shapely box, Polygon, or MultiPolygon in crs. Holes and multiple parts are kept.

crs Any

:class:pyproj.CRS of geometry.

source str

Human-readable origin, recorded in the product manifest.

describe

Python
describe() -> dict

Return a JSON-serializable summary.

Global interpolation inputs for one WSE profile.

Attributes:

Name Type Description
profile str

Profile (column) name.

x, (y, z)

Sample coordinates and WSE in upstream order (wet centres, then merged hull-exterior vertices).

x_axis, y_axis

Exact np.arange query axes. The effective step can differ from res in the last bits.

xmin, (ymin, res)

Raster-01 origin and pixel size.

wet_union Any

Shapely union of the wet cell polygons.

crs Any

CRS of the hydraulic results (and of all coordinates above).

wet_cell_count int

Number of wet cells (centres) used.

grid_anchor str

"ras2fim" (origin at the wet-union bounds, upstream) or "terrain" (origin snapped down onto the terrain lattice).

lattice_origin Optional[Tuple[float, float]]

Terrain pixel corner of a terrain-anchored profile.

lattice_index Optional[Tuple[int, int]]

Integer (column, row) lattice index of (xmin, ymin) from lattice_origin; edges are always origin + k * res.

shape property

Python
shape: Tuple[int, int]

(rows, cols) of the raster-01 grid.

Reusable sloping inputs created by :meth:RasFim.prepare_sloping_model.

Use a context manager or call :meth:close to release staged files and geometry. Calls on one context are serialized. Capable engines retain one owned process, geometry, terrain blocks and a bounded output/weight cache. Capable engines share bounded reconstructed timestep state across reaches. Metadata is returned by copy.

info property

Python
info: dict

Copy of preparation timing, fixed selectors and planned cache ceilings.

closed property

Python
closed: bool

Whether this context has released its retained inputs.

map_profiles

Python
map_profiles(output_folder, *, profiles=None, bbox=None, polygon=None, polygon_layer=None, aoi_crs=None, writer_threads=1, max_inflight_profiles=1, max_working_mib=None, timeout=None, write_floodplain=False, template_raster=None, invalid_cells=None, product_writer='rasterio', row_stream_rows=0, final_format=None)

Map all prepared names or an ordered subset into a new/empty folder.

profiles is a sequence of prepared names, not timestep selectors. Bounding boxes and polygons constrain output pixels, preserving complete model connectivity. Working memory and concurrency use the same planned admission as RasFim.map_sloping_profiles. The returned manifest's performance includes a copy of preparation evidence; its total time covers this call only. No additional depth cutoff is applied. max_working_mib=None inherits the factory budget. Source changes close the context; invalid profile names leave it usable. invalid_cells is fixed at preparation; None or the prepared policy is accepted and any other value raises ValueError. product_writer="native" requires native_geotiff_outputs and writes lossless LZW TIFFs through terrio without raster-array pipe transfers. It excludes templates, floodplain polygonization and velocity. The default "rasterio" preserves the existing delivery path. Native compression uses one worker; writer_threads controls Rasterio only. final_format has the :meth:RasFim.map_sloping_profiles contract. row_stream_rows has the same opt-in native plain-sloping contract as RasFim.map_sloping_profiles; zero keeps full-array rendering.

close

Python
close() -> None

Release staged files and geometry; safe to call repeatedly.

FimPreparedOneDModel dataclass

Receipt-bound staged global geometry; use with map_one_d_profiles.

Source and payload hashes are rechecked before each mapping call.

validate

Python
validate(threads=1)

Recheck the receipt, hashes, grid, CRS and units of the bound inputs.

threads bounds concurrent file hashing (at most 8).

map_profiles

Python
map_profiles(output_folder, *, profiles=None, allow_unqualified=False, bbox=None, polygon=None, polygon_layer=None, aoi_crs=None, engine_path=None, threads=1, max_working_mib=1024, timeout=None, raise_on_failure=True, final_format=None)

Map prepared profile names into a new or empty output folder.

profiles is an ordered sequence of prepared names, following the prepared sloping API. None selects all names. AOIs preserve the complete source geometry and terrain grid; preparation remains unqualified.

FimPreparedCoupledModel dataclass

Immutable global mixed inputs created only by prepare_coupled_model.

Source, engine, receipt and payload hashes are rechecked for every mapping and before/after whole-batch publication. Reconstructed instances refuse.

map_profiles

Python
map_profiles(output_folder, *, profiles=None, allow_unqualified=False, bbox=None, polygon=None, polygon_layer=None, aoi_crs=None, engine_path=None, threads=1, max_working_mib=1024, timeout=None, raise_on_failure=True)

Map prepared profile names into a new or empty output folder.

profiles is an ordered sequence of prepared names, following the prepared sloping API. None selects all names. AOIs preserve the complete source geometry and terrain grid; preparation remains unqualified.