Skip to content

terrain

Terrain discovery and consolidation for HEC-RAS projects.

Overview

The terrain module discovers named terrain layers from a HEC-RAS project's rasmap configuration and consolidates each surface's TIFF members independently. This is useful for:

  • Inspecting terrain configuration: Enumerate all terrain layers, their CRS, resolution, and file locations
  • Consolidating terrain: Merge the TIFF members of each named terrain into its own authoritative file
  • Downsampling without upsampling: Select a whole native-cell multiple with a 5 ft publication floor
  • Recovering relocated projects: Consolidate an explicit, priority-ordered TIFF list when stored RASMapper paths cannot be resolved on the processing host
  • Publishing source construction: Export source TIFF footprints and terrain-modification vectors
  • Creating HEC-RAS terrain HDFs: Generate new terrain HDF files via RasProcess.exe (required for result mapping)
  • Native modification-aware export: Ask RAS Mapper to consolidate a registered terrain into one validated GeoTIFF while preserving source priority, stitches, masks, and vector modifications

Terrain Modification Vectors

extract_terrain_modification_layers() (and export_terrain_modifications(), which writes each non-empty layer as GeoParquet) reads the terrain HDF's /Modifications group. Each modification layer can hold several features, and each feature is one row with its own attributes (feature_index, feature_name).

