Core Classes¶
Core classes for HEC-RAS project management and execution.
Important Notes¶
Static Class Pattern
All primary classes use static methods - do NOT instantiate:
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
Most methods accept multiple input types via @standardize_input:
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) -> 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
|
Returns:
| Name | Type | Description |
|---|---|---|
RasPrj |
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 | |
|---|---|
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 | |
RasPrj¶
RasPrj
¶
RasPrj.py - Manages HEC-RAS projects within the ras-commander library
This module provides a class for managing HEC-RAS projects.
Classes:
| Name | Description |
|---|---|
RasPrj |
A class for managing HEC-RAS projects. |
Functions:
| Name | Description |
|---|---|
init_ras_project |
Initialize a RAS project. |
get_ras_exe |
Determine the HEC-RAS executable path based on the input. |
DEVELOPER NOTE: This class is used to initialize a RAS project and is used in conjunction with the RasCmdr class to manage the execution of RAS plans. By default, the RasPrj class is initialized with the global 'ras' object. However, you can create multiple RasPrj instances to manage multiple projects. Do not mix and match global 'ras' object instances and custom instances of RasPrj - it will cause errors.
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
To use logging in this module: 1. Use the @log_call decorator for automatic function call logging. 2. For additional logging, use logger.level calls (e.g., logger.info(), logger.debug()).
Example
@log_call def my_function():
logger.debug("Additional debug information")
# Function logic here
All of the methods in this class are class methods and are designed to be used with instances of the class.
List of Functions in RasPrj: - initialize() - _load_project_data() - _get_geom_file_for_plan() - _parse_plan_file() - _parse_unsteady_file() - _parse_flow_file() - _get_prj_entries() - _parse_boundary_condition() - is_initialized (property) - check_initialized() - find_ras_prj() - get_project_name() - get_prj_entries() - get_plan_entries() - get_flow_entries() - get_unsteady_entries() - get_geom_entries() - get_hdf_entries() - print_data() - get_plan_value() - get_boundary_conditions() - update_results_df() - get_results_entries()
Functions in RasPrj that are not part of the class:
- init_ras_project()
- get_ras_exe()
Plan Execution¶
RasCmdr¶
RasCmdr
¶
RasCmdr - Execution operations for running HEC-RAS simulations
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
To use logging in this module: 1. Use the @log_call decorator for automatic function call logging. 2. For additional logging, use logger.level calls (e.g., logger.info(), logger.debug()).
Example
@log_call def my_function():
logger.debug("Additional debug information")
# Function logic here
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasCmdr: - compute_plan() - compute_parallel() - compute_test_mode()
Real-Time Execution Monitoring (v0.88.0+)¶
The stream_callback parameter enables real-time progress monitoring during HEC-RAS execution:
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 geometry preprocessingon_prep_complete(plan_number)- After preprocessingon_exec_start(plan_number, command)- When HEC-RAS subprocess startson_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
|
on_exec_start
¶Print execution start message.
Source code in ras_commander/callbacks.py
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())
Thread Safety for Parallel Execution
Callbacks used with compute_parallel() must be thread-safe. Use threading.Lock for shared state:
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 |
int
|
Maximum wait time before timeout (default: 300) |
message_callback |
Optional[Callable[[str], None]]
|
Optional callback for new messages |
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 | |
|---|---|
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 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 | |
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:
| Name | Type | Description |
|---|---|---|
bool |
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:
| Name | Type | Description |
|---|---|---|
bool |
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
ExecutionCallback Protocol¶
ExecutionCallback
¶
ExecutionCallback - Protocol for HEC-RAS execution progress callbacks.
This module defines the callback interface for monitoring HEC-RAS computation lifecycle events. Callbacks enable real-time progress tracking, logging, and UI updates during long-running simulations.
The Protocol pattern allows partial implementation - classes only need to implement the callback methods they care about.
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 Order
- on_prep_start() - Before geometry preprocessing
- on_prep_complete() - After preprocessing
- on_exec_start() - HEC-RAS subprocess started
- on_exec_message() - During execution (potentially many calls)
- on_exec_complete() - HEC-RAS subprocess finished
- on_verify_result() - After HDF verification (if verify=True)
Thread Safety
When used with compute_parallel(), callbacks are invoked from worker threads concurrently. Implementations MUST be thread-safe. Use locks, thread-local storage, or atomic operations as needed.
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 | |
on_prep_start
¶Called before geometry preprocessing 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
May be called concurrently for different plans in compute_parallel().
Source code in ras_commander/ExecutionCallback.py
on_prep_complete
¶Called after geometry preprocessing and core setup complete.
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
May be called concurrently for different plans in compute_parallel().
Source code in ras_commander/ExecutionCallback.py
on_exec_start
¶Called when HEC-RAS subprocess starts.
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 command line (e.g., '"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
May be called concurrently for different plans in compute_parallel().
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
May be called concurrently for different plans in compute_parallel(). 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 is invoked immediately after subprocess completes (successfully or not).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan_number
|
str
|
Plan identifier (e.g., "01", "02") |
required |
success
|
bool
|
True if subprocess exited with code 0, False otherwise |
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
May be called concurrently for different plans in compute_parallel().
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 is the strongest guarantee that HEC-RAS succeeded
- verified=False may indicate computation errors or incomplete results
Thread Safety
May be called concurrently for different plans in compute_parallel().
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¶
RasControl
¶
RasControl - HECRASController API Wrapper (ras-commander style)
Provides ras-commander style API for legacy HEC-RAS versions (3.x-4.x) that use HECRASController COM interface instead of HDF files.
Includes robust process management with session tracking, orphan detection, and optional watchdog protection for Jupyter kernel restarts.
Public functions (HEC-RAS Operations): - RasControl.run_plan(plan, ras_object=None, force_recompute=False, use_watchdog=True, max_runtime=3600) -> Tuple[bool, List[str]] - RasControl.get_steady_results(plan, ras_object=None) -> pandas.DataFrame - RasControl.get_unsteady_results(plan, max_times=None, ras_object=None) -> pandas.DataFrame - RasControl.get_output_times(plan, ras_object=None) -> List[str] - RasControl.get_plans(plan, ras_object=None) -> List[dict] - RasControl.set_current_plan(plan, ras_object=None) -> bool - RasControl.get_comp_msgs(plan, ras_object=None) -> str
Public functions (Process Management): - RasControl.list_processes(show_all=False) -> pandas.DataFrame - RasControl.scan_orphans() -> List[SessionLock] - RasControl.cleanup_orphans(interactive=True, dry_run=False) -> int - RasControl.force_cleanup_all() -> int
Private functions: - _terminate_ras_process() -> None - _is_ras_running() -> bool - RasControl._normalize_version(version: str) -> str - RasControl._get_project_info(plan, ras_object=None) -> Tuple[Path, str, Optional[str], Optional[str]] - RasControl._com_open_close(project_path: Path, version: str, operation_func: Callable[[Any], Any]) -> Any
Session tracking infrastructure: - SessionLock dataclass - Tracks active COM sessions with lock files - Module-level _active_sessions dict - Tracks all active sessions - atexit handler - Emergency cleanup on Python exit - Watchdog support - Optional independent process for kernel restart protection
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¶
RasPlan
¶
RasPlan - Operations for handling plan files in HEC-RAS projects
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
To use logging in this module: 1. Use the @log_call decorator for automatic function call logging. 2. For additional logging, use logger.level calls (e.g., logger.info(), logger.debug()). 3. Obtain the logger using: logger = logging.getLogger(name)
Example
@log_call def my_function(): logger = logging.getLogger(name) logger.debug("Additional debug information") # Function logic here
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasPlan: - set_geom(): Set the geometry for a specified plan - set_steady(): Apply a steady flow file to a plan file - set_unsteady(): Apply an unsteady flow file to a plan file - set_num_cores(): Update the maximum number of cores to use - set_geom_preprocessor(): Update geometry preprocessor settings - clone_plan(): Create a new plan file based on a template - clone_unsteady(): Copy unsteady flow files from a template - clone_steady(): Copy steady flow files from a template - clone_geom(): Copy geometry files from a template - get_next_number(): Determine the next available number from a list - get_plan_value(): Retrieve a specific value from a plan file - get_results_path(): Get the results file path for a plan - get_plan_path(): Get the full path for a plan number - get_flow_path(): Get the full path for a flow number - get_unsteady_path(): Get the full path for an unsteady number - get_geom_path(): Get the full path for a geometry number - update_run_flags(): Update various run flags in a plan file - update_plan_intervals(): Update computation and output intervals - update_plan_description(): Update the description in a plan file - read_plan_description(): Read the description from a plan file - read_geom_description(): Read the description from a geometry file - update_geom_description(): Update the description in a geometry file - read_flow_description(): Read the description from a steady flow file - update_flow_description(): Update the description in a steady flow file - update_simulation_date(): Update simulation start and end dates - get_restart_output_settings(): Parse restart/Hot Start output settings - set_restart_output_settings(): Configure restart/Hot Start output settings - get_shortid(): Get the Short Identifier from a plan file - set_shortid(): Set the Short Identifier in a plan file - get_plan_title(): Get the Plan Title from a plan file - set_plan_title(): Set the Plan Title in a plan file - delete_plan(): Delete a plan and its associated files - renumber_plan(): Renumber a plan file and update references - delete_geom(): Delete a geometry file and its associated files - renumber_geom(): Renumber a geometry file and update references - delete_unsteady(): Delete an unsteady flow file - renumber_unsteady(): Renumber an unsteady flow file and update references - delete_steady(): Delete a steady flow file - renumber_steady(): Renumber a steady flow file and update references
RasFlowOptimization¶
RasFlowOptimization
¶
RasFlowOptimization - Native HEC-RAS flow hydrograph optimization helpers.
This module configures HEC-RAS Automated Flow Optimization using the native
Flow Ratio ... plan-file parameters and extracts trial summaries from HDF
results or computation messages after execution.
All methods are static and are designed to be used without instantiation.
RasGeo¶
RasGeo
¶
RasGeo - Operations for handling geometry files in HEC-RAS projects
DEPRECATION NOTICE
This class is deprecated and will be removed before v1.0. Please migrate to the new geometry subpackage classes: - GeomPreprocessor.clear_geompre_files() - replaces RasGeo.clear_geompre_files() - GeomLandCover.get_base_mannings_n() - replaces RasGeo.get_mannings_baseoverrides() - GeomLandCover.set_base_mannings_n() - replaces RasGeo.set_mannings_baseoverrides() - GeomLandCover.get_region_mannings_n() - replaces RasGeo.get_mannings_regionoverrides() - GeomLandCover.set_region_mannings_n() - replaces RasGeo.set_mannings_regionoverrides()
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasGeo: - clear_geompre_files(): Clears geometry preprocessor files for specified plan files [DEPRECATED] - get_mannings_baseoverrides(): Reads base Manning's n table from a geometry file [DEPRECATED] - get_mannings_regionoverrides(): Reads Manning's n region overrides from a geometry file [DEPRECATED] - set_mannings_baseoverrides(): Writes base Manning's n values to a geometry file [DEPRECATED] - set_mannings_regionoverrides(): Writes regional Manning's n overrides to a geometry file [DEPRECATED] - clone_geom(): Copy geometry files from a template with optional title and description
RasUnsteady¶
RasUnsteady
¶
RasUnsteady - Operations for handling unsteady flow files in HEC-RAS projects.
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
To use logging in this module: 1. Use the @log_call decorator for automatic function call logging. 2. For additional logging, use logger.level calls (e.g., logger.info(), logger.debug()).
Example
@log_call def my_function(): logger.debug("Additional debug information") # Function logic here
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasUnsteady: - update_flow_title() - read_unsteady_description() - update_unsteady_description() - update_restart_settings() - set_restart_settings() - get_restart_settings() - set_hydrograph_fixed_start_time() - extract_boundary_and_tables() - print_boundaries_and_tables() - identify_tables() - parse_fixed_width_table() - extract_tables() - write_table_to_file() - get_met_precipitation_config() - set_precipitation_hyetograph() - set_constant_precipitation() - set_gridded_precipitation() - configure_gridded_dss_precipitation() - set_meteorological_station() - get_meteorological_stations() - set_point_evapotranspiration() - get_point_evapotranspiration()
Precipitation Functions: - get_met_precipitation_config() - Read Meteorological Data tab precipitation settings - set_precipitation_hyetograph() - Write hyetograph DataFrame to unsteady file - set_gridded_precipitation() - Configure GDAL raster precipitation - configure_gridded_dss_precipitation() - Configure gridded DSS precipitation
Meteorological Point Data Functions: - set_meteorological_station() - Create/update meteorological station metadata - get_meteorological_stations() - Parse meteorological station metadata - set_point_evapotranspiration() - Write point ET series from a DataFrame - get_point_evapotranspiration() - Parse point ET series into a DataFrame
DSS Boundary Condition Functions:
- get_dss_boundaries() - Extract all DSS-linked BCs with full path info
- get_inline_hydrograph_boundaries() - Extract inline table BCs with time series data
- delete_boundary() - Remove one Boundary Location block from an unsteady file
- update_dss_run_identifier() - Update DSS path F-part for new scenarios
- set_boundary_dss_link() - Convert inline BC to DSS-linked (complete state transition)
- set_boundary_inline_hydrograph() - Write inline hydrograph, convert DSS to inline
- set_flow_hydrograph_slope() - Add or update Flow Hydrograph Slope= (EG slope) for a Flow Hydrograph BC
- set_normal_depth_boundary() - Add or update Normal Depth (Friction Slope=) for a 1D river or 2D BC line boundary
- get_unique_dss_subbasins() - Get unique HMS subbasin names from DSS paths
- update_dss_path_by_station() - Update DSS A-part for specific river station
- update_flow_multiplier_by_station() - Update/insert QMult for specific river station
- update_boundary_dss_paths() - Batch update DSS paths and multipliers
- get_rating_curve() - Read Rating Curve (stage, discharge) pairs from a boundary
- set_rating_curve() - Write or replace Rating Curve data on a boundary
Stage/Flow Hydrograph Functions (Internal Boundary): - get_stage_flow_hydrograph() - Read observed stage/flow pairs from an internal BC - set_stage_flow_hydrograph() - Write observed stage/flow pairs to an internal BC
Lateral Inflow Hydrograph Functions: - get_lateral_inflow_hydrograph() - Read lateral inflow hydrograph data from a boundary - set_lateral_inflow_hydrograph() - Write lateral inflow hydrograph data to a boundary
Uniform Lateral Inflow Hydrograph Functions: - get_uniform_lateral_inflow_hydrograph() - Read uniform lateral inflow data (reach-based BC) - set_uniform_lateral_inflow_hydrograph() - Write uniform lateral inflow data (reach-based BC)
Initial Conditions Method Selection: - get_initial_flow_method() - Determine which IC method is active (restart_file, prior_ws, initial_flow_distribution, none) - set_initial_flow_method() - Set the IC method selection (restart_file, prior_ws, initial_flow_distribution, none) - get_prior_ws_filename() - Read Prior WS Filename and Profile from unsteady file - set_prior_ws_filename() - Write Prior WS Filename and Profile to unsteady file
Initial Flow Distribution Table: - get_initial_conditions() - Read all IC entries (flow, storage, rrr) as DataFrame - set_initial_conditions() - Write IC entries from list of dicts or DataFrame (auto-sets IC method) - validate_initial_flow_stations() - Check IC flow stations match geometry cross sections
Non-Newtonian Method Selection: - get_non_newtonian_method() - Read the Non-Newtonian method integer and return name - set_non_newtonian_method() - Set the Non-Newtonian method by integer or name
RasSteady¶
RasSteady
¶
RasSteady - Read and author HEC-RAS steady flow files (.f##).
All methods are static and are designed to be used without instantiation.
Utilities¶
RasUtils¶
RasUtils
¶
RasUtils - Utility functions for the ras-commander library
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
To use logging in this module: 1. Use the @log_call decorator for automatic function call logging. 2. For additional logging, use logger.level calls (e.g., logger.info(), logger.debug()).
Example
@log_call def my_function(): logger.debug("Additional debug information") # Function logic here
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasUtils: - create_directory() - safe_resolve() - find_files_by_extension() - get_file_size() - get_file_modification_time() - normalize_ras_number() - get_plan_path() - remove_with_retry() - update_plan_file() - check_file_access() - convert_to_dataframe() - save_to_excel() - calculate_rmse() - calculate_percent_bias() - calculate_error_metrics() - update_file() - get_next_number() - clone_file() - update_project_file() - remove_prj_entry() - rename_prj_entry() - decode_byte_strings() - perform_kdtree_query() - find_nearest_neighbors() - consolidate_dataframe() - find_nearest_value() - horizontal_distance() - find_valid_ras_folders() - is_valid_ras_folder() - safe_write_geometry() # Phase 2.1 - Atomic file write with backup - rollback_geometry() # Phase 2.1 - Restore from backup - validate_geometry_file_basic() # Phase 2.1 - Basic validation - backup_files() # Move files to timestamped Backup folder (safe deletion) - _read_description_block() # Internal - Read BEGIN DESCRIPTION / END DESCRIPTION block - _write_description_block() # Internal - Write BEGIN DESCRIPTION / END DESCRIPTION block
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.
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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}")
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Resolved path with drive letter preserved if applicable |
Example
from pathlib import Path from ras_commander import RasUtils
Local drive - normal resolution¶
resolved = RasUtils.safe_resolve(Path("C:/Projects/Model.prj"))
Mapped drive - preserves H: instead of converting to UNC¶
resolved = RasUtils.safe_resolve(Path("H:/Projects/Model.prj"))
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
set |
set[str]
|
Names to ignore (Windows reserved device names) |
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the name is a reserved device name |
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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")
Source code in ras_commander/RasUtils.py
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")
Source code in ras_commander/RasUtils.py
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}")
Source code in ras_commander/RasUtils.py
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
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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}")
Source code in ras_commander/RasUtils.py
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}")
Source code in ras_commander/RasUtils.py
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)
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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
Source code in ras_commander/RasUtils.py
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
|
pd.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))
Source code in ras_commander/RasUtils.py
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'))
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
float |
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
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
float |
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
Source code in ras_commander/RasUtils.py
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]
|
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)
Source code in ras_commander/RasUtils.py
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")
Source code in ras_commander/RasUtils.py
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"
Source code in ras_commander/RasUtils.py
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")
Source code in ras_commander/RasUtils.py
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")
Source code in ras_commander/RasUtils.py
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¶
Source code in ras_commander/RasUtils.py
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¶
Source code in ras_commander/RasUtils.py
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")
Source code in ras_commander/RasUtils.py
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
|
pd.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
Source code in ras_commander/RasUtils.py
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
|
np.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])
Source code in ras_commander/RasUtils.py
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
|
np.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])
Source code in ras_commander/RasUtils.py
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
|
pd.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]
Source code in ras_commander/RasUtils.py
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]
|
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
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
float |
float
|
Horizontal distance. |
Example
distance = RasUtils.horizontal_distance(np.array([0, 0]), np.array([3, 4])) print(distance) 5.0
Source code in ras_commander/RasUtils.py
find_valid_ras_folders
staticmethod
¶
find_valid_ras_folders(search_path: Union[str, Path], max_depth: Optional[int] = None, return_project_info: 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
|
Returns:
| Type | Description |
|---|---|
Union[List[Path], List[Dict[str, Any]]]
|
Union[List[Path], List[Dict[str, Any]]]: - If return_project_info=False: List of Path objects for valid HEC-RAS folders - If return_project_info=True: List of dicts with keys: - 'folder': Path to the project folder - 'project_name': Name extracted from .prj filename - 'prj_file': Path to the .prj file - 'plan_count': Number of plan files found - 'plan_numbers': List of plan numbers (e.g., ['01', '02', '15']) |
Example
Find all valid HEC-RAS project folders¶
folders = RasUtils.find_valid_ras_folders("C:/Projects/Hydrology") for folder in folders: ... print(f"Found project: {folder}")
Get detailed info about each project¶
projects = RasUtils.find_valid_ras_folders( ... "C:/Projects", ... max_depth=3, ... return_project_info=True ... ) for proj in projects: ... print(f"{proj['project_name']}: {proj['plan_count']} plans")
Note
This function distinguishes HEC-RAS .prj files from ESRI projection files by checking for "Proj Title=" on the first line of the file.
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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:
| Name | Type | Description |
|---|---|---|
bool |
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")
Source code in ras_commander/RasUtils.py
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]
|
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
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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:
| Name | Type | Description |
|---|---|---|
bool |
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.
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of files modified. |
Example
from ras_commander import RasUtils count = RasUtils.dos2unix(Path("/project/dir")) print(f"Converted {count} files")
Source code in ras_commander/RasUtils.py
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:
| Name | Type | Description |
|---|---|---|
Dict[str, Path]
|
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 |
Dict[str, Path]
|
{"6.6": Path("C:/Program Files (x86)/HEC/HEC-RAS/6.6/Ras.exe")} |
Source code in ras_commander/RasUtils.py
| Python | |
|---|---|
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 | |
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¶
RasExamples
¶
RasExamples - Manage and load HEC-RAS example projects for testing and development
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL - Logs are written to both console and a rotating file handler. - The default log file is 'ras_commander.log' in the 'logs' directory. - The default log level is INFO.
To use logging in this module: 1. Use the @log_call decorator for automatic function call logging. 2. For additional logging, use logger.level calls (e.g., logger.info(), logger.debug()). 3. Obtain the logger using: logger = logging.getLogger(name)
Example
@log_call def my_function(): logger = logging.getLogger(name) logger.debug("Additional debug information") # Function logic here
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasExamples: - get_example_projects() - list_categories() - list_projects() - extract_project() - is_project_extracted() - clean_projects_directory()
RasMap¶
RasMap
¶
RasMap - Parses HEC-RAS mapper configuration files (.rasmap)
This module provides functionality to extract and organize information from HEC-RAS mapper configuration files, including paths to terrain, soil, and land cover data. It also includes functions to automate the post-processing of stored maps.
This module is part of the ras-commander library and uses a centralized logging configuration.
Logging Configuration: - The logging is set up in the logging_config.py file. - A @log_call decorator is available to automatically log function calls. - Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
Classes:
| Name | Description |
|---|---|
RasMap |
Class for parsing and accessing HEC-RAS mapper configuration. |
All of the methods in this class are static and are designed to be used without instantiation.
List of Functions in RasMap: - parse_rasmap(): Parse a .rasmap file and extract relevant information - get_rasmap_path(): Get the path to the .rasmap file based on the current project - initialize_rasmap_df(): Initialize the rasmap_df as part of project initialization - get_terrain_names(): Extracts terrain layer names from a given .rasmap file - list_map_layers(): List all map layers in the RASMapper configuration file - list_reference_map_layers(): List shapefile/GeoJSON reference map layers - list_basemap_layers(): List standard basemap layers registered in .rasmap - set_map_layer_visibility(): Toggle reference, basemap, and land-classification map layers - add_reference_map_layer(): Add a shapefile/GeoJSON reference map layer - add_basemap_layer(): Add a standard basemap layer - add_map_layer(): Add a map layer to the RASMapper configuration file - remove_map_layer(): Remove a map layer from the RASMapper configuration file - list_geometry_layers(): List top-level geometries and child geometry elements - list_geometry_features(): List HDF geometry features inside a layer - list_land_classification_polygons(): List sidecar classification polygon overrides - add_land_classification_polygon(): Add sidecar classification polygon override - update_land_classification_polygon(): Update sidecar classification polygon override - delete_land_classification_polygon(): Delete sidecar classification polygon override - set_geometry_layer_visibility(): Toggle child geometry elements such as mesh, XS, and structures - list_result_layers(): List RASMapper result plan and child layers - set_result_layer_visibility(): Toggle result plan and result child layers - get_current_view(): Read the RASMapper CurrentView bounds - set_current_view(): Write the RASMapper CurrentView bounds - set_terrain_layer_visibility(): Toggle terrain layers for RASMapper inspection - list_terrain_display_settings(): List persisted terrain display settings - get_terrain_display_settings(): Read persisted terrain display settings for one terrain - set_terrain_display_settings(): Write persisted terrain display settings - set_update_legend_with_view(): Enable viewport-updated legends on raster surface layers - zoom_to_geometry_layer(): Zoom CurrentView to HDF-derived geometry element extents - get_geometry_feature_bounds(): Get HDF-derived extents for a selected feature - open_rasmapper(): Launch standalone RasMapper.exe against the project .rasmap - capture_rasmapper_snapshot(): Capture a visible RASMapper window screenshot - create_spatial_review_package(): Build a RASMapper QA/QC evidence bundle - postprocess_stored_maps(): Automates the generation of stored floodplain map outputs via GUI automation - store_all_maps(): Headless stored map generation using RasStoreMapHelper.exe (no GUI required) - get_results_folder(): Get the folder path containing raster results for a specified plan - get_results_raster(): Get the .vrt file path for a specified plan and variable name - set_water_surface_render_mode(): Set the water surface rendering mode (horizontal or sloped) - get_water_surface_render_mode(): Get the current water surface rendering mode - add_terrain_layer(): Add terrain layer to RASMapper configuration - list_results_plans(): List all plan result layers in the RASMapper configuration - ensure_results_plan_layer(): Register a plan HDF as a RASMapper result layer - ensure_2d_encroachment_plan_layers(): Register editable 2D encroachment plan layers - list_results_map_layers(): List RASMapper result map layers - add_results_map_layer(): Add a RASMapper result map layer - list_calculated_layers(): List all calculated layers across all plan results - add_calculated_layer(): Add a calculated layer with .rasscript to the RASMapper configuration - remove_calculated_layer(): Remove a calculated layer from the RASMapper configuration - add_wse_comparison_layers(): Batch add WSE comparison layers for existing/proposed plan pairs
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.add_land_classification_polygon() authors the RAS Mapper Classification Polygons sidecar group used by land-cover, soils, and infiltration layers. It also upserts the affected Raster Map and Variables class rows when those datasets exist.
from shapely.geometry import box
from ras_commander import RasMap
polygons = RasMap.add_land_classification_polygon(
"Land Classification/LandCover.hdf",
box(2083000, 370500, 2083500, 371000),
class_name="Parking Lot",
class_id=99,
variable_values={
"mannings_n": 0.105,
"percent_impervious": 95.0,
},
)
Use list_land_classification_polygons(), update_land_classification_polygon(), and delete_land_classification_polygon() for extraction and maintenance. After editing sidecar polygons for an already-associated geometry, rerun preprocessing/property-table workflows so compiled geometry HDFs consume the new override.
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() writes the geometry HDF attributes through Python-native h5py.
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. It does not compile plain-text .g## geometry into HDF or create missing geometry datasets.
RasProcess¶
RasProcess
¶
RasProcess - Wrapper for RasProcess.exe CLI automation
This module provides functionality to automate HEC-RAS mapping operations through the undocumented RasProcess.exe command-line interface. It enables headless generation of stored maps, preprocessing, and other RASMapper operations.
Key Features: - Generate stored maps (WSE, Depth, Velocity, etc.) without GUI - Support for Max/Min profiles and specific timesteps - Automatic .rasmap modification for stored map configuration - Georeferencing fix for StoreMap command bug - Linux support via Wine (headless, no display required)
Classes:
| Name | Description |
|---|---|
RasProcess |
Static class for RasProcess.exe CLI operations |
Note
RasProcess.exe is an undocumented CLI tool bundled with HEC-RAS that exposes RASMapper automation functionality. See rasmapper_docs/16_rasprocess_cli_reference.md for complete documentation.
Linux/Wine Support: On Linux, RasProcess.exe runs under Wine with .NET Framework 4.8. Requirements: - Wine 8.0+ (64-bit prefix) - winetricks: dotnet48, gdiplus, corefonts - HEC-RAS DLLs copied into Wine prefix (see setup_wine_environment())
The module auto-detects Linux and wraps commands with Wine automatically.
No code changes needed for users — just install the Wine environment.
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
)
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.