Floodplain Mapping via GUI Automation¶
This notebook demonstrates floodplain mapping using HEC-RAS GUI automation to generate: - Maximum Water Surface Elevation (WSE) rasters - Maximum Depth rasters
The workflow is fully automated: HEC-RAS opens, computes the stored maps, and auto-closes when complete. No manual interaction is required.
How It Works¶
RasMap.postprocess_stored_maps() handles the full workflow:
1. Backs up plan and .rasmap files
2. Sets run flags to floodplain-mapping-only (skips simulation)
3. Configures stored map layers in .rasmap XML (creates RASResults layer if missing)
4. Opens HEC-RAS GUI and clicks Compute
5. Polls plan HDF for "Complete Process" signal to detect completion
6. Auto-closes HEC-RAS and restores original files
Comparison with RasProcess CLI (Notebook 601)¶
| Method | Speed | GUI Required | Best For |
|---|---|---|---|
| GUI Automation (this notebook) | ~15 sec | Yes (auto-managed) | Debugging, visual verification |
| RasProcess CLI (notebook 601) | ~8 sec | No | Production, batch processing |
Prerequisites¶
- HEC-RAS 6.x installed (provides GUI executable)
- Windows operating system
- Required packages:
ras-commander,rasterio,matplotlib,pywin32
# =============================================================================
# DEVELOPMENT MODE TOGGLE
# =============================================================================
USE_LOCAL_SOURCE = True # <-- Set to True to use local ras-commander source
if USE_LOCAL_SOURCE:
import sys
from pathlib import Path
local_path = str(Path.cwd().parent)
if local_path not in sys.path:
sys.path.insert(0, local_path)
print(f"LOCAL SOURCE MODE: Loading from {local_path}/ras_commander")
else:
print("PIP PACKAGE MODE: Loading installed ras-commander")
from ras_commander import RasCmdr, RasExamples, RasMap, init_ras_project, ras
import rasterio
from rasterio.plot import show
import matplotlib.pyplot as plt
from pathlib import Path
import ras_commander
print(f"Loaded: {ras_commander.__file__}")
Parameters¶
# =============================================================================
# PARAMETERS
# =============================================================================
PROJECT_NAME = "BaldEagleCrkMulti2D"
RAS_VERSION = "7.0"
PLAN = "06" # Dam break plan
print(f"Project: {PROJECT_NAME}, Plan: {PLAN}")
Step 1: Extract Example Project and Initialize¶
project_path = RasExamples.extract_project(PROJECT_NAME, suffix="600")
init_ras_project(project_path, RAS_VERSION)
print(f"Project: {ras.project_name}")
print(f"Folder: {ras.project_folder}")
print(f"\nPlans:")
print(ras.plan_df[['plan_number', 'Plan Title']].to_string())
Step 2: Compute Plan (if needed)¶
GUI automation generates stored maps from existing HDF results. The plan must be computed first.
hdf_path = ras.project_folder / f"{ras.project_name}.p{PLAN}.hdf"
if not hdf_path.exists():
print(f"Computing plan {PLAN}...")
RasCmdr.compute_plan(PLAN, num_cores=2)
print(f"Plan {PLAN} complete.")
else:
print(f"Plan {PLAN} already computed ({hdf_path.stat().st_size / (1024*1024):.1f} MB)")
Step 3: Generate Maps via GUI Automation¶
One function call handles everything:
- Configures .rasmap with stored map layers
- Sets plan flags to mapping-only (skips re-running the simulation)
- Opens HEC-RAS, clicks Compute, monitors HDF for completion
- Auto-closes HEC-RAS when maps are generated
- Restores original plan and .rasmap files
# Get available terrains
rasmap_path = ras.project_folder / f"{ras.project_name}.rasmap"
terrains = RasMap.get_terrain_names(rasmap_path)
print(f"Available terrains: {terrains}")
# Generate stored maps — HEC-RAS will open and auto-close
success = RasMap.postprocess_stored_maps(
plan_number=PLAN,
specify_terrain=terrains[0] if terrains else None,
layers=['Depth', 'WSEL']
)
if success:
print("\nSuccessfully generated stored maps via GUI automation")
else:
print("\nFailed to generate stored maps")
Step 4: Verify Output Files¶
# Find the output directory using Short Identifier from plan_df
plan_info = ras.plan_df[ras.plan_df['plan_number'] == PLAN].iloc[0]
short_id = plan_info.get('Short Identifier', f'Plan_{PLAN}')
output_folder = ras.project_folder / short_id
print(f"Output folder: {output_folder}")
if output_folder.exists():
tif_files = sorted(output_folder.glob('*.tif'))
vrt_files = sorted(output_folder.glob('*.vrt'))
print(f"\nGenerated files:")
for f in tif_files + vrt_files:
print(f" {f.name} ({f.stat().st_size / 1024:.1f} KB)")
else:
print("Output folder not found — maps were not generated")
Step 5: Visualize Results¶
# Find depth and WSE TIF files
depth_tifs = sorted(output_folder.glob('Depth*.tif')) if output_folder.exists() else []
wse_tifs = sorted(output_folder.glob('WSE*.tif')) if output_folder.exists() else []
if depth_tifs:
fig, axes = plt.subplots(1, 2, figsize=(16, 8))
# Plot depth raster
with rasterio.open(depth_tifs[0]) as src:
show(src, ax=axes[0], cmap='Blues')
axes[0].set_title(f'Max Depth - Plan {PLAN}')
axes[0].set_xlabel('Easting')
axes[0].set_ylabel('Northing')
print(f"Depth raster: {src.width}x{src.height}, CRS: {src.crs}")
# Plot WSE raster
if wse_tifs:
with rasterio.open(wse_tifs[0]) as src:
show(src, ax=axes[1], cmap='terrain')
axes[1].set_title(f'Max WSE - Plan {PLAN}')
axes[1].set_xlabel('Easting')
axes[1].set_ylabel('Northing')
print(f"WSE raster: {src.width}x{src.height}, CRS: {src.crs}")
plt.tight_layout()
plt.show()
else:
print("No depth rasters found for visualization")
Technical Notes¶
Completion Detection¶
The GUI automation detects when floodplain mapping is complete by polling the plan HDF file:
1. Records the HDF modification time before launching HEC-RAS
2. After clicking Compute, polls every 2 seconds
3. When the HDF is modified AND contains "Complete Process" in compute messages, mapping is done
4. HEC-RAS is terminated automatically and backup files are restored
RASResults Layer Creation¶
Some example projects have an empty <Results /> section in their .rasmap file (no RASResults layers). The function automatically creates the required <Layer Type="RASResults"> XML element when one doesn't exist, referencing the plan's HDF file.
When to Use GUI vs RasProcess¶
- GUI Automation (this notebook): Useful when you need to debug mapping issues or verify output visually in RASMapper. The HEC-RAS window is visible during computation.
- RasProcess CLI (notebook 601): Faster, headless, recommended for production and batch workflows. No GUI window opens.