Layer Contents
terrain_modification_lines Line, levee and channel centrelines with width (top width), left_slope, right_slope and max_extent (RAS Mapper's Max Reach)
terrain_modification_polygons Polygon modifications (shape_type="polygon") and the outlines of pier, rectangle, ellipse and triangle modifications (shape_type), built from their stored parameters
terrain_modification_footprints One polygon per feature covering the terrain it can change: lines buffered by max_extent (or, when no max extent is stored, half the top width, an estimate that can omit side-slope reach; see footprint_basis and footprint_half_width), polygons and shapes as drawn. A line with neither a positive max_extent nor a positive width has no footprint
terrain_modification_control_points Elevation control points

A centreline is not a footprint: a channel or levee changes the terrain across its top width and side slopes, up to Max Reach either side. Use terrain_modification_footprints to test whether a feature can affect a location. A max_extent footprint is an upper bound; how far the side slopes actually reach depends on the terrain. A top_width footprint (no max extent stored) covers only the top width and can omit side-slope reach, so do not use it to rule out an effect at a location. A line with no usable max extent or width has no footprint, so check terrain_modification_lines when every feature must be covered.

Stored vs Active Modifications

A terrain HDF stores modification layers under /Modifications. RAS Mapper (HEC-RAS 6.6, 7.0.1) applies them only when the project's .rasmap terrain layer has an ElevationModificationGroup named exactly Modifications, and then applies every stored layer: the group's per-layer entries and Checked state are not consulted. Two projects can share one terrain HDF and still map on different terrains: a project whose terrain layer has no Modifications group (none, or only one under another name) maps on the unmodified terrain, and a RAS Mapper export through it is identical to the unmodified terrain.

from ras2cng.terrain import terrain_modification_status, active_terrain_modifications

status = terrain_modification_status("Terrain/T.hdf", "Model.rasmap")
status.stored      # layers in the HDF
status.active      # layers RAS Mapper applies in this project
status.inactive    # stored but not applied (no Modifications group)
status.registered  # layers the .rasmap lists (informational)
status.basis       # "rasmap", or "hdf" when the .rasmap has no entry for this terrain

Without a .rasmap, or when it has no layer for this terrain HDF, every stored layer counts as active, so an unknown activation is never treated as unmodified. active_terrain_modifications() returns the labels of the active set; fast-map uses it to choose between native terrain operations and the RAS Mapper export. terrain_modifications() remains an inventory of everything stored or registered. ras2cng inspect shows active/stored counts per terrain, and archive manifests record stored_modifications, active_modifications, inactive_modifications and activation_basis in each terrain_modifications entry.

How Terrain Discovery Works

  1. Reads the project's .rasmap file to get terrain names in priority order
  2. For each terrain name, locates the corresponding .hdf file in the Terrain/ directory
  3. Discovers associated .tif files by matching the HDF stem against TIF file names
  4. Optionally reads CRS and resolution from TIF files using rasterio

Terrain Name Matching

TIF files are associated with a terrain by matching the file stem against the terrain name. The matching is case-insensitive and allows suffixes separated by ., _, or -:

TIF Stem Terrain Name Match?
Terrain50 Terrain50 Yes (exact)
Terrain50.muncie_clip Terrain50 Yes (dot separator)
Terrain50_tile2 Terrain50 Yes (underscore separator)
Terrain50-highres Terrain50 Yes (dash separator)
Terrain50WithChannel Terrain50 No (alphanumeric continuation)

How Terrain Consolidation Works

  1. Discover terrain TIFs from rasmap (priority ordered)
  2. Keep terrain names separate: different named RASMapper terrains are never merged implicitly
  3. Choose a target grid: preserve native resolution at or above 5 ft; otherwise use the smallest whole native-cell multiple at or above 5 ft. A mixed-resolution mosaic requires an explicit target that is a whole multiple of its coarsest native grid; every source factor is retained in provenance.
  4. Merge by windows: reproject each member to the target grid and let the first RASMapper source win in overlaps without allocating the full mosaic in memory
  5. Optionally create HEC-RAS terrain HDF via RasTerrain.create_terrain_from_rasters() (requires RasProcess.exe)
  6. Optionally register the new terrain in the project's rasmap

Steps 5-6 require RasProcess.exe (Windows or Wine). Steps 1-4 are pure Python (rasterio).

Merge engine (opt-in)

Step 4 warps each 512-pixel destination block separately with rasterio. Setting RAS2CNG_TERRAIN_MERGE_ENGINE=terrio does one whole-output warp of every source with terrio instead (it needs the CLB terrio build; without it, or when the sources do not share one CRS, the merge stays on rasterio and the reason is recorded). auto and rasterio keep the default.

The switch changes the values. terrio's mosaic is bit-identical to GDAL's own whole-output warp, and the blockwise output is not: on the Bald Eagle terrain (two sources, 40 ft target) 18.5 M of 49.7 M pixels differ between the two, by up to 4.44 ft (274 pixels by more than 1 ft), with identical valid masks. terrio took 4.9 s against 20.9 s, with a 453 MiB peak against 829 MiB. It is off by default so that existing outputs do not change. The engine used is written to the terrain provenance file as merge_engine.

Native Registered-Terrain Export

export_modified_terrain() is the production path for a single, modification-aware terrain TIFF. It delegates to RasTerrain.export_rasmapper_terrain() rather than selecting the first source TIFF or reconstructing terrain-modification mathematics in Python. RAS Mapper performs the consolidation and nearest-neighbor resampling on the authoritative source grid. Exact source-derived scale factors are 1, 2, 4, and 8.

The output is committed only after ras-commander semantically validates it; a JSON receipt is written beside the TIFF. Existing output and receipt files are protected unless overwrite=True (or --overwrite in the CLI).

The optional geometry argument is deprecated and ignored because native registered-terrain export does not consume a geometry HDF. terrain_name may be omitted only when the project registers exactly one terrain; ambiguous projects must select the exact RAS Mapper terrain name. The compatibility argument is scheduled for removal in ras2cng 1.1.

This path uses ras-commander 0.100.0 or newer, which exposes RasTerrain.export_rasmapper_terrain(). An older installation receives an explicit upgrade error instead of falling back to the numerically different row sampler.

Qualified runtimes are HEC-RAS 6.4.1, 6.5, 6.6, and 7.0.1 on native Windows and Wine. HEC-RAS 6.3, 6.4.0, 6.7 beta builds, and 7.0.0 are rejected. Stable 7.1 is forward-open: ras-commander will accept it only when the installed binary satisfies the exact managed API contract.

API Reference

ras2cng.terrain.TerrainInfo dataclass

Information about a single terrain layer discovered from a RAS project.

Source code in ras2cng/terrain.py
@dataclass
class TerrainInfo:
    """Information about a single terrain layer discovered from a RAS project."""
    name: str
    hdf_path: Optional[Path] = None
    hdf_exists: bool = False
    tif_files: list[Path] = field(default_factory=list)
    crs: Optional[str] = None
    resolution: Optional[str] = None       # e.g. "50.0 x 50.0 ft"
    bounds: Optional[tuple] = None         # (xmin, ymin, xmax, ymax)
    total_size_mb: float = 0.0
    #: :meth:`TerrainModificationStatus.to_dict` for this project, or None
    #: (no terrain HDF, or it could not be read).
    modifications: Optional[dict] = None

ras2cng.terrain.discover_terrains(project_path)

Discover terrain layers from rasmap in priority order.

Uses RasMap.get_terrain_names() + rasmap_df['terrain_hdf_path']. For each terrain HDF, discovers associated .tif files in same directory.

Parameters:

Name Type Description Default
project_path Path

Path to .prj file or project directory

required

Returns:

Type Description
list[TerrainInfo]

List of TerrainInfo in rasmap priority order

Source code in ras2cng/terrain.py
def discover_terrains(project_path: Path) -> list[TerrainInfo]:
    """Discover terrain layers from rasmap in priority order.

    Uses RasMap.get_terrain_names() + rasmap_df['terrain_hdf_path'].
    For each terrain HDF, discovers associated .tif files in same directory.

    Args:
        project_path: Path to .prj file or project directory

    Returns:
        List of TerrainInfo in rasmap priority order
    """
    from ras2cng.project import resolve_project_path
    from ras_commander import init_ras_project

    project_dir, prj_file = resolve_project_path(Path(project_path))
    ras = init_ras_project(project_dir, ras_object="new", load_results_summary=False)

    terrains: list[TerrainInfo] = []

    # Try to get terrain names from rasmap
    terrain_names = _get_terrain_names_safe(project_dir)

    # Try to get terrain HDF paths from rasmap_df
    terrain_hdf_paths: dict[str, Path] = {}
    if ras.rasmap_df is not None and not ras.rasmap_df.empty:
        if "terrain_hdf_path" in ras.rasmap_df.columns:
            for _, row in ras.rasmap_df.iterrows():
                hdf_p = row.get("terrain_hdf_path")
                name = row.get("terrain_name", "")
                if hdf_p and str(hdf_p).strip():
                    terrain_hdf_paths[str(name)] = Path(str(hdf_p))

    # If no rasmap terrain info, fall back to scanning Terrain/ directory
    if not terrain_names and not terrain_hdf_paths:
        terrain_dir = project_dir / "Terrain"
        if terrain_dir.exists():
            hdf_files = sorted(terrain_dir.glob("*.hdf"))
            for hdf_f in hdf_files:
                name = hdf_f.stem
                tif_files = _discover_tifs_for_hdf(hdf_f)
                info = _get_raster_info(tif_files)
                terrains.append(TerrainInfo(
                    name=name,
                    hdf_path=hdf_f,
                    hdf_exists=hdf_f.exists(),
                    tif_files=tif_files,
                    crs=info.get("crs"),
                    resolution=info.get("resolution"),
                    bounds=info.get("bounds"),
                    total_size_mb=sum(f.stat().st_size for f in tif_files if f.exists()) / (1024 * 1024),
                    modifications=_modification_status_safe(hdf_f, project_dir, prj_file),
                ))
            # Also check for standalone TIFs
            if not hdf_files:
                tif_files = _glob_tifs(terrain_dir)
                if tif_files:
                    info = _get_raster_info(tif_files)
                    terrains.append(TerrainInfo(
                        name="Terrain",
                        tif_files=tif_files,
                        crs=info.get("crs"),
                        resolution=info.get("resolution"),
                        bounds=info.get("bounds"),
                        total_size_mb=sum(f.stat().st_size for f in tif_files if f.exists()) / (1024 * 1024),
                    ))
        return terrains

    # Build terrain info from rasmap data
    seen_names = set()
    for name in terrain_names or list(terrain_hdf_paths.keys()):
        if name in seen_names:
            continue
        seen_names.add(name)

        hdf_path = terrain_hdf_paths.get(name)
        if hdf_path and not hdf_path.is_absolute():
            hdf_path = project_dir / hdf_path

        tif_files = _discover_tifs_for_hdf(hdf_path) if hdf_path else []
        # Also check Terrain/ directory for TIFs matching the name
        if not tif_files:
            terrain_dir = project_dir / "Terrain"
            if terrain_dir.exists():
                all_tifs = _glob_tifs(terrain_dir)
                # Exact stem match: "Terrain" matches "Terrain.tif" and
                # "Terrain_tile2.tif" but NOT "TerrainWithChannel.tif"
                tif_files = sorted(
                    f for f in all_tifs
                    if _stem_matches_name(f.stem, name)
                )

        info = _get_raster_info(tif_files)
        terrains.append(TerrainInfo(
            name=name,
            hdf_path=hdf_path,
            hdf_exists=hdf_path.exists() if hdf_path else False,
            tif_files=tif_files,
            crs=info.get("crs"),
            resolution=info.get("resolution"),
            bounds=info.get("bounds"),
            total_size_mb=sum(f.stat().st_size for f in tif_files if f.exists()) / (1024 * 1024),
            modifications=_modification_status_safe(hdf_path, project_dir, prj_file),
        ))

    return terrains

ras2cng.terrain.consolidate_terrain(project_path, output_dir, *, terrain_name='Consolidated', downsample_factor=None, target_resolution=None, terrain_names=None, horizontal_units='Feet', units='Feet', ras_version='6.6', create_hdf=True, register_rasmap=True)

Consolidate project terrains and create a new HEC-RAS terrain HDF.

Full pipeline: 1. Discover terrain TIFFs from rasmap (priority ordered) 2. Merge via rasterio.merge.merge(method='first') -- first wins in overlaps 3. Optionally downsample (reduce resolution) 4. Create HEC-RAS terrain HDF via RasTerrain.create_terrain_from_rasters() 5. Register new terrain in rasmap via RasMap.add_terrain_layer()

Steps 4-5 require RasProcess.exe. If create_hdf=False, only produces the merged TIFF (useful for exporting to cloud-native COG pipeline).

Parameters:

Name Type Description Default
project_path Path

Path to .prj file or project directory

required
output_dir Path

Directory for output terrain files

required
terrain_name str

Name for the consolidated terrain (default: "Consolidated")

'Consolidated'
downsample_factor Optional[float]

Factor to reduce resolution (2.0 = half resolution)

None
target_resolution Optional[float]

Target cell size in project units (overrides downsample_factor)

None
terrain_names Optional[list[str]]

One named terrain to consolidate. Required when the project contains multiple named terrains.

None
horizontal_units str

Horizontal raster units (Feet or Meters), used to enforce the five-foot publication floor.

'Feet'
units str

Vertical units "Feet" or "Meters"

'Feet'
ras_version str

HEC-RAS version for RasProcess.exe

'6.6'
create_hdf bool

If True, create HEC-RAS terrain HDF (requires RasProcess.exe)

True
register_rasmap bool

If True, register new terrain in project rasmap

True

Returns:

Type Description
Path

Path to consolidated terrain HDF (if create_hdf) or TIFF (if not)

Source code in ras2cng/terrain.py
def consolidate_terrain(
    project_path: Path,
    output_dir: Path,
    *,
    terrain_name: str = "Consolidated",
    downsample_factor: Optional[float] = None,
    target_resolution: Optional[float] = None,
    terrain_names: Optional[list[str]] = None,
    horizontal_units: str = "Feet",
    units: str = "Feet",
    ras_version: str = "6.6",
    create_hdf: bool = True,
    register_rasmap: bool = True,
) -> Path:
    """Consolidate project terrains and create a new HEC-RAS terrain HDF.

    Full pipeline:
    1. Discover terrain TIFFs from rasmap (priority ordered)
    2. Merge via rasterio.merge.merge(method='first') -- first wins in overlaps
    3. Optionally downsample (reduce resolution)
    4. Create HEC-RAS terrain HDF via RasTerrain.create_terrain_from_rasters()
    5. Register new terrain in rasmap via RasMap.add_terrain_layer()

    Steps 4-5 require RasProcess.exe. If create_hdf=False, only produces
    the merged TIFF (useful for exporting to cloud-native COG pipeline).

    Args:
        project_path: Path to .prj file or project directory
        output_dir: Directory for output terrain files
        terrain_name: Name for the consolidated terrain (default: "Consolidated")
        downsample_factor: Factor to reduce resolution (2.0 = half resolution)
        target_resolution: Target cell size in project units (overrides downsample_factor)
        terrain_names: One named terrain to consolidate. Required when the
            project contains multiple named terrains.
        horizontal_units: Horizontal raster units (Feet or Meters), used to
            enforce the five-foot publication floor.
        units: Vertical units "Feet" or "Meters"
        ras_version: HEC-RAS version for RasProcess.exe
        create_hdf: If True, create HEC-RAS terrain HDF (requires RasProcess.exe)
        register_rasmap: If True, register new terrain in project rasmap

    Returns:
        Path to consolidated terrain HDF (if create_hdf) or TIFF (if not)
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Step 1: Discover terrains
    terrains = discover_terrains(project_path)
    if not terrains:
        raise ValueError("No terrain data found in project")

    # Select exactly one named terrain. TIFF members of that terrain are a
    # mosaic; separate named terrain surfaces are distinct model inputs.
    if terrain_names:
        if len(terrain_names) != 1:
            raise ValueError(
                "Consolidate one named terrain at a time; distinct named terrains "
                "must never be merged"
            )
        name_set = set(terrain_names)
        terrains = [t for t in terrains if t.name in name_set]
        if not terrains:
            raise ValueError(f"No terrains matching names: {terrain_names}")
    elif len(terrains) > 1:
        raise ValueError(
            "Multiple named terrains were discovered. Pass terrain_names=[<name>] "
            "and publish each named surface separately."
        )

    # Collect all TIF files in priority order
    all_tifs: list[Path] = []
    for t in terrains:
        all_tifs.extend(t.tif_files)

    if not all_tifs:
        raise ValueError("No TIFF files found for terrain consolidation")

    # Step 2: Merge TIFFs and record the publication-resolution decision.
    final_tif = consolidate_terrain_files(
        all_tifs,
        output_dir,
        terrain_name=terrain_name,
        source_terrain_name=terrains[0].name,
        downsample_factor=downsample_factor,
        target_resolution=target_resolution,
        horizontal_units=horizontal_units,
    )

    # Step 4: Create HEC-RAS terrain HDF (requires RasProcess.exe)
    if not create_hdf:
        console.print(f"[green]OK[/green] TIFF-only mode: {final_tif}")
        return final_tif

    try:
        from ras_commander import RasTerrain

        from ras2cng.project import resolve_project_path
        project_dir, prj_file = resolve_project_path(Path(project_path))

        terrain_hdf = RasTerrain.create_terrain_from_rasters(
            input_rasters=[final_tif],
            output_folder=output_dir,
            terrain_name=terrain_name,
            units=units,
            hecras_version=ras_version,
        )
        terrain_hdf = Path(terrain_hdf)
        console.print(f"  HEC-RAS terrain HDF -> {terrain_hdf.name}")
    except ImportError:
        console.print("[yellow]Warning:[/yellow] RasTerrain not available; returning TIFF only")
        return final_tif
    except Exception as e:
        console.print(f"[yellow]Warning:[/yellow] Terrain HDF creation failed: {e}")
        console.print("  Returning merged TIFF instead")
        return final_tif

    # Step 5: Register in rasmap
    if register_rasmap:
        try:
            from ras_commander import RasMap

            rasmap_path = project_dir / f"{prj_file.stem}.rasmap"
            if rasmap_path.exists():
                RasMap.add_terrain_layer(
                    terrain_hdf=terrain_hdf,
                    rasmap_path=rasmap_path,
                    layer_name=terrain_name,
                )
                console.print(f"  Registered in rasmap: {rasmap_path.name}")
        except Exception as e:
            console.print(f"[yellow]Warning:[/yellow] Could not register terrain in rasmap: {e}")

    console.print(f"[green]OK[/green] Terrain consolidation complete: {terrain_hdf}")
    return terrain_hdf

ras2cng.terrain.consolidate_terrain_files(tif_files, output_dir, *, terrain_name='Consolidated', source_terrain_name=None, downsample_factor=None, target_resolution=None, horizontal_units='Feet', source_paths=None)

Consolidate an explicit, priority-ordered terrain TIFF mosaic.

This entry point supports projects whose RAS Mapper paths cannot be resolved on the processing host. The first source wins where valid pixels overlap, and the normal no-upsample publication policy is always enforced.

Source code in ras2cng/terrain.py
def consolidate_terrain_files(
    tif_files: list[Path],
    output_dir: Path,
    *,
    terrain_name: str = "Consolidated",
    source_terrain_name: Optional[str] = None,
    downsample_factor: Optional[float] = None,
    target_resolution: Optional[float] = None,
    horizontal_units: str = "Feet",
    source_paths: Optional[list[str | Path]] = None,
) -> Path:
    """Consolidate an explicit, priority-ordered terrain TIFF mosaic.

    This entry point supports projects whose RAS Mapper paths cannot be resolved
    on the processing host. The first source wins where valid pixels overlap,
    and the normal no-upsample publication policy is always enforced.
    """

    sources = [Path(path) for path in tif_files]
    if not sources:
        raise ValueError("No TIFF files provided for terrain consolidation")

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    source_inventory = inspect_terrain_sources(sources)
    if source_paths is not None:
        if len(source_paths) != len(source_inventory):
            raise ValueError("source_paths must contain one display path per TIFF source")
        for item, display_path in zip(source_inventory, source_paths):
            item["path"] = Path(display_path).as_posix()

    native_resolutions = [
        max(item["resolution_x"], item["resolution_y"])
        for item in source_inventory
    ]
    if downsample_factor is not None and target_resolution is not None:
        raise ValueError("Use either downsample_factor or target_resolution, not both")

    requested_resolution = target_resolution
    if downsample_factor is not None:
        if downsample_factor < 1:
            raise ValueError("downsample_factor must be at least 1; upsampling is prohibited")
        requested_resolution = max(native_resolutions) * float(downsample_factor)

    decision = select_terrain_resolution(
        native_resolutions,
        requested=requested_resolution,
        horizontal_units=horizontal_units,
    )

    console.print(f"[bold]Terrain consolidation:[/bold] {len(sources)} TIFF(s)")
    merged_tif = output_dir / f"{terrain_name}_merged.tif"
    merge_engine, merge_fallback = select_terrain_merge_engine(sources)
    if merge_fallback:
        console.print(f"  [yellow]Note:[/yellow] terrain merge uses rasterio: {merge_fallback}")
    _merge_tifs(
        sources,
        merged_tif,
        target_resolution=decision.target_resolution,
        engine=merge_engine,
    )
    console.print(f"  Merged -> {merged_tif.name} ({merge_engine})")

    provenance = {
        "schema": "ras2cng.terrain-consolidation/v1",
        "terrain_name": source_terrain_name or terrain_name,
        "output_name": terrain_name,
        "source_priority": "first-valid-value-wins",
        "resampling": "bilinear",
        # "rasterio": one GDAL warp per 512-px destination block (the default).
        # "terrio": one whole-output warp, bit-identical to GDAL's own
        # whole-output painter warp; opt-in (RAS2CNG_TERRAIN_MERGE_ENGINE).
        "merge_engine": merge_engine,
        "merge_engine_fallback_reason": merge_fallback,
        "resolution": asdict(decision),
        "sources": source_inventory,
        "output": merged_tif.name,
    }
    provenance_path = output_dir / f"{terrain_name}_terrain-provenance.json"
    provenance_path.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8")
    console.print(f"  Provenance -> {provenance_path.name}")
    return merged_tif

ras2cng.terrain.consolidate_project_terrains(project_path, output_dir, *, target_resolutions=None, horizontal_units='Feet')

Consolidate TIFF members separately for every named project terrain.

Source code in ras2cng/terrain.py
def consolidate_project_terrains(
    project_path: Path,
    output_dir: Path,
    *,
    target_resolutions: Optional[dict[str, float]] = None,
    horizontal_units: str = "Feet",
) -> dict[str, Path]:
    """Consolidate TIFF members separately for every named project terrain."""

    terrains = discover_terrains(project_path)
    if not terrains:
        raise ValueError("No terrain data found in project")
    targets = target_resolutions or {}
    unknown = sorted(set(targets) - {terrain.name for terrain in terrains})
    if unknown:
        raise ValueError(f"Target resolutions reference unknown terrains: {unknown}")

    outputs: dict[str, Path] = {}
    used_names: set[str] = set()
    for terrain in terrains:
        slug = re.sub(r"[^A-Za-z0-9]+", "_", terrain.name).strip("_") or "Terrain"
        output_name = slug
        suffix = 2
        while output_name.lower() in used_names:
            output_name = f"{slug}_{suffix}"
            suffix += 1
        used_names.add(output_name.lower())
        outputs[terrain.name] = consolidate_terrain(
            project_path,
            output_dir,
            terrain_name=output_name,
            terrain_names=[terrain.name],
            target_resolution=targets.get(terrain.name),
            horizontal_units=horizontal_units,
            create_hdf=False,
            register_rasmap=False,
        )
    return outputs

ras2cng.terrain.export_modified_terrain(project_path, output_tif, *, geometry=None, terrain_name=None, downsample_factor=1, overwrite=False, hecras_version=None)

Export a registered terrain with modifications applied as one GeoTIFF.

Delegates consolidation, grid alignment, nearest-neighbor downsampling, and vector-modification rasterization to RAS Mapper's native terrain export. Registered source priority, stitches, and masks are therefore preserved.

HEC-RAS 6.4.1, 6.5, 6.6, and 7.0.1 are qualified on Windows and Wine. Stable 7.1 is forward-open subject to ras-commander's managed-contract check. Unsupported project/runtime versions fail before native execution.

Parameters:

Name Type Description Default
project_path Path

Path to .prj file or project directory

required
output_tif Path

Output GeoTIFF path

required
geometry Optional[str]

Deprecated compatibility argument. Native registered-terrain export does not use a geometry HDF, so any supplied value is ignored.

None
terrain_name Optional[str]

Exact registered terrain name. May be omitted only when the project registers exactly one terrain.

None
downsample_factor int

Exact source-derived factor: 1, 2, 4, or 8.

1
overwrite bool

Replace an existing output and receipt when true.

False
hecras_version Optional[str]

Installed HEC-RAS version to export with (e.g. "7.0.1"). None lets ras-commander choose from the project.

None

Returns:

Type Description
Path

Path to the output GeoTIFF

Raises:

Type Description
RuntimeError

If ras-commander lacks native terrain export support or RAS Mapper reports an operational failure.

Source code in ras2cng/terrain.py
def export_modified_terrain(
    project_path: Path,
    output_tif: Path,
    *,
    geometry: Optional[str] = None,
    terrain_name: Optional[str] = None,
    downsample_factor: int = 1,
    overwrite: bool = False,
    hecras_version: Optional[str] = None,
) -> Path:
    """Export a registered terrain with modifications applied as one GeoTIFF.

    Delegates consolidation, grid alignment, nearest-neighbor downsampling, and
    vector-modification rasterization to RAS Mapper's native terrain export.
    Registered source priority, stitches, and masks are therefore preserved.

    HEC-RAS 6.4.1, 6.5, 6.6, and 7.0.1 are qualified on Windows and Wine.
    Stable 7.1 is forward-open subject to ras-commander's managed-contract
    check. Unsupported project/runtime versions fail before native execution.

    Args:
        project_path: Path to .prj file or project directory
        output_tif: Output GeoTIFF path
        geometry: Deprecated compatibility argument. Native registered-terrain
            export does not use a geometry HDF, so any supplied value is ignored.
        terrain_name: Exact registered terrain name. May be omitted only when
            the project registers exactly one terrain.
        downsample_factor: Exact source-derived factor: 1, 2, 4, or 8.
        overwrite: Replace an existing output and receipt when true.
        hecras_version: Installed HEC-RAS version to export with (e.g.
            "7.0.1"). None lets ras-commander choose from the project.

    Returns:
        Path to the output GeoTIFF

    Raises:
        RuntimeError: If ras-commander lacks native terrain export support or
            RAS Mapper reports an operational failure.
    """
    from ras_commander import RasTerrain, init_ras_project
    from ras2cng.project import resolve_project_path

    _, prj_file = resolve_project_path(Path(project_path))
    if geometry is not None:
        warnings.warn(
            "export_modified_terrain(..., geometry=...) is deprecated because "
            "native registered-terrain export does not use a geometry HDF; the "
            "argument is ignored and will be removed in ras2cng 1.1.",
            DeprecationWarning,
            stacklevel=2,
        )

    export_native = getattr(RasTerrain, "export_rasmapper_terrain", None)
    if not callable(export_native):
        raise RuntimeError(
            "The installed ras-commander does not provide native registered-terrain "
            "export. Upgrade to a release containing "
            "RasTerrain.export_rasmapper_terrain()."
        )

    # The project object's version must agree with the export runtime, or
    # ras-commander uses (and rejects) the version stored in the project.
    ras = init_ras_project(
        prj_file,
        ras_object="new",
        load_results_summary=False,
        **({"ras_version": hecras_version} if hecras_version else {}),
    )

    console.print(f"\n[bold cyan]ras2cng terrain-mod[/bold cyan] -> {output_tif}")
    console.print(f"  Project  : {prj_file.name}")
    console.print(f"  Terrain  : {terrain_name or '[auto: single registered terrain]'}")
    console.print(f"  Scale    : {downsample_factor}x source resolution")
    console.print("  Exporting through native RAS Mapper...")

    result = export_native(
        **({"hecras_version": hecras_version} if hecras_version else {}),
        ras_project_path=prj_file,
        output_tif=Path(output_tif),
        terrain_name=terrain_name,
        downsample_factor=downsample_factor,
        rasterize_modifications=True,
        overwrite=overwrite,
        ras_object=ras,
    )
    if not result:
        detail = getattr(result, "error", None) or "RAS Mapper terrain export failed"
        receipt = getattr(result, "receipt_path", None)
        if receipt:
            detail = f"{detail} (receipt: {receipt})"
        raise RuntimeError(detail)

    committed_output = Path(result.output_path)
    console.print(f"  Terrain  : {result.terrain_name}")
    console.print(f"  Receipt  : {result.receipt_path}")
    console.print(f"[green]OK[/green] Modified terrain raster: {committed_output}")
    return committed_output

ras2cng.terrain.extract_terrain_source_footprints(tif_files, *, out_crs=None)

Build one queryable footprint polygon per native terrain TIFF member.

Source code in ras2cng/terrain.py
def extract_terrain_source_footprints(
    tif_files: list[Path],
    *,
    out_crs: Optional[str] = None,
):
    """Build one queryable footprint polygon per native terrain TIFF member."""

    import geopandas as gpd
    import pandas as pd
    import rasterio
    from shapely.geometry import box

    frames = []
    for priority, path in enumerate(tif_files):
        path = Path(path)
        with rasterio.open(path) as source:
            if source.crs is None:
                raise ValueError(f"Terrain source has no CRS: {path}")
            frame = gpd.GeoDataFrame(
                {
                    "priority": [priority],
                    "source_file": [path.name],
                    "size_bytes": [path.stat().st_size],
                    "source_crs": [source.crs.to_string()],
                    "resolution_x": [abs(float(source.res[0]))],
                    "resolution_y": [abs(float(source.res[1]))],
                    "width": [int(source.width)],
                    "height": [int(source.height)],
                    "dtype": [str(source.dtypes[0])],
                    "nodata": [None if source.nodata is None else float(source.nodata)],
                },
                geometry=[box(*source.bounds)],
                crs=source.crs,
            )
            if out_crs:
                frame = frame.to_crs(out_crs)
            frames.append(frame)
    if not frames:
        return gpd.GeoDataFrame(geometry=[], crs=out_crs)
    target_crs = frames[0].crs
    normalized = [
        frame if frame.crs == target_crs else frame.to_crs(target_crs)
        for frame in frames
    ]
    return gpd.GeoDataFrame(
        pd.concat(normalized, ignore_index=True),
        geometry="geometry",
        crs=target_crs,
    )

ras2cng.terrain.extract_terrain_modification_layers(terrain_hdf_path, *, crs=None)

Read RASMapper terrain modification vectors from a terrain HDF.

Each /Modifications/<layer> group can hold several features; every feature becomes its own row (feature_index within the layer, with that feature's own Attributes row).

Returns four GeoDataFrames (always present, possibly empty):

  • terrain_modification_lines: line, levee and channel centrelines with their width (top width), left_slope, right_slope and max_extent (RAS Mapper's "Max Reach": how far either side of the centreline the modification may change the terrain).
  • terrain_modification_polygons: polygon modifications, and the outlines of pier, rectangle, ellipse and triangle modifications (shape_type), built from their stored parameters the way RAS Mapper builds them.
  • terrain_modification_footprints: one polygon per feature covering the terrain the feature can change. Lines are buffered by max_extent (or by half the top width when no max extent is stored; footprint_basis says which and footprint_half_width by how much); polygons and shapes are their own footprint. A line with neither value has no footprint row.
  • terrain_modification_control_points.

Parameters:

Name Type Description Default
terrain_hdf_path Path

HEC-RAS terrain HDF.

required
crs Optional[str]

CRS to assign (default: the terrain HDF's projection).

None

Raises:

Type Description
FileNotFoundError

The terrain HDF does not exist.

ValueError

No CRS is given and the HDF has none.

Source code in ras2cng/terrain.py
def extract_terrain_modification_layers(
    terrain_hdf_path: Path,
    *,
    crs: Optional[str] = None,
) -> dict[str, object]:
    """Read RASMapper terrain modification vectors from a terrain HDF.

    Each ``/Modifications/<layer>`` group can hold several features; every
    feature becomes its own row (``feature_index`` within the layer, with that
    feature's own ``Attributes`` row).

    Returns four GeoDataFrames (always present, possibly empty):

    * ``terrain_modification_lines``: line, levee and channel centrelines with
      their ``width`` (top width), ``left_slope``, ``right_slope`` and
      ``max_extent`` (RAS Mapper's "Max Reach": how far either side of the
      centreline the modification may change the terrain).
    * ``terrain_modification_polygons``: polygon modifications, and the
      outlines of pier, rectangle, ellipse and triangle modifications
      (``shape_type``), built from their stored parameters the way RAS Mapper
      builds them.
    * ``terrain_modification_footprints``: one polygon per feature covering
      the terrain the feature can change. Lines are buffered by ``max_extent``
      (or by half the top width when no max extent is stored;
      ``footprint_basis`` says which and ``footprint_half_width`` by how
      much); polygons and shapes are their own footprint. A line with neither
      value has no footprint row.
    * ``terrain_modification_control_points``.

    Args:
        terrain_hdf_path: HEC-RAS terrain HDF.
        crs: CRS to assign (default: the terrain HDF's projection).

    Raises:
        FileNotFoundError: The terrain HDF does not exist.
        ValueError: No CRS is given and the HDF has none.
    """

    import geopandas as gpd
    import h5py
    from ras_commander.hdf import HdfBase
    from ras_commander.terrain import RasTerrainModWriter

    terrain_hdf_path = Path(terrain_hdf_path)
    if not terrain_hdf_path.is_file():
        raise FileNotFoundError(f"Terrain HDF does not exist: {terrain_hdf_path}")
    source_crs = crs
    if source_crs is None:
        try:
            source_crs = HdfBase.get_projection(terrain_hdf_path)
        except Exception:
            source_crs = None
    if not source_crs:
        raise ValueError(
            f"Terrain modifications require a validated CRS: {terrain_hdf_path}"
        )

    metadata = RasTerrainModWriter.list_modifications(terrain_hdf_path)
    metadata_by_name = {
        str(row["name"]): row.to_dict()
        for _, row in metadata.iterrows()
    }
    rows: dict[str, list[dict]] = {name: [] for name in TERRAIN_MODIFICATION_LAYERS}
    with h5py.File(terrain_hdf_path, "r") as hdf:
        modifications = hdf.get("Modifications")
        if modifications is not None:
            for name, group in modifications.items():
                if isinstance(group, h5py.Group):
                    _collect_modification_group(
                        name, group, metadata_by_name.get(name, {}), rows
                    )

    return {
        layer: gpd.GeoDataFrame(
            records if records else {"geometry": []}, geometry="geometry", crs=source_crs
        )
        for layer, records in rows.items()
    }

ras2cng.terrain.terrain_modification_status(terrain_hdf, rasmap_path=None)

Which of a terrain's modifications RAS Mapper applies in a project.

Parameters:

Name Type Description Default
terrain_hdf Path

The terrain HDF.

required
rasmap_path Optional[Path]

The project's .rasmap. Without it every stored layer counts as active (basis="hdf").

None

Returns:

Type Description
TerrainModificationStatus

class:TerrainModificationStatus.

Source code in ras2cng/terrain.py
def terrain_modification_status(
    terrain_hdf: Path, rasmap_path: Optional[Path] = None
) -> TerrainModificationStatus:
    """Which of a terrain's modifications RAS Mapper applies in a project.

    Args:
        terrain_hdf: The terrain HDF.
        rasmap_path: The project's ``.rasmap``. Without it every stored
            layer counts as active (``basis="hdf"``).

    Returns:
        :class:`TerrainModificationStatus`.
    """
    import xml.etree.ElementTree as ET

    terrain_hdf = Path(terrain_hdf)
    stored, problems = _stored_terrain_modifications(terrain_hdf)
    rasmap = Path(rasmap_path) if rasmap_path is not None else None
    status = TerrainModificationStatus(
        terrain_hdf=str(terrain_hdf),
        rasmap=str(rasmap) if rasmap is not None else None,
        stored=stored,
        active=list(stored),
        problems=problems,
    )
    if rasmap is None or not rasmap.is_file():
        return status
    try:
        scope = _rasmap_terrain_scope(terrain_hdf, rasmap)
    except (ET.ParseError, OSError) as exc:
        status.problems.append(f"rasmap: unreadable ({exc})")
        return status
    if scope is None:
        status.problems.append(f"rasmap: no terrain layer for {terrain_hdf.name}")
        return status
    registered, applied = scope
    status.registered = registered
    status.basis = "rasmap"
    if applied:
        # Every stored layer applies; a listed layer the HDF lacks stays
        # visible (and keeps the terrain off the native route).
        status.active = list(dict.fromkeys([*stored, *registered]))
    else:
        status.active = []
    return status

ras2cng.terrain.active_terrain_modifications(terrain_hdf, rasmap_path=None)

Labels of the modifications RAS Mapper applies, or [].

Use this, not :func:terrain_modifications, wherever modifications change mapping or routing. See :func:terrain_modification_status.

Source code in ras2cng/terrain.py
def active_terrain_modifications(
    terrain_hdf: Path, rasmap_path: Optional[Path] = None
) -> list[str]:
    """Labels of the modifications RAS Mapper applies, or ``[]``.

    Use this, not :func:`terrain_modifications`, wherever modifications
    change mapping or routing. See :func:`terrain_modification_status`.
    """
    return terrain_modification_status(terrain_hdf, rasmap_path).active_labels()

ras2cng.terrain.TerrainModificationStatus dataclass

Stored vs active terrain modifications for one terrain in one project.

RAS Mapper (HEC-RAS 6.6, 7.0.1) applies a terrain HDF's modification layers only when the project's .rasmap terrain layer has an ElevationModificationGroup named exactly Modifications. With one, it applies every layer the HDF stores: the group's per-layer entries and their Checked state are not consulted (T14; ras-commander RasFim.top_priority_terrain_source). Without one (no group, or only a group under another name) it applies none: a RAS Mapper export through such a project was identical to the unmodified terrain.

A modified terrain goes to RAS Mapper's export unless the engine advertises rasmapper-effective-terrain/2 and every modification form is qualified (see fast_map.TerrainResolver.modified_route).

Attributes:

Name Type Description
terrain_hdf str

The terrain HDF.

rasmap Optional[str]

The .rasmap read, or None.

stored list[str]

Layer names in the HDF's /Modifications group.

registered list[str]

Layer names the .rasmap lists under this terrain (in any ElevationModificationGroup; informational).

active list[str]

What RAS Mapper applies: every stored layer (plus any listed layer the HDF lacks) when the terrain layer has a Modifications group, none when it has not, and every stored layer when there is no .rasmap or the terrain is not in it, so an unknown activation never reads as unmodified.

basis str

"rasmap" or "hdf" (the fallback above).

problems list[str]

An unreadable or linked /Modifications group, or an unreadable .rasmap. A problem in the HDF counts as active.

Source code in ras2cng/terrain.py
@dataclass
class TerrainModificationStatus:
    """Stored vs active terrain modifications for one terrain in one project.

    RAS Mapper (HEC-RAS 6.6, 7.0.1) applies a terrain HDF's modification
    layers only when the project's ``.rasmap`` terrain layer has an
    ``ElevationModificationGroup`` named exactly ``Modifications``. With
    one, it applies every layer the HDF stores: the group's per-layer
    entries and their ``Checked`` state are not consulted (T14;
    ras-commander ``RasFim.top_priority_terrain_source``). Without one (no
    group, or only a group under another name) it applies none: a RAS Mapper
    export through such a project was identical to the unmodified terrain.

    A modified terrain goes to RAS Mapper's export unless the engine
    advertises ``rasmapper-effective-terrain/2`` and every modification form
    is qualified (see ``fast_map.TerrainResolver.modified_route``).

    Attributes:
        terrain_hdf: The terrain HDF.
        rasmap: The ``.rasmap`` read, or ``None``.
        stored: Layer names in the HDF's ``/Modifications`` group.
        registered: Layer names the ``.rasmap`` lists under this terrain
            (in any ``ElevationModificationGroup``; informational).
        active: What RAS Mapper applies: every ``stored`` layer (plus any
            listed layer the HDF lacks) when the terrain layer has a
            ``Modifications`` group, none when it has not, and every
            ``stored`` layer when there is no ``.rasmap`` or the terrain is
            not in it, so an unknown activation never reads as unmodified.
        basis: ``"rasmap"`` or ``"hdf"`` (the fallback above).
        problems: An unreadable or linked ``/Modifications`` group, or an
            unreadable ``.rasmap``. A problem in the HDF counts as active.
    """

    terrain_hdf: str
    rasmap: Optional[str]
    stored: list[str] = field(default_factory=list)
    registered: list[str] = field(default_factory=list)
    active: list[str] = field(default_factory=list)
    basis: str = "hdf"
    problems: list[str] = field(default_factory=list)

    @property
    def inactive(self) -> list[str]:
        """Stored layers RAS Mapper does not apply in this project."""
        active = set(self.active)
        return [name for name in self.stored if name not in active]

    def active_labels(self) -> list[str]:
        """``hdf:``/``rasmap:`` labels of the active set, plus HDF problems.

        Empty only when nothing is applied and nothing is unknown.
        """
        stored = set(self.stored)
        labels = [
            f"hdf:{name}" if name in stored else f"rasmap:{name} (not in the HDF)"
            for name in self.active
        ]
        return labels + [p for p in self.problems if p.startswith("hdf:")]

    def to_dict(self) -> dict:
        record = asdict(self)
        record["inactive"] = self.inactive
        return record

inactive property

Stored layers RAS Mapper does not apply in this project.

active_labels()

hdf:/rasmap: labels of the active set, plus HDF problems.

Empty only when nothing is applied and nothing is unknown.

Source code in ras2cng/terrain.py
def active_labels(self) -> list[str]:
    """``hdf:``/``rasmap:`` labels of the active set, plus HDF problems.

    Empty only when nothing is applied and nothing is unknown.
    """
    stored = set(self.stored)
    labels = [
        f"hdf:{name}" if name in stored else f"rasmap:{name} (not in the HDF)"
        for name in self.active
    ]
    return labels + [p for p in self.problems if p.startswith("hdf:")]