Skip to content

Terrain Modification Analysis

This notebook writes a channel terrain modification into a copy of the Bald Eagle Creek example terrain with RasTerrainModWriter, then measures what RAS Mapper applies: terrain profiles along the channel and elevation-volume curves for the existing and proposed terrain.

  • Inputs: BaldEagleCrkMulti2D from RasExamples, extracted twice: an unmodified existing copy and a proposed copy that receives the modification.
  • Outputs: the modified terrain HDF and .rasmap of the proposed copy, profile and volume comparisons, and two figures. Everything stays under the run root in working/.
  • Runtime: under a minute on Windows with HEC-RAS installed. Writing needs only h5py; sampling needs pythonnet and HEC-RAS 6.6+ RasMapperLib.dll (RasTerrainMod).
  • Scope: terrain geometry only. No hydraulic plan is run, and the channel grade is an illustration, not a design.
Python
# Setup and imports
from pathlib import Path
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import h5py

from ras_commander import RasExamples, init_ras_project
from ras_commander.terrain import RasTerrainModWriter

NOTEBOOK_DIR = Path.cwd()
REPO_ROOT = NOTEBOOK_DIR.parent
RUN_ROOT = Path(
    os.environ.get(
        "RAS_COMMANDER_EXAMPLE_RUN_ROOT",
        REPO_ROOT / "working" / "example_930_terrain_modification_analysis",
    )
).resolve()
RUN_ROOT.mkdir(parents=True, exist_ok=True)
EXAMPLE_PROJECTS_ROOT = RUN_ROOT / "example_projects"

def run_path(path):
    '''Return a portable label for an artifact under this notebook's run root.'''
    return str(Path("run") / Path(path).resolve().relative_to(RUN_ROOT))

# Optional: RasTerrainMod for reading terrain with modifications applied (requires pythonnet)
try:
    from ras_commander.terrain import RasTerrainMod
    bridge_ok = RasTerrainMod.setup_gdal_bridge()
    print(f'RasTerrainMod available (GDAL bridge: {bridge_ok})')
    HAS_TERRAIN_MOD = bridge_ok
except (ImportError, OSError) as e:
    print(f'RasTerrainMod not available: {e}')
    print('Terrain modification WRITING will work, but reading/sampling requires pythonnet + HEC-RAS 6.6+')
    HAS_TERRAIN_MOD = False

print('RasTerrainModWriter imported successfully')
print(f'Run root: {RUN_ROOT.name}')
Text Only
2026-11-11 18:35:03 - ras_commander.terrain.RasTerrainMod - INFO - Configured HEC-RAS GDAL runtime for HEC-RAS 7.0


RasTerrainMod available (GDAL bridge: True)
RasTerrainModWriter imported successfully
Run root: example_930_terrain_modification_analysis

Step 1: Setup

RasTerrainModWriter can create terrain modifications without pythonnet or the GDAL bridge. For profiles, volume curves, and other small analytical samples of modified terrain, use RasTerrainMod (get_terrain_profile, get_terrain_volume_elevation, and related methods). It requires pythonnet and HEC-RAS 6.6+ RasMapperLib.dll.

Python
# GDAL bridge setup (only needed for terrain sampling, not for writing modifications)
if HAS_TERRAIN_MOD:
    print('GDAL bridge is ready for terrain sampling')
else:
    print('Skipping GDAL bridge - terrain writing still works')
Text Only
GDAL bridge is ready for terrain sampling

Step 2: Extract Existing and Proposed Project Copies

Extract BaldEagleCrkMulti2D twice. The existing copy is never modified; the proposed copy receives the channel modification. Each copy keeps its own geometry HDF, terrain HDF and .rasmap, so the two conditions can be sampled side by side. The river centerline in geometry g06 supplies the channel alignment.

Python
existing_path = RasExamples.extract_project(
    'BaldEagleCrkMulti2D',
    output_path=EXAMPLE_PROJECTS_ROOT,
    suffix='930_existing',
)
project_path = RasExamples.extract_project(
    'BaldEagleCrkMulti2D',
    output_path=EXAMPLE_PROJECTS_ROOT,
    suffix='930_terrainmod',
)
print(f'Existing copy: {run_path(existing_path)}')
print(f'Proposed copy: {run_path(project_path)}')

# Find terrain HDF and rasmap of the proposed copy
terrain_hdf = list((project_path / 'Terrain').glob('*.hdf'))[0]
rasmap_path = list(project_path.glob('*.rasmap'))[0]
existing_rasmap = existing_path / rasmap_path.name
print(f'Terrain: {terrain_hdf.name}')
print(f'Rasmap: {rasmap_path.name}')

