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:
Project Management¶
init_ras_project¶
init_ras_project
¶
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
>>> # 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 | |
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
¶
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
¶
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. |
get_boundary_conditions
¶
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
>>> 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
¶
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. |
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
>>> 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
¶
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
Note: This is useful for identifying which plans have been successfully computed and can be used for further results analysis.
get_hdf_paths
¶
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) |
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. |
get_plan_info
¶
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 |
get_plan_value
staticmethod
¶
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
¶
get_plans_without_results
¶
get_prj_entries
¶
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
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
¶
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. |
get_project_units
staticmethod
¶
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
¶
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
¶
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. |
initialize
¶
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
¶
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. |
refresh_project_crs
¶
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
¶
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 |
update_results_df
¶
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 |
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.
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
¶
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
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.
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
¶
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 | |
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
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.
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
¶
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, |
required |
ras_object
|
RasPrj
|
Initialized :class: |
None
|
timeout_seconds
|
float
|
Grace period before force-killing only the already matched processes. |
10.0
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
cancel_plan_exact
staticmethod
¶
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
¶
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].
|
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_failurerecords 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
¶
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
|
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 |
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 |
None
|
hdf_output_profile
|
str
|
Named HDF output profile to apply before
execution. Equivalent to |
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
|
disable_omp_affinity
|
bool
|
Set Intel |
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 |
ValueError
|
If |
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)
Run with recommended HDF write parameters¶
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_runtimewhile 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
¶
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) —
RasUnsteadyinras_exe_dirwith alibs/tree (libs/,libs/mkl/,libs/rhel_8/) beside it, in its parent, or — for HEC's 6.1RAS_Linux_test_setup/Ras_v61/Releaselayout — two levels up. When bothlibs/rhel_8andlibs/centos_7exist onlyrhel_8is used, matching HEC'srun_unsteady.sh. - bin_ras (5.0.7) —
bin_ras/rasUnsteady64with libraries colocated inbin_ras/(nolibs/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_THREADSstill carrynum_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 |
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+ ( |
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 |
compute_test_mode
staticmethod
¶
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].
|
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
¶
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 |
required |
ras_object
|
RasPrj
|
Explicit initialized :class: |
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
|
registry and JSON-serializable |
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
¶
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
¶
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 |
required |
ras_exe_dir
|
Union[str, Path]
|
Directory containing the |
required |
ras_object
|
RasPrj
|
Optional RAS project object. If None, uses global |
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
|
|
ComputeResult
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the |
remove_plan_execution_artifacts
staticmethod
¶
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 |
required |
result_format
|
RemovalFormat
|
Required selection: |
required |
include_message_sidecars
|
bool
|
Also remove the plan's exact
|
False
|
ras_object
|
RasPrj
|
Explicit initialized :class: |
None
|
Returns:
| Type | Description |
|---|---|
Immutable
|
class: |
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 | |
|---|---|
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 | |
to_dict
¶
Return a JSON-serializable evidence record without message text.
Source code in ras_commander/ExecutionEvidence.py
EvidenceObservation
dataclass
¶
Bases: Generic[T]
One typed execution observation with explicit state and provenance.
Source code in ras_commander/ExecutionEvidence.py
to_dict
¶
Return a JSON-serializable observation record.
Source code in ras_commander/ExecutionEvidence.py
PlanExecutionCleanup
dataclass
¶
Audit record returned after exact, permanent artifact removal.
Source code in ras_commander/ExecutionArtifacts.py
to_dict
¶
Return a JSON-safe representation for execution audit records.
Source code in ras_commander/ExecutionArtifacts.py
PlanExecutionCleanupError
¶
Bases: RuntimeError
Raised when exact cleanup fails after reporting any partial removal.
Source code in ras_commander/ExecutionArtifacts.py
ResultArtifactAmbiguityError
¶
Bases: RuntimeError
Raised when coexisting result formats cannot be read safely.
Source code in ras_commander/ExecutionArtifacts.py
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.
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:
[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:
on_prep_start(plan_number)- Before plan setup, including requested preprocessor-file clearing and core settingson_prep_complete(plan_number)- After plan setup; engine preprocessing may still be requiredon_exec_start(plan_number, command)- Immediately before launching the HEC-RAS subprocesson_exec_message(plan_number, message)- Each .bco file message (real-time)on_exec_complete(plan_number, success, duration)- After executionon_verify_result(plan_number, verified)- After HDF verification (ifverify=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
__init__
¶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
on_exec_start
¶Print execution start message.
Source code in ras_commander/callbacks.py
| Python | |
|---|---|
on_exec_message
¶Print execution messages (if verbose mode enabled).
on_exec_complete
¶Print execution completion message.
Source code in ras_commander/callbacks.py
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
__init__
¶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
on_exec_start
¶Open log file for this plan.
Source code in ras_commander/callbacks.py
on_exec_message
¶Write message to plan's log file.
Source code in ras_commander/callbacks.py
on_exec_complete
¶Write completion message and close log file.
Source code in ras_commander/callbacks.py
__del__
¶
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
__init__
¶Initialize progress bar callback.
Source code in ras_commander/callbacks.py
on_exec_start
¶Create progress bar for this plan.
on_exec_message
¶Update progress bar with new message.
Source code in ras_commander/callbacks.py
on_exec_complete
¶Close progress bar and display final status.
Source code in ras_commander/callbacks.py
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
__init__
¶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
on_prep_start
¶Thread-safe wrapper for on_prep_start.
on_prep_complete
¶Thread-safe wrapper for on_prep_complete.
on_exec_start
¶Thread-safe wrapper for on_exec_start.
on_exec_message
¶Thread-safe wrapper for on_exec_message.
on_exec_complete
¶Thread-safe wrapper for on_exec_complete.
Source code in ras_commander/callbacks.py
on_verify_result
¶Thread-safe wrapper for on_verify_result.
Source code in ras_commander/callbacks.py
Custom Callbacks¶
Create custom callbacks by implementing the ExecutionCallback protocol:
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 | |
preprocess_plan
staticmethod
¶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 |
6
|
precipitation_repair_timeout
|
Optional[int]
|
Seconds allowed for each repair
attempt. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
PreprocessResult
|
Result with success flag, file paths, and timing.
Bool-compatible: |
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 | |
|---|---|
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 | |
run_ras_geom_preprocess
staticmethod
¶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 |
required |
ras_object
|
RasPrj
|
Initialized :class: |
None
|
input_hdf_path
|
Optional[Union[str, Path]]
|
Optional explicit plan |
None
|
x_file_path
|
Optional[Union[str, Path]]
|
Optional explicit project |
None
|
executable_path
|
Optional[Union[str, Path]]
|
Optional explicit |
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 | |
|---|---|
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 | |
verify_preprocessing
staticmethod
¶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 | |
|---|---|
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 | |
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 | |
|---|---|
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 | |
enable_detailed_logging
staticmethod
¶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
monitor_until_signal
¶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 | |
|---|---|
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 | |
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 | |
|---|---|
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 | |
on_prep_start
¶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
on_prep_complete
¶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
on_exec_start
¶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
on_exec_message
¶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.
Source code in ras_commander/ExecutionCallback.py
on_exec_complete
¶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
on_verify_result
¶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
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
¶
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 |
force_cleanup_all
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
**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
¶
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.
**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:
>>> 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:
>>> 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:
>>> 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
¶
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
¶
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 |
run_plan
staticmethod
¶
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 |
True
|
blocking
|
bool
|
For modern Controllers, pass the blocking flag to
|
False
|
controller_version
|
Optional[str]
|
Optional exact Controller product identity.
Use |
None
|
strict_close
|
bool
|
Require the resolved Controller's safe-close
contract after an otherwise successful operation. For HEC-RAS
5+, a |
False
|
observe_dialogs
|
bool
|
Opt in to exact Controller dialog observation before
|
False
|
Returns:
| Type | Description |
|---|---|
RasControlResult
|
Result object backward compatible with Tuple[bool, List[str]].
|
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)
Disable watchdog (not recommended in Jupyter)¶
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
¶
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
¶
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:
# 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:
- First tries
.computeMsgs.txt(modern format) - Falls back to
.comp_msgs.txt(legacy format) - Returns empty string if neither exists
File Operations¶
RasPlan¶
A class for operations on HEC-RAS plan files.
add_hdf_output_variable
staticmethod
¶
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 ( |
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
¶
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'
|
additional_variables
|
Optional[List[str]]
|
Optional additional HDF output variables to enable. |
None
|
ras_object
|
RasPrj
|
Optional RAS project object. If None, uses global |
None
|
target_ras_version
|
str, float, or Path
|
HEC-RAS version
that will run the plan ( |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True when all requested updates succeeded. |
clone_geom
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Parsed options with |
get_flow_path
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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 |
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Optional[Any]]
|
Parsed restart-output settings, including raw HEC-RAS keys for auditability. |
get_results_path
staticmethod
¶
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
¶
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the plan file is not found. |
get_shortid
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
|
list_hdf_output_setting_profiles
staticmethod
¶
List named HDF write-parameter profiles.
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[str, Any]]
|
Profile names mapped to write parameters. |
read_flow_description
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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]
|
|
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 |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True when the plan file was updated or already matched. |
set_2d_flow_options
staticmethod
¶
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]]
|
|
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 |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True when the plan file was written or already matched. |
set_geom
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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 |
None
|
ras_object
|
RasPrj
|
Optional RAS project object. If None, uses global |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True when the plan file was updated, False on error. |
set_num_cores
staticmethod
¶
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
¶
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
¶
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 |
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 |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True when the plan file was updated or already current. |
set_sediment_output_variables
staticmethod
¶
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::
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. |
required |
output_level
|
Optional[int]
|
If provided, set |
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, |
set_shortid
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
|
|
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: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
New plan number. |
disable_plan
staticmethod
¶
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
¶
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
¶
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 ( |
required |
ras_object
|
RasPrj
|
Optional RAS project object. If None, uses global
|
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with normalized keys including |
Dict[str, Any]
|
|
get_trial_results
staticmethod
¶
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
¶
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
¶
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 |
set_settings
staticmethod
¶
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
|
|
required |
reference_location
|
str
|
Existing HEC-RAS reference point/line name. A
full value such as |
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
|
user_selected_hydrographs
|
Optional[bool]
|
Override the native user-selected flag.
Defaults to |
None
|
restart_approach
|
Optional[str]
|
Optional restart approach. Accepted shorthands:
|
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
|
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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 |
extract_tables
staticmethod
¶
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
¶
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
¶
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:
- ``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
¶
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
¶
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:
- ``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
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Initial flow, storage/2D elevation, and RRR elevation entries from the unsteady file. |
get_initial_flow_method
staticmethod
¶
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
¶
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
¶
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
¶
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.
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
¶
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, |
Dict[str, Optional[Any]]
|
|
Dict[str, Optional[Any]]
|
sidecar HDF (empty dict if no sidecar exists). |
get_meteorological_stations
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Optional[Any]]
|
Parsed usage settings and raw values. |
get_rules_bc
staticmethod
¶
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
¶
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
¶
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).
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
¶
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
¶
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 |
inspect_boundary_blocks
staticmethod
¶
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
¶
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 |
preview_dss_references
staticmethod
¶
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
¶
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 |
read_unsteady_description
staticmethod
¶
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
¶
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.
set_boundary_dss_link
staticmethod
¶
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.
Parameters¶
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.
Returns¶
bool True if boundary was successfully updated, False if not found
Raises¶
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.
Example¶
from ras_commander import RasUnsteady
Link a boundary to DSS¶
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
¶
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:
- ``'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:
- Sets
Use DSS=False - Removes
DSS File=andDSS Path=content (sets to empty) - Writes inline data after the hydrograph header line
- 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
¶
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
¶
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 afterStage 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:
- ``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
¶
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 afterStage Hydrograph TW Check=if present, otherwise immediately before the first DSS metadata line (DSS Path=,DSS File=, orUse 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_lineis 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:
- ``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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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, |
None
|
ras_object
|
Optional[Any]
|
Optional RAS project object. If None, uses global |
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 |
set_ic_from_output_profile
staticmethod
¶
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
¶
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:
* ``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
¶
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
¶
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
¶
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:
- ``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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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 unlessuse_critical_fallback=Trueforces the flag to be present and set to1. - 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) whenuse_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 ofBoundary Location=.(area_2d, bc_line)for a 2D BC line attached to a 2D Flow Area, matched on theBoundary Location=2D Flow Area name (field index 5) and the BC line / SA name (field index 7). For Normal Depth,bc_lineis 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:
- ``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
¶
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
¶
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
¶
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
¶
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:
- ``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
¶
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
¶
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
¶
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
¶
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
¶
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 afterFlow 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:
- ``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
¶
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:
- ``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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
Return a critical-depth boundary specification.
known_water_surface
staticmethod
¶
Return a known-water-surface boundary specification.
normal_depth
staticmethod
¶
Return a normal-depth boundary specification.
rating_curve
staticmethod
¶
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
¶
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 |
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 |
dict[str, Any]
|
|
dict[str, Any]
|
|
update_flow_file
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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/
Returns:
| Type | Description |
|---|---|
Dict[str, Path]
|
Mapping of version string -> Path to the executable. |
Dict[str, Path]
|
On Windows/Wine this is |
Dict[str, Path]
|
is no Ras.exe, so it maps to the |
Dict[str, Path]
|
|
Example
|
{"6.6": Path("C:/Program Files (x86)/HEC/HEC-RAS/6.6/Ras.exe")} |
dos2unix
staticmethod
¶
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
¶
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
¶
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
¶
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
¶
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]]]
|
|
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
- Verify backup file exists
- Copy backup -> original (preserves backup for safety)
- 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
¶
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 |
safe_write_geometry
staticmethod
¶
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
- Create timestamped backup: geom_file.YYYYMMDD_HHMMSS.bak
- Write to temp file: geom_file.tmp
- Basic validation (line count reasonable, file size reasonable)
- Atomic rename temp -> original (os.replace)
- 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
¶
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 |
{}
|
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
¶
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
¶
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
¶
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
¶
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²) |
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 |
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
¶
Remove all extracted projects from the example_projects directory.
download_fema_ble_model
classmethod
¶
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
¶
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
¶
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
¶
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
¶
Return registry metadata for a ScienceBase model slug or alias.
inspect_sciencebase_model
classmethod
¶
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
¶
Check if a specific project is already extracted.
list_projects
classmethod
¶
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
¶
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
¶
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
¶
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.
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.
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.
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.
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¶
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¶
# 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¶
# 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.
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:
# 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
¶
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
¶
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
¶
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
¶
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
¶
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 |
dict
|
|
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
¶
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
¶
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 |
'FimPreparedSlopingModel'
|
|
'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
¶
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 |
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
|
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'
|
allow_unqualified
|
bool
|
Required for |
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'
|
|
'pd.DataFrame'
|
ignoring ring start, orientation and part order; collinear vertices |
'pd.DataFrame'
|
remain significant. |
'pd.DataFrame'
|
|
'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
¶
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;
|
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
( |
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'
|
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
¶
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 |
None
|
wsel_profiles
|
Optional[DataFrame]
|
Optional complete cell-keyed WSEL table, mutually
exclusive with profiles. Requires physical and ghost rows in
every mesh. See |
None
|
render_mode
|
str
|
|
'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 |
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'
|
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 |
0
|
final_format
|
Optional[Dict[str, Any]]
|
|
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,
|
None
|
velocity
|
bool
|
Also render velocity magnitude ( |
False
|
velocity_depth
|
str
|
|
'rendered'
|
derived_products
|
Sequence[str]
|
Per-profile products from the clipping depth and
velocity: |
()
|
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'
|
terrain_crs_fnv1a64
|
Optional[str]
|
Engine WKT hash to accept when the engine
cannot identify the terrain EPSG code, as in
:meth: |
None
|
shear_stress
|
bool
|
Also render RAS Mapper's Max shear stress
( |
False
|
shear_depth
|
str
|
|
'rendered'
|
storage_areas
|
bool
|
Also draw the plan's standalone storage areas as
RAS Mapper level pools ( |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
and |
DataFrame
|
Supplied vectors add |
DataFrame
|
per-mesh/profile hashes for rendered requests. |
DataFrame
|
|
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
|
|
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
¶
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
¶
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
¶
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: |
required |
output_folder
|
PathLike
|
New or empty directory. |
required |
products
|
Sequence[str]
|
Subset of |
('depth_x_velocity', 'depth_x_velocity_squared', 'froude')
|
render_mode
|
str
|
|
'sloping'
|
velocity_depth
|
str
|
|
'rendered'
|
reduce_shallow_to_horizontal
|
bool
|
slopingPretty shallow reduction, as in
:meth: |
False
|
use_depth_weighted_faces
|
bool
|
slopingPretty depth-weighted faces, as in
:meth: |
False
|
postprocessing_hdf
|
Optional[PathLike]
|
Optional |
None
|
bbox
|
Optional[Sequence[float]]
|
Optional output bounds in |
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: |
None
|
invalid_cells
|
str
|
Invalid-cell ownership policy. |
'repair'
|
terrain_crs_fnv1a64
|
Optional[str]
|
Engine WKT hash, as for :meth: |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with one row per product ( |
DataFrame
|
|
DataFrame
|
hold the evidence, |
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
¶
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
|
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
applies), |
Dict[str, Any]
|
|
``modifications``, ``rasmap_checked`` and ``rasmap_warnings``
|
a |
Dict[str, Any]
|
list of |
Dict[str, Any]
|
code |
Dict[str, Any]
|
group under another name (RAS Mapper ignores it; rename it to |
Dict[str, Any]
|
|
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 |
supports_effective_terrain
staticmethod
¶
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
staticmethod
¶
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 |
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 |
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 |
None
|
hecras_version
|
Optional[str]
|
HEC-RAS release whose export the modifications
reproduce (for example |
None
|
ras_object
|
Any
|
Optional initialized RAS project whose HEC-RAS
version selects |
None
|
basis
|
str
|
|
'export'
|
Returns:
| Type | Description |
|---|---|
dict
|
Receipt with |
Dict[str, Any]
|
|
Dict[str, Any]
|
engines), |
Dict[str, Any]
|
an unmodified terrain), |
Dict[str, Any]
|
|
``rasmap_warnings`` (as for
|
meth: |
Dict[str, Any]
|
|
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
¶
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
|
|
required |
engine_path
|
Optional[PathLike]
|
Engine executable, otherwise environment/PATH. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
The basis is available. |
read_terrain_modifications
staticmethod
¶
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: |
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 |
None
|
ras_object
|
Any
|
Optional initialized RAS project. Its HEC-RAS version
and project file take precedence over |
None
|
hecras_version
|
Optional[Any]
|
HEC-RAS release whose export the layers reproduce,
for example |
None
|
length_units
|
Optional[str]
|
RAS Mapper unit system, |
None
|
strict
|
bool
|
Raise :class: |
False
|
engine_path
|
Optional[PathLike]
|
Optional engine executable whose advertised
|
None
|
Returns:
| Type | Description |
|---|---|
dict
|
A |
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/Modificationsgroup, or only layers and features RAS Mapper skips) or"refused".statusdescribes the HDF layers only, not whether RAS Mapper applies them: it applies none unless the rasmap terrain layer has anElevationModificationGroupnamedModifications. Use :meth:top_priority_terrain_source["modified"]before treatinglayersas applied, or passrasmap_pathand checkwarnings:modification_group_missingmeans nothing is applied;modification_group_misnamedmeans that group's entries are ignored, and nothing is applied only when no group is namedModifications.refusal(str or None): For"refused", the reason the terrain cannot take the native route, naming the layer and feature; otherwiseNone.refusal_reason(str or None): The stable reason code of the refusal, copied from thereasonattribute of the reader's :class:FimUnsupportedError(for example"multi_ring_polygon"or"unqualified_hecras_version");Nonewhen the refusal has no code or there is no refusal. Match on this code rather than on therefusaltext.hecras_version(str or None): The engine rule,"7.0.1","6.6"or"6.7";Nonewhen 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";Nonewhen 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 withoutrasmap_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 namedModifications),"rasmap_layer_not_in_hdf"(theModificationsgroup lists layers the HDF does not store; :meth:build_effective_terrainrefuses the terrain) and"rasmap_not_checked"(the rasmap cannot be read or does not register this terrain). Warnings do not changestatus.-
layers(list of dict): Engine request layers in HDF order (empty unless"staged"). Layerpriorityis the HDFPriority(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_percentin percent; ellipserotationin degrees. NaN template values areNone. Bykind: -
"ground_line":name,priority,subtype("levee"or"channel"),length_units, optionalcontrol_points({"x", "y", "elevation"}dicts; a NaN elevation isNone) andfeatureswithelevation_type(SetValue,SetIfHigher,SetIfLower,Add),top_width,left_slope,right_slope,max_reach,points([x, y]),profile([station, elevation]),system_name,transition_percentandelev_pt_tolerance. "polygon":name,priority,length_units, optionalcontrol_pointsandfeatureswithelevation_type(as ground lines),elevation,rings([[x, y], ...]per part),generate_boundary,use_shape_z,profile,elev_pt_toleranceand, withuse_shape_z,vertex_z."ellipse":name,priorityandfeatureswithelevation_type(SetValue,SetIfHigher,SetIfLower),elevation,center([x, y]),radius_x,radius_yandrotation.
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 |
ValueError
|
|
OSError
|
The terrain HDF does not exist or cannot be opened. |
map_whole_simulation
staticmethod
¶
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 advertisingduration_rulerasmapper-backward-window-recession/1; older engines needallow_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 |
required |
output_folder
|
PathLike
|
New or empty folder for |
required |
products
|
Sequence[str]
|
Any of |
('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
|
False
|
terrain_hdf
|
Optional[PathLike]
|
Optional registered terrain HDF whose unmodified
priority-1 source TIFF is |
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: |
None
|
invalid_cells
|
str
|
Pixel ownership for cells whose face polylines do
not form a valid polygon, as in :meth: |
'repair'
|
storage_areas
|
bool
|
Also accumulate the plan's standalone storage areas
as level pools ( |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
with |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
MeshCellPolygonError
|
|
FimUnsupportedError
|
Duration without |
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
¶
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 |
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 |
None
|
profile_prefix
|
str
|
Prefix for selecting profile columns. |
DEFAULT_PROFILE_PREFIX
|
bbox
|
Optional[Sequence[float]]
|
Output constraint in |
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: |
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,
|
None
|
invalid_cells
|
str
|
Policy for cells whose face polylines do not form
a valid polygon, as in :meth: |
'repair'
|
storage_areas
|
Optional[Dict[str, Union[str, int]]]
|
Optional mapping of every mapped profile column
to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
MeshCellPolygonError
|
|
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
¶
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: |
'repair'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
Return the engine path and its method record (ras2fim-batch method).
get_cells_from_results_gpkg
staticmethod
¶
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
¶
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
|
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
¶
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
|
resolve_aoi
staticmethod
¶
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]]
|
|
None
|
polygon
|
Any
|
A Shapely Polygon/MultiPolygon (needs |
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 |
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
¶
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
¶
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 |
required |
terrain_path
|
PathLike
|
Single-band terrain GeoTIFF, same CRS as |
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
|
None
|
centers
|
GeoDataFrame
|
Unique integer |
None
|
hdf_path
|
Optional[PathLike]
|
Plan or geometry HDF; centres are read through
:meth: |
None
|
mesh_name
|
Optional[str]
|
2D flow area for |
None
|
output_crs
|
Any
|
CRS of the final grid. One without an EPSG code needs an
engine whose |
'EPSG:3857'
|
output_resolution
|
float
|
Final pixel size in |
3.0
|
bbox
|
Optional[Sequence[float]]
|
Bounding box; without |
None
|
polygon
|
Any
|
Polygon area of interest; see :meth: |
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: |
None
|
engine_path
|
Optional[PathLike]
|
Engine executable; see :meth: |
None
|
threads
|
Optional[int]
|
Engine threads. Default |
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 |
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'
|
grid_anchor
|
str
|
|
'ras2fim'
|
coplanar
|
str
|
|
'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
|
False
|
timeout
|
Optional[float]
|
Seconds allowed per engine call (default no limit). |
None
|
raise_on_failure
|
bool
|
Raise :class: |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with one row per profile ( |
DataFrame
|
schema). |
DataFrame
|
|
DataFrame
|
stopped the batch sequence). The manifest is also written to |
DataFrame
|
|
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
|
|
map_ras2fim_results
staticmethod
¶
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
¶
Query advertised presence or a truthy flag, without implying qualification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Engine registry key, such as |
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
|
|
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.
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.
A validated bounding-box or polygon area of interest.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
|
geometry |
Any
|
Shapely box, Polygon, or MultiPolygon in |
crs |
Any
|
:class: |
source |
str
|
Human-readable origin, recorded in the product manifest. |
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 |
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
|
|
lattice_origin |
Optional[Tuple[float, float]]
|
Terrain pixel corner of a terrain-anchored profile. |
lattice_index |
Optional[Tuple[int, int]]
|
Integer |
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
¶
Copy of preparation timing, fixed selectors and planned cache ceilings.
map_profiles
¶
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.
FimPreparedOneDModel
dataclass
¶
Receipt-bound staged global geometry; use with map_one_d_profiles.
Source and payload hashes are rechecked before each mapping call.
validate
¶
Recheck the receipt, hashes, grid, CRS and units of the bound inputs.
threads bounds concurrent file hashing (at most 8).
map_profiles
¶
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
¶
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.