# Read river centerline from geometry HDF (g06 has centerlines)
geom_hdf = project_path / 'BaldEagleDamBrk.g06.hdf'
existing_geom_hdf = existing_path / geom_hdf.name
with h5py.File(geom_hdf, 'r') as f:
    centerline_pts = f['Geometry/River Centerlines/Polyline Points'][:]
print(f'River centerline: {len(centerline_pts)} points')

# Verify files exist
for path in (terrain_hdf, rasmap_path, existing_rasmap, geom_hdf, existing_geom_hdf):
    assert path.exists(), f'Missing: {path}'
Text Only
2026-11-11 18:35:06 - ras_commander.RasExamples - INFO - Successfully extracted project 'BaldEagleCrkMulti2D' to BaldEagleCrkMulti2D_930_existing


2026-11-11 18:35:08 - ras_commander.RasExamples - INFO - Successfully extracted project 'BaldEagleCrkMulti2D' to BaldEagleCrkMulti2D_930_terrainmod


Existing copy: run\example_projects\BaldEagleCrkMulti2D_930_existing
Proposed copy: run\example_projects\BaldEagleCrkMulti2D_930_terrainmod
Terrain: Terrain50.hdf
Rasmap: BaldEagleDamBrk.rasmap
River centerline: 383 points

Step 3: Choose the Channel Invert

RAS Mapper stores a channel invert as an absolute elevation profile along the line. add_channel_modification accepts it as profile_points, a constant elevation, or a Z column; alternatively depth= sets the invert that far below the terrain sampled at each vertex.

An earlier version of this notebook passed depth=15. The writer then stored -15 as an absolute invert, so RAS Mapper would have cut the channel to about -15 ft. The corrected writer measures depth below the existing ground. Bald Eagle Creek's terrain already contains the channel, so the centerline vertices sit on the channel bed. With depth=15, the corrected writer would dig a 100-ft-wide trench 15 ft below the existing bed along the whole 7.3-mile alignment, and the invert would rise and fall with the bed samples. That is not a channel modification anyone would draw, so this notebook uses a different approach rather than a different depth.

Here the invert is a uniform design grade: a straight line fitted through the existing bed profile, written with profile_points. In take_lower mode, RAS Mapper lowers the terrain only where the channel template is below the existing ground. Riffles and bars above the grade are cut; pools below it are left alone. The alignment starts at centerline vertex 1, because vertex 0 lies on the high bank at the upstream boundary (about 20 ft above the bed).

Python
channel_alignment = centerline_pts[1:100]
alignment_stations = np.r_[0.0, np.cumsum(np.hypot(*np.diff(channel_alignment, axis=0).T))]
alignment_length = float(alignment_stations[-1])
print(f'Alignment: {len(channel_alignment)} vertices, {alignment_length:,.0f} ft '
      f'({alignment_length / 5280:.1f} mi)')

if HAS_TERRAIN_MOD:
    # Existing bed along the alignment, sampled from the unmodified copy
    existing_bed = RasTerrainMod.get_terrain_profile(
        existing_rasmap, existing_geom_hdf,
        x_coords=channel_alignment[:, 0].tolist(),
        y_coords=channel_alignment[:, 1].tolist(),
    )
    grade_slope, grade_intercept = np.polyfit(
        existing_bed['station'], existing_bed['elevation'], 1
    )
    design_profile = np.array([
        [0.0, grade_intercept],
        [alignment_length, grade_intercept + grade_slope * alignment_length],
    ])
    channel_invert = {'profile_points': design_profile}
    print(f'Existing bed samples: {len(existing_bed)}, '
          f'{existing_bed["elevation"].min():.1f} to {existing_bed["elevation"].max():.1f} ft')
    print(f'Design grade: {design_profile[0, 1]:.2f} ft to {design_profile[1, 1]:.2f} ft '
          f'(slope {-grade_slope:.5f} ft/ft)')
else:
    # Without RasMapperLib, let the writer sample the terrain sources itself and
    # set the invert a modest depth below them.
    channel_invert = {'depth': 2.0}
    print('RasTerrainMod unavailable: using depth=2.0 below the sampled terrain')
Text Only
Alignment: 99 vertices, 38,577 ft (7.3 mi)


2026-11-11 18:35:09 - ras_commander.terrain.RasTerrainMod - INFO - RasMapperLib.dll loaded


Existing bed samples: 6405, 607.3 to 656.9 ft
Design grade: 651.57 ft to 604.75 ft (slope 0.00121 ft/ft)

Step 4: Add the Channel Terrain Modification

add_channel_modification writes the layer into the terrain HDF (/Modifications/) and registers it in the .rasmap inside an ElevationModificationGroup. RAS Mapper applies HDF modifications only when that group exists. The bottom width is 100 ft with 3H:1V side slopes; max_extent (RAS Mapper's Max Reach) limits the total footprint to 200 ft, half on each side of the line.

Python
RasTerrainModWriter.add_modification_group(terrain_hdf, rasmap_path)

RasTerrainModWriter.add_channel_modification(
    terrain_hdf_path=terrain_hdf,
    rasmap_path=rasmap_path,
    name="River Channel",
    polyline_points=channel_alignment,
    width=100.0,       # 100 ft bottom width
    left_slope=3.0,    # 3H:1V side slopes
    right_slope=3.0,
    max_extent=200.0,  # Max Reach: total footprint width
    mode="take_lower",
    **channel_invert,
)

# Verify the modification as RAS Mapper stores it
with h5py.File(terrain_hdf, "r") as f:
    grp = f["Modifications/River Channel"]
    attrs = grp["Attributes"][0]
    print("Modification: River Channel")
    print(f"  Type: {grp.attrs['Type'].decode()}, Subtype: {grp.attrs['Subtype'].decode()}")
    print(f"  Elevation Type: {attrs['Elevation Type'].decode()}")
    print(f"  Alignment: {len(grp['Polyline Points'])} points")
    print(f"  Top Width: {attrs['Top Width']} ft, Max Reach: {attrs['Max Reach']} ft")
    print(f"  System Name: {attrs['System Name'].decode()!r} (empty = ordinary channel)")
    print(f"  Profile Values (station, invert):\n{grp['Profile Values'][:]}")

display(RasTerrainModWriter.list_modifications(terrain_hdf))

# Verify rasmap was updated
import xml.etree.ElementTree as ET
tree = ET.parse(rasmap_path)
for mg in tree.findall('.//Layer[@Type="ElevationModificationGroup"]'):
    group_name = mg.get('Name')
    print(f"Rasmap modification group: {group_name}")
    for child in mg.findall("Layer"):
        child_name = child.get('Name')
        child_type = child.get('Type')
        print(f"  Layer: {child_name} (Type={child_type})")
Text Only
Modification: River Channel
  Type: Levee, Subtype: Channel
  Elevation Type: SetIfLower
  Alignment: 99 points
  Top Width: 100.0 ft, Max Reach: 200.0 ft
  System Name: '' (empty = ordinary channel)
  Profile Values (station, invert):
[[    0.        651.57495]
 [38576.938     604.75476]]
name type subtype priority modification_type modification_mode width left_slope right_slope max_extent elev_pt_tolerance profile_points feature_count system_names
0 River Channel Levee Channel 0 2 take_lower 100.0 3.0 3.0 200.0 50.0 2 1 []
Text Only
Rasmap modification group: Modifications
  Layer: River Channel (Type=GroundLineModificationLayer)

Step 5: Get Terrain Extent

Query the terrain bounding box to understand the project domain.

Python
try:
    if HAS_TERRAIN_MOD:
        extent = RasTerrainMod.get_terrain_extent(str(rasmap_path), str(geom_hdf))
        print(f"Success: {extent['success']}")
        print(f"X range: {extent['min_x']:,.0f} to {extent['max_x']:,.0f}")
        print(f"Y range: {extent['min_y']:,.0f} to {extent['max_y']:,.0f}")
    else:
        print("Skipping terrain extent (pythonnet not available)")
except Exception as e:
    print(f"Terrain extent sampling failed: {e}")
    print("This is expected if pythonnet/RasMapperLib is not fully configured.")
    HAS_TERRAIN_MOD = False
Text Only
Success: True
X range: 1,834,327 to 2,149,836
Y range: 162,919 to 414,873

Step 6: Existing vs Proposed Terrain Profile

Sample the same polyline in both copies. RasTerrainMod returns elevations with every modification of the .rasmap terrain applied, the same surface RAS Mapper draws, without opening the GUI. Each copy is sampled with its own geometry HDF: RAS Mapper resolves the terrain relative to the geometry, so pairing the existing .rasmap with the proposed geometry would sample the proposed terrain. filter_tolerance=0.0 keeps every sample, so the two profiles compare point by point.

Python
try:
    if HAS_TERRAIN_MOD:
        x_profile = channel_alignment[:, 0].tolist()
        y_profile = channel_alignment[:, 1].tolist()
        existing_profile = RasTerrainMod.get_terrain_profile(
            str(existing_rasmap), str(existing_geom_hdf),
            x_coords=x_profile, y_coords=y_profile, filter_tolerance=0.0,
        )
        profile = RasTerrainMod.get_terrain_profile(
            str(rasmap_path), str(geom_hdf),
            x_coords=x_profile, y_coords=y_profile, filter_tolerance=0.0,
        )
        stations = existing_profile['station'].to_numpy()
        existing_z = existing_profile['elevation'].to_numpy()
        proposed_z = np.interp(stations, profile['station'], profile['elevation'])
        design_z = np.interp(stations, design_profile[:, 0], design_profile[:, 1]) \
            if 'profile_points' in channel_invert else None
        change = proposed_z - existing_z
        lowered = change < -0.01
        print(f"Existing profile: {len(existing_profile)} points, "
              f"{existing_z.min():.1f} to {existing_z.max():.1f} ft")
        print(f"Proposed profile: {len(profile)} points, "
              f"{profile['elevation'].min():.1f} to {profile['elevation'].max():.1f} ft")
        print(f"Lowered along {lowered.mean():.0%} of the samples; "
              f"mean cut {-change[lowered].mean():.2f} ft, max cut {-change.min():.2f} ft")
        print(f"Raised anywhere: {bool((change > 0.01).any())} (take_lower never fills)")
        if design_z is not None:
            gap = np.abs(proposed_z[lowered] - design_z[lowered])
            print(f"Where lowered, proposed bed is within {gap.max():.2f} ft of the design grade")
    else:
        print("Skipping terrain profile (pythonnet not available)")
except Exception as e:
    print(f"Terrain profile sampling failed: {e}")
    HAS_TERRAIN_MOD = False
Text Only
Existing profile: 8616 points, 607.3 to 656.9 ft
Proposed profile: 6498 points, 604.8 to 651.6 ft
Lowered along 54% of the samples; mean cut 2.70 ft, max cut 7.17 ft
Raised anywhere: False (take_lower never fills)
Where lowered, proposed bed is within 0.00 ft of the design grade
Python
if HAS_TERRAIN_MOD and 'existing_profile' in dir():
    fig, ax = plt.subplots(figsize=(14, 5))
    ax.plot(stations, existing_z, color='0.45', linewidth=0.8, label='Existing bed')
    ax.plot(stations, proposed_z, color='tab:blue', linewidth=0.8, label='Proposed (modification applied)')
    if design_z is not None:
        ax.plot(stations, design_z, 'k--', linewidth=1.0, label='Design invert (profile_points)')
    ax.fill_between(stations, proposed_z, existing_z, where=lowered, color='tab:orange',
                    alpha=0.4, label='Cut')
    ax.set_xlabel('Station along alignment (ft)')
    ax.set_ylabel('Elevation (ft)')
    ax.set_title('Channel bed profile: existing vs proposed (take_lower)')
    ax.legend()
    ax.grid(True, alpha=0.25)
    plt.tight_layout()
    plt.show()
else:
    print("Skipping profile plot (no data)")

png

Step 7: Elevation-Volume Curves for a Polygon

Compute the elevation-volume relationship within a 1,000-ft square centred on the channel, once for each condition. Elevation-volume curves support: - Detention pond sizing - Storage volume calculations - No-net-fill compliance

Both curves include every modification in their terrain, so the proposed curve includes the channel excavation. Above the highest ground in the polygon, the difference between the two curves is the cut volume.

Python
try:
    if HAS_TERRAIN_MOD:
        cx, cy = channel_alignment[24]
        hw = 500.0
        poly_x = [cx-hw, cx+hw, cx+hw, cx-hw, cx-hw]
        poly_y = [cy-hw, cy-hw, cy+hw, cy+hw, cy-hw]
        ev_existing = RasTerrainMod.get_terrain_volume_elevation(
            str(existing_rasmap), str(existing_geom_hdf),
            x_coords=poly_x, y_coords=poly_y,
        )
        ev_cuft = RasTerrainMod.get_terrain_volume_elevation(
            str(rasmap_path), str(geom_hdf),
            x_coords=poly_x, y_coords=poly_y,
        )
        top = min(ev_existing['elevation'].max(), ev_cuft['elevation'].max())
        cut_cuft = (np.interp(top, ev_cuft['elevation'], ev_cuft['volume'])
                    - np.interp(top, ev_existing['elevation'], ev_existing['volume']))
        print(f"Existing curve: {len(ev_existing)} points, "
              f"lowest ground {ev_existing['elevation'].min():.2f} ft")
        print(f"Proposed curve: {len(ev_cuft)} points, "
              f"lowest ground {ev_cuft['elevation'].min():.2f} ft")
        print(f"Cut volume in the polygon: {cut_cuft:,.0f} cu ft ({cut_cuft / 27:,.0f} cu yd)")
    else:
        print("Skipping elevation-volume (pythonnet not available)")
except Exception as e:
    print(f"Volume calculation failed: {e}")
    HAS_TERRAIN_MOD = False
Text Only
Existing curve: 42 points, lowest ground 639.64 ft
Proposed curve: 34 points, lowest ground 639.59 ft
Cut volume in the polygon: 293,700 cu ft (10,878 cu yd)
Python
if HAS_TERRAIN_MOD and 'ev_cuft' in dir():
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(ev_existing['volume'], ev_existing['elevation'], 'o-', color='0.45',
            markersize=3, label='Existing')
    ax.plot(ev_cuft['volume'], ev_cuft['elevation'], 'o-', color='tab:blue',
            markersize=3, label='Proposed')
    ax.set_xlabel('Volume (cubic feet)')
    ax.set_ylabel('Elevation (ft)')
    ax.set_title('Elevation-Volume Curves, 1,000-ft square on the channel')
    ax.legend()
    ax.grid(True, alpha=0.25)
    plt.tight_layout()
    plt.show()
else:
    print("Skipping volume plot (no data)")

png

Step 8: Elevation-Volume Table

Tabulate both curves at common elevations for engineering review. Values between curve points are interpolated linearly, so the added storage above the cut varies by a few hundred cubic feet.

Python
if HAS_TERRAIN_MOD and 'ev_cuft' in dir():
    levels = np.arange(np.ceil(ev_cuft['elevation'].min()), np.floor(top) + 1.0, 1.0)
    summary = pd.DataFrame({
        'elevation': levels,
        'existing_volume': np.interp(levels, ev_existing['elevation'], ev_existing['volume'],
                                     left=0.0),
        'proposed_volume': np.interp(levels, ev_cuft['elevation'], ev_cuft['volume'], left=0.0),
    })
    summary['added_storage'] = summary['proposed_volume'] - summary['existing_volume']
    print(summary.to_string(index=False, float_format=lambda v: f'{v:,.1f}'))
else:
    print("Skipping volume table (no data)")
Text Only
 elevation  existing_volume  proposed_volume  added_storage
     640.0             95.9          5,845.3        5,749.4
     641.0         11,539.2         80,161.4       68,622.2
     642.0         68,005.1        224,918.7      156,913.6
     643.0        183,243.2        403,188.8      219,945.5
     644.0        351,052.4        614,521.8      263,469.4
     645.0        653,837.6        938,462.5      284,624.9
     646.0      1,298,904.4      1,591,784.6      292,880.2
     647.0      2,235,253.5      2,528,101.4      292,847.9
     648.0      3,224,601.7      3,518,117.5      293,515.7
     649.0      4,221,667.2      4,515,366.8      293,699.6

Production Raster Derivatives

RasTerrainMod remains the focused API for terrain profiles, volume curves, and small analytical sampling. For a production GeoTIFF derivative of a terrain already registered in RAS Mapper, use RasTerrain.export_rasmapper_terrain() so RAS Mapper performs the native consolidation, grid-aligned resampling, and optional modification rasterization.

See Native RAS Mapper Terrain Export for the bounded export workflow and receipt validation. See Terrain Modifications for a real modification-off versus modification-on pixel comparison, and Terrain Modification Layer Writers for every writer layer kind, the read_layers round trip, and pixel checks against RAS Mapper's own export on HEC-RAS 6.6 and 7.0.1.

Key Takeaways

  • RasTerrainModWriter creates terrain modifications programmatically (channel, levee, polygon, ellipse)
  • Writes to both terrain HDF (/Modifications/) and .rasmap XML
  • No pythonnet or RasMapperLib required for writing
  • A channel invert is an absolute profile (profile_points, elevation or Z); depth= is measured below the terrain sampled at each vertex
  • The newest layer goes on top (Priority 0 wins where layers overlap)
  • RasTerrainMod (optional) provides headless terrain sampling with modifications applied
  • Requires pythonnet + HEC-RAS 6.6+ RasMapperLib.dll
  • Used for cut/fill analysis, elevation-volume curves, terrain profiles
  • Sample each project copy with its own geometry HDF
  • The dual-storage architecture (HDF + XML) is handled automatically by both classes