Terrain Modules¶
Classes for terrain creation, terrain modification writing, and terrain modification analysis.
Platform Requirements
RasTerrainMod requires Windows with pythonnet and a HEC-RAS installation (uses RasMapperLib.dll via .NET interop). RasTerrain.export_rasmapper_terrain() runs natively on Windows and through a configured Wine runtime on Linux. Other RasTerrain and RasTerrainModWriter methods retain their documented platform requirements.
RasTerrain¶
Terrain HDF creation from rasters using RasProcess.exe CreateTerrain.
Terrain Creation Methods¶
create_terrain_hdf(input_rasters, output_hdf, projection_prj, units="Feet", stitch=True, hecras_version="7.0", timeout_seconds=600)- Create HEC-RAS terrain HDF from input rasterscreate_terrain_from_rasters(input_rasters, output_folder, terrain_name="Terrain", units="Feet", stitch=True, hecras_version="7.0", generate_prj=True)- Convenience wrapper with automatic PRJ generation
Native Registered-Terrain Export¶
export_rasmapper_terrain(ras_project_path, output_tif, terrain_name=None, extent=None, downsample_factor=1, rasterize_modifications=True, overwrite=False, timeout_seconds=1800, hecras_version=None, ras_object=None, receipt_path=None)- Consolidate a registered RAS Mapper terrain to one semantically validated GeoTIFF
The native export loads the exact terrain entry from the project's .rasmap.
Consequently, source priority/order, stitches, masks, and terrain-modification
surfaces remain HEC-RAS behavior. The base raster always uses nearest-neighbor
and the output cell size is exactly the finest registered source cell size
times 1, 2, 4, or 8. Requested bounds snap outward to the authoritative
source grid. Registered sources may have different, non-integer-related cell
sizes: the API passes the exact selected output cell size to RAS Mapper with
Export to Single Raster enabled, and RAS Mapper performs the consolidation
and downsampling using the loaded source order, stitches, and masks. Preflight
rejects only missing, non-finite, or non-positive level-zero source grids.
The method writes to a unique same-directory partial, validates the GeoTIFF,
then atomically promotes it. overwrite=False is the default. A JSON receipt
is written beside the TIFF by default, and the returned TerrainExportResult
is bool-compatible. The derivative is not registered back into the project.
Windows-drive and UNC project/input paths retain their supported normalization.
Direct output to a real UNC share is not qualified: the host stages its owned
GDAL junction beside the output, and Windows junction creation generally cannot
target a remote volume. This fails before export rather than silently changing
destinations. Write to a short local path, then copy the committed TIFF and
receipt to the share. A qualification path whose fully qualified helper response
name exceeded the legacy .NET 260-character limit also failed cleanly; long-path
output staging remains unqualified.
A failed export returns success=False with a failure_kind that callers can
act on without parsing the error text:
failure_kind |
Condition | Next action |
|---|---|---|
out_of_memory |
The helper raised .NET System.OutOfMemoryException, including when it is wrapped in a type-initializer exception |
Retry with more memory available to the helper process |
empty_extent |
RAS Mapper reported that its partial TIFF "does not have embedded statistics", and a full-resolution scan of every registered source that intersects the window found no valid cell | Skip the window, or pass empty_extent="nodata" |
empty_extent_unconfirmed |
RAS Mapper reported the same error, but the coverage scan could not read a source or rasterio is not installed | Check the source paths listed in empty_extent_check |
no_response, invalid_response |
The helper wrote no response file, or a response that failed schema validation | Inspect the exit code and stderr in helper_invocations |
native_error |
Any other exception reported by the helper | Read error and the helper response |
timeout, error |
The bounded runtime expired, or a host-side step such as GeoTIFF validation failed | Read error |
With empty_extent="nodata", a confirmed empty window produces an all-nodata
Float32 GeoTIFF (nodata -9999) on the snapped export grid, using the
.rasmap projection file's CRS, and the result sets empty_extent=True. If
the scan finds any valid cell, the export fails as native_error; RAS Commander
does not replace a native failure with nodata output.
helper_invocations records each native helper call: the request, process
exit code, parsed response, the last 20,000 characters of stderr, and a status.
The receipt carries the same records, so the evidence remains after the
task-local stage is removed. Under Wine, stderr often holds only the
XDG_RUNTIME_DIR is invalid or not set warning, which also appears in
successful runs. RAS Commander keeps that line in the record but never uses it
as the failure summary. A helper that reports success and then exits non-zero,
for example after a crash during runtime shutdown, is not treated as a failure.
Its response must still validate, an export's TIFF must exist, and the output
goes through the same semantic GeoTIFF validation. The record status is
success_nonzero_exit, and messages notes the exit code.
Supported HEC-RAS versions are deliberately narrow:
| Runtime | Status | Evidence |
|---|---|---|
| 6.3 / 6.3.1 | Unsupported | The installed API lacks the bounded GenerateNewRasTerrain(..., resampleVecMods, ...) contract; its public single-file method always uses the full terrain extent |
| 6.4.0 | Unsupported | Not locally installed or qualified; HEC's 6.4.1 resolved issues report that creating a terrain in 6.4 could add 1.0 to elevations |
| 6.4.1 | Supported | Exact private contract reflected; bounded modification-aware, mixed-source, and two-source stitched exports qualified on native Windows and Wine |
| 6.5 | Supported | Exact private contract reflected; bounded modification-aware, mixed-source, and two-source stitched exports qualified on native Windows and Wine |
| 6.6 | Supported | Native Windows and Wine qualified with bounded modification-aware and stitched exports; HEC's 6.6 terrain manual explicitly documents the unified export options |
| 6.7 beta releases | Unsupported prereleases | HEC's archive lists Beta, Beta 2, Beta 3, Beta 4a, and Beta 5 before 7.0. The locally installed Beta 4-labeled and Beta 5 runtimes passed bounded checks, but the API accepts no beta runtime |
| 7.0.0 | Unsupported | Although the checked windows completed, HEC documents a terrain-modification export defect that can omit the minimum-Y portion of a modification |
| 7.0.1 | Supported | The official installer's signature was validated, then the installed runtime was reflected and qualified on native Windows and Wine after HEC reported the 7.0.0 defect fixed in 7.0.1 resolved issues. Bounded modification-aware, mixed-source, and stitched exports passed |
| 7.0.2 | Supported on Windows for bounded raster export | The helper selects the changed spatial-index overload at runtime. A bounded two-source BaldEagle export matched the 7.0.1 control byte for byte. Vector modifications and Wine remain unqualified on this release |
| 7.1 | Forward-open; not yet qualified | The API and installation discovery accept the exact 7.1 term so the official release can run when installed. The helper still verifies the exact managed method contract at runtime. The official HEC-RAS downloads page currently contains no HEC-RAS Classic 7.1 release |
| Other versions | Unsupported | Their exact mapper contract and semantics have not been qualified |
When ras_object is supplied, it must be an initialized RasPrj. The API
checks ras_object.ras_version and, when identifiable, the release folder in
ras_object.ras_exe_path before creating output directories or starting native
work. It raises ValueError for unsupported versions and for any mismatch
between the explicit version, project version, and executable release. The
existing 6.4 convenience term resolves to the qualified 6.4.1 installation;
an actual executable in a 6.4 folder remains rejected.
The four qualified releases all passed on native Windows and under Wine. The
Wine matrix used task-local runtime/project copies and nine successful receipts:
for each of 6.4.1, 6.5, and 7.0.1 it exported a bounded two-source Muncie terrain,
the mixed-resolution Terrain50 terrain with modifications disabled, and the
same terrain with modifications enabled. Arrays and validity masks were
pixel-identical across those three releases; the modification comparison raised
264 cells by 0.15625 to 9.625 feet while 1,769 control cells remained exactly
unchanged. HEC-RAS 6.6 additionally passed exact-input native-Windows/Wine
pixel-parity checks.
HEC-RAS 7.1 is deliberately forward-open rather than pre-qualified. Until HEC
publishes the binary, no claim is made about its export semantics. When the
release is installed, version discovery accepts 7.1, 7.1.0, 7.10, or
71; helper reflection fails closed if HEC changes the expected native contract.
from pathlib import Path
from ras_commander import RasMap, RasTerrain
project = Path(r"C:\Models\Example\Example.prj")
print(RasMap.list_terrain_layers(project)[["name", "resolved_path"]])
result = RasTerrain.export_rasmapper_terrain(
project,
Path(r"C:\Exports\channel_window_2x.tif"),
terrain_name="Terrain",
extent=(100000.0, 200000.0, 101000.0, 201000.0),
downsample_factor=2,
rasterize_modifications=True,
hecras_version="6.6",
)
if not result:
raise RuntimeError(result.error)
print(result.output_path)
print(result.receipt_path)
print(result.source_inventory)
On Linux, configure RasProcess.configure_wine() first. The host clones the
configured Wine prefix into task-local state by default. An orchestration
system that already supplies a prefix owned exclusively by the current task
may set RAS_COMMANDER_TERRAIN_WINE_PREFIX_IS_TASK_LOCAL=1; do not set it for
a shared prefix.
RasTerrainMod.compute_modified_terrain_raster() is deprecated as of 0.99.2
and is scheduled for removal in 1.1. It samples one horizontal
TerrainProfile per row of a caller-supplied GeoTIFF grid and interpolates the
profile onto cell centers. Existing callers may use it during the compatibility
window, but new code should call export_rasmapper_terrain() with
downsample_factor=1 and rasterize_modifications=True. Native export failures
are reported rather than rerouted through the numerically different sampler.
Utility Methods¶
vrt_to_tiff(vrt_path, output_path, compression="LZW", create_overviews=True, overview_levels=None, nodata_value=None, hecras_version="7.0")- Convert VRT to single optimized TIFF using HEC-RAS bundled GDALget_available_versions()- List installed HEC-RAS versions with terrain creation support
Bank Line Generation¶
compute_bank_lines(geom_path, crs=None, ras_object=None)- Generate bank-line geometry from cross-section bank stations
Usage¶
from ras_commander import RasTerrain
# Create terrain from rasters
terrain_hdf = RasTerrain.create_terrain_from_rasters(
input_rasters=["dem_north.tif", "dem_south.tif"],
output_folder="terrain/",
terrain_name="Project_Terrain",
units="Feet",
hecras_version="7.0",
)
RasTerrainModWriter¶
Line and polygon terrain modification HDF/.rasmap writing. Also available as the alias RasTerrainModification.
Line Modification Methods¶
add_high_ground_modification(terrain_hdf_path, rasmap_path, name, polyline_points, top_width=20.0, side_slope=2.0, ...)- Add levee/road terrain modification with trapezoidal profile along polyline (TakeHigher mode)add_fill_surface_modification(terrain_hdf_path, rasmap_path, name, polyline_points, top_width=20.0, side_slope=2.0, ...)- Add fill-surface (SetValue) modification along polylineadd_channel_modification(terrain_hdf_path, rasmap_path, name, polyline_points, width=50.0, depth=None, ..., *, elevation=None, profile_points=None, ...)- Add trapezoidal channel modification (TakeLower mode). The invert is an absolute elevation profile (profile_points,elevationor polyline Z);depthinstead sets it below the terrain source sampled at each vertex.
Ground lines are written as RAS Mapper saves them: Type=Levee, an empty System Name (a non-empty one sends even a lone line through RAS Mapper's system path and changes its footprint at bends; pass system_name only for an intended join), NaN Transition Percent, and an absolute profile in Profile Info/Profile Values. A new layer goes on top of the list (Priority 0, which wins), as in the RAS Mapper GUI; pass priority to place it elsewhere. HEC-RAS 6.6 and 7.0.1 exports of writer layers equal those of the same features authored in RAS Mapper.
Polygon and Ellipse Modification Methods¶
add_modification_polygon(terrain_hdf_path, name, polygon_coords, elevation_method="boundary_from_terrain", control_points=None, ..., elevation=None, priority=None, perimeter_control_points=None)- Add polygon modification: constant (elevation), vertex-Z (shape_z/provided, portable across 6.6 and 7.x), terrain-sampled boundary, or a boundary fromperimeter_control_points(outside the ring, withinelev_pt_tolerance; rendered identically by HEC-RAS 6.6, 6.7 Beta 4/5, 7.0, 7.0.1 and 7.0.2).control_pointsare interior mass pointsadd_ellipse_modification(terrain_hdf_path, rasmap_path, name, ellipses, mode="set_value")- Add ellipse/circle modifications (rotation in degrees)add_modification_layer(terrain_hdf_path, rasmap_path, layer)- Write one layer in theread_layersform (ground line, constant polygon, ellipse) back to a terrain
The RAS Mapper export (HEC-RAS 6.6 and 7.0.1) applies a terrain's HDF modifications only when its .rasmap terrain layer has an ElevationModificationGroup named exactly Modifications. Without that group, or with the group under any other name, the export applies none of them and reports nothing: a terrain written into a Hydroconnectors group exported unchanged, and renaming the group to Modifications applied it. The writers always register layers in Modifications. group_name accepts only "Modifications" (the default) and raises ValueError for any other name, before anything is written; an existing group under another name is renamed to Modifications, with a warning, because the terrain's other HDF layers then also apply. RasFim.top_priority_terrain_source(terrain_hdf, rasmap_path=...) flags an existing misnamed group in rasmap_warnings (code modification_group_misnamed) without changing either file.
Group Management¶
add_modification_group(terrain_hdf_path, rasmap_path, group_name="Modifications")- Add the emptyModificationsgroup to terrain HDF and.rasmap(no other group name is accepted)
Query Methods¶
list_modifications(terrain_hdf_path)- List all terrain modifications stored in HDF sidecar groupget_modification_profile(terrain_hdf_path, name)- Read modification station/elevation profile
To read the modification layers in the form the native effective-terrain
engine (rasmapper-effective-terrain/2) needs, with the reason for any form it
refuses, use
RasFim.read_terrain_modifications().
Analysis Methods¶
sample_modification_surface(terrain_hdf_path, name, points, existing_elevations=None, ...)- Evaluate line modification surface at XY pointsapply_modification_to_profile(terrain_hdf_path, name, profile, ...)- Apply line modification to existing terrain profilecompare_before_after_profiles(rasmap_existing, rasmap_modified, geom_hdf_path, x_coords, y_coords, ...)- Compare terrain profiles before/after modification
Usage¶
from ras_commander import RasTerrainModWriter
# Add a levee (high ground)
RasTerrainModWriter.add_high_ground_modification(
terrain_hdf_path="Terrain/Terrain.hdf",
rasmap_path="Project.rasmap",
name="Proposed Levee",
polyline_points=[(x1, y1), (x2, y2), (x3, y3)],
top_width=20.0,
side_slope=3.0,
elevation=25.0,
)
# Add a detention pond (polygon)
RasTerrainModWriter.add_modification_polygon(
terrain_hdf_path="Terrain/Terrain.hdf",
name="Detention Pond",
polygon_coords=[(x1, y1), (x2, y2), (x3, y3), (x4, y4)],
control_points=[(cx, cy, target_elev)],
mode="set_value",
rasmap_path="Project.rasmap",
)
RasTerrainMod¶
Terrain profile and volume comparison with modifications applied. Uses RasMapperLib.dll via pythonnet to sample the actual modified terrain surface.
Windows Only
Requires Windows, pythonnet, and an installed HEC-RAS version. Call setup_gdal_bridge() once before other methods.
Setup¶
setup_gdal_bridge(hecras_version="7.0", python_dir=None, create_junction=True)- Configure HEC-RAS GDAL runtime for pythonnet before loading
Terrain Sampling¶
get_terrain_extent(rasmap_path, geom_hdf_path, ras_object=None)- Get terrain bounding box with modifications appliedget_terrain_profile(rasmap_path, geom_hdf_path, x_coords, y_coords, filter_tolerance=0.01, ras_object=None)- Sample terrain elevation along polylineiter_terrain_point_elevations(rasmap_path, terrain_name, point_batches, cell_size, use_obstructions=True, nodata_values=(-9999.0,))- Read bounded original-coordinate Float64 batches as native Float32 elevations; isolated HEC-RAS 6.6, serial native calls of at most 65536 points with caller batch shape/order preserved, no interpolation/fallback.get_terrain_volume_elevation(rasmap_path, geom_hdf_path, x_coords, y_coords, ...)- Compute elevation-volume curve for polygon
Comparison Methods¶
compare_terrain_profiles(rasmap_existing, rasmap_proposed, geom_hdf_path, x_coords, y_coords, ...)- Compare terrain profiles between existing and proposed (cut/fill analysis)compare_terrain_volumes(rasmap_existing, rasmap_proposed, geom_hdf_path, x_coords, y_coords, ...)- Compare elevation-volume curves for no-net-fill analysis
Raster Export¶
compute_modified_terrain_raster(rasmap_path, geom_hdf_path, terrain_tif_path, output_tif_path=None, ...)- Deprecated: row-sampled compatibility raster; useRasTerrain.export_rasmapper_terrain()
Usage¶
from ras_commander.terrain import RasTerrainMod
# One-time setup
RasTerrainMod.setup_gdal_bridge("7.0")
# Compare existing vs proposed terrain along a profile
comparison = RasTerrainMod.compare_terrain_profiles(
rasmap_existing="Existing.rasmap",
rasmap_proposed="Proposed.rasmap",
geom_hdf_path="Model.g01.hdf",
x_coords=[x1, x2, x3],
y_coords=[y1, y2, y3],
)
print(comparison[['station', 'existing_elevation', 'proposed_elevation', 'difference']])
Usgs3depAws¶
USGS 3DEP elevation acquisition from the public AWS S3 bucket, plus VRT mosaicking with HEC-RAS bundled GDAL. Direct download currently covers the 1m project-based products; 10m and 30m are discovery only.
Discovery Methods¶
download_tile_index(resolution, cache_folder=None)- Download and cache the spatial metadata GeoPackagequery_tiles_api(bbox, resolution, buffer_distance=0.0)- Query the National Map tile index REST APIfind_tiles_for_bbox(bbox, resolution, cache_folder=None, buffer_distance=0.0)- Projects intersecting a WGS84 extentlist_projects_for_bbox(bbox, resolution, cache_folder=None, buffer_distance=0.0)- Same, with_yearparsed from project namesselect_projects_for_coverage(projects, bbox, min_coverage_fraction=0.999, min_project_area_fraction=0.0)- Newest project per sub-area, plus a coverage report
Download Methods¶
download_tiles(bbox, resolution, output_folder, cache_folder=None, overwrite_dest=False, max_workers=3, project_name=None, min_year=None, buffer_distance=0.0, *, project_selection="newest", min_coverage_fraction=0.999, min_project_area_fraction=0.0, return_provenance=False, exclude_tile_ids=None)- Download the intersecting 1m tiles
project_selection controls what happens when several projects intersect the
extent:
| Mode | Behavior |
|---|---|
"newest" (default) |
Keeps only the single most recent project. Any sub-area that project does not cover is silently absent from the mosaic. |
"coverage" |
Greedily covers the extent with the newest project available per sub-area, falls back to older projects only for the residual geometry, logs each project's contributed area, and warns when the extent cannot be fully covered. Tiles are returned oldest project first so the newest data wins on overlap in a gdalbuildvrt mosaic. |
With return_provenance=True the call returns (tile_paths, provenance), where
each provenance record carries tile_id, file_name, file_path,
source_url, project_name, project_year, etag, last_modified,
content_length, and local_size_bytes. That is enough to record exactly which
tiles a terrain was built from without re-hashing the rasters.
HEC-RAS Terrain Raster¶
build_terrain_raster(output_raster, project_crs, geom_path=None, aoi_geometry=None, *, buffer_distance=100.0, buffer_units="US survey foot", vertical_unit=None, minimum_cell_size=5.0, target_resolution=None, backfill_resolutions=(10, 30), exclude_tile_ids=None, download_folder=None, cache_folder=None, resampling_method="bilinear", nodata=-9999.0, src_nodata=None, max_workers=3, hecras_version=None, hec_terrain_hdf=None, receipt_path=None, overwrite=False, timeout_seconds=7200, tile_plan=None, require_cached_tiles=False)- Build one gap-free GeoTIFF terrain in the project CRS
RASMapper creates result rasters that mirror the terrain VRT structure: when a
terrain references several rasters, every result output mirrors that
multi-raster structure. build_terrain_raster() therefore delivers exactly one
raster, already in the project CRS so HEC-RAS never reprojects, and can prove
the HEC-RAS terrain built from it has a single source member.
| Step | Behavior |
|---|---|
| AOI | Buffered model extent in the project CRS. From geom_path it is the model footprint (HdfProject.get_project_extent(..., geometry_type="footprint"), text-only 1D supported) unioned with the full cross-section cut lines, which can protrude past the edge-line footprint. The buffer is an absolute distance (default 100 US survey feet), not a percentage. A caller geometry (aoi_geometry, project CRS) is buffered the same way. The project CRS is always caller-supplied. |
| Priority | 3DEP 1m project-based DEMs via download_tiles(project_selection="coverage") (newest project per sub-area), then seamless 1/3 arc-second (~10m), then 1 arc-second (~30m). A lower tier is downloaded only where higher tiers leave AOI pixels uncovered. |
| Cell size | The dominant resolution is the native resolution of the tier contributing the most AOI area, converted to project units with exact fractions (1m is 3937/1200 = 3.2808333333333333 US survey feet). The cell size is k * dominant_resolution for the smallest integer k >= 1 reaching minimum_cell_size (default 5 project units): 1m in EPSG:2277 gives k=2 and 6.5616666666666667 ftUS; a 10m source (32.8 ft) already meets the minimum, so k=1. target_resolution overrides the rule; a value that is not an integer multiple of the dominant resolution is snapped to the nearest multiple (at least 1x) with a logged warning. The receipt records multiple, dominant_resolution, minimum_cell_size, requested_resolution, snapped, chosen_by, and the resulting value. |
| Composite | One HEC-RAS bundled gdalwarp.exe call, sources lowest priority first and highest last, bilinear resampling for every tier (resampling_method, default "bilinear"), -t_srs, -tr, -tap, -te snapped outward, tiled/compressed GeoTIFF with BIGTIFF=IF_SAFER. |
| Vertical units | 3DEP heights are NAVD88 metres. Reprojection changes horizontal units only, and the bundled GDAL 3.0.2 gdalwarp does not rescale Z even with compound CRSs, so valid pixels are explicitly scaled (x 3.2808333333333333 for US survey feet). |
| Gate | Nodata pixels inside the buffered AOI polygon (not its bounding rectangle; any touching pixel counts) must be zero. Otherwise TerrainBuildError is raised with reason_code="terrain_aoi_nodata_after_backfill", the count, bounds, and sample locations. Terrain is never fabricated. |
| Receipt | <output stem>.terrain_receipt.json: per-tier projects, tiles (URL, ETag, Last-Modified, size), contributed AOI pixels and area; the cell-size rule inputs and result; vertical datum, units, and factor; target CRS; grid origin and shape; nodata-inside-AOI count. |
| HEC-RAS handoff | With hec_terrain_hdf, RasTerrain.create_terrain_hdf builds the terrain from the single raster with stitching disabled, and the resulting Terrain.vrt must have exactly one source member (reason_code="hec_terrain_vrt_not_single_source" otherwise). |
from ras_commander.terrain import TerrainBuildError, Usgs3depAws
try:
receipt = Usgs3depAws.build_terrain_raster(
"Terrain/maha_creek_navd88_ftus_epsg2277.tif",
project_crs="EPSG:2277", # caller-asserted for text-only models
geom_path="MAHA CREEK.g01",
hecras_version="6.6",
hec_terrain_hdf="Terrain/hec-terrain-6.6/Terrain.hdf",
)
except TerrainBuildError as error:
print(error.reason_code, error.details)
else:
print(receipt["resolution"]["value"], receipt["hec_terrain"]["source_member_count"])
Catalog Builds: Plan, Prefetch, Build Offline¶
For many models that share one tile store (for example a catalog built in parallel in containers or on HPC nodes with no internet and a read-only store), split acquisition from building:
plan_terrain_tiles(project_crs, geom_path=None, aoi_geometry=None, *, buffer_distance=100.0, buffer_units="US survey foot", backfill_resolutions=(10, 30), min_coverage_fraction=0.999, min_project_area_fraction=0.0, cache_folder=None, exclude_tile_ids=None)- Network. Computes the same buffered AOIbuild_terrain_raster()uses (one shared routine) and every tile each tier needs, and returns a JSON-serializable plan.prefetch_terrain_tiles(plans, download_folder, *, max_workers=4, overwrite=False)- Network, single writer. Deduplicates tiles by URL across any number of plans, downloads each once intodownload_folder/<product>/<filename>, keeps size-matched existing files, and returns a manifest.build_terrain_raster(..., tile_plan=plan, require_cached_tiles=True)- No network. Uses the plan's AOI and tile lists and reads the store without writing to it.
| Plan field | Content |
|---|---|
schema, version, created_at, project_crs |
Identity (ras-commander/usgs-3dep-terrain-tile-plan, 1.0.0) |
buffer |
Distance, units, and distance in project units |
aoi |
wkt (full precision, project CRS), wkt_sha256, bounds, bounds_wgs84, and the AOI report (cross-section counts) |
selection |
Coverage fractions, backfill resolutions, excluded tile ids |
tiers |
Highest priority first. Each tier has tier, product, resolution, and tiles; each tile has tile_id, url, filename, relative_path, product, tier_resolution, project, project_folder, year, etag, last_modified, and content_length (from a HEAD request). Tier 1 lists coverage-selected 1m tiles in composite order and adds coverage (covered and uncovered fraction, uncovered area, and uncovered geometry WKT). Backfill tiers list EVERY seamless 1-degree tile intersecting the AOI, unconditionally, because interior 1m voids cannot be predicted from the index; tiles missing on S3 are listed under unavailable_tiles. |
The prefetch manifest lists one entry per unique URL with filename,
relative_path, local_path, url, tier_resolutions, products,
project, project_folder, year, etag, last_modified,
content_length, local_size_bytes, status (downloaded, cached, or
failed), error, and referenced_by_plans (plan SHA-256 digests), plus
counts. Failures are reported per tile rather than raised; a partial or
size-mismatched download is removed so it can never pass as cached.
With tile_plan, build_terrain_raster() does not recompute the AOI and does
not query the tile index or S3 listings. geom_path and aoi_geometry must be
omitted, project_crs must match the plan, and backfill_resolutions must be
a subset of the planned tiers. With require_cached_tiles=True it never
downloads, never writes into download_folder, and makes no HEAD or other
network request. Every tile of every planned tier must already be in the
store, otherwise TerrainBuildError is raised with
reason_code="terrain_tile_not_cached" and the missing relative paths.
require_cached_tiles=True without tile_plan is rejected. The receipt
build_mode block records offline, network_access, the store folder, and
the plan's SHA-256. Per-tile provenance comes from the plan, plus the local
size and a size_matches_plan flag computed without network access. The
cell-size rule, bilinear composite, single raster, zero-nodata gate, and
single-member Terrain.vrt check are unchanged.
import json
from concurrent.futures import ProcessPoolExecutor
from ras_commander.terrain import Usgs3depAws
# 1. Plan (network), one plan per model
plans = {name: Usgs3depAws.plan_terrain_tiles("EPSG:2277", geom_path=geom) for name, geom in models.items()}
# 2. Prefetch once, single writer
manifest = Usgs3depAws.prefetch_terrain_tiles(plans.values(), "tile-store", max_workers=8)
assert manifest["counts"]["failed"] == 0
# 3. Build offline in parallel against the read-only store
def build(name):
return Usgs3depAws.build_terrain_raster(
f"terrain/{name}.tif", "EPSG:2277",
download_folder="tile-store", tile_plan=plans[name], require_cached_tiles=True,
hec_terrain_hdf=f"terrain/{name}/Terrain.hdf", hecras_version="6.6",
)
with ProcessPoolExecutor() as pool:
receipts = list(pool.map(build, plans))
Mosaic Methods¶
create_vrt(tile_files, output_vrt, hecras_version=None)- Build a VRT mosaic of downloaded tiles with HEC-RAS bundledgdalbuildvrt.exe
create_vrt() inherits the source SRS and native cell size. Do not use a
multi-raster VRT as a HEC-RAS terrain source; use build_terrain_raster().
RasTauDem¶
D8 stream links and catchments from a DEM, using the TauDEM 5 command-line
tools (PitRemove, D8FlowDir, AreaD8, Threshold, StreamNet). TauDEM is GPL-3
software that RAS Commander runs only as separate processes; install it from
hydrology.usu.edu/taudem. MPI (MS-MPI on
Windows, MPICH or Open MPI on Linux) is optional: without mpiexec each tool
runs as one process.
get_taudem_info(taudem_dir=None, mpiexec_path=None)- Locate the tools: argument, thenRAS_COMMANDER_TAUDEM_DIR, thenPATH, then the default Windows folder. The launcher: argument, thenRAS_COMMANDER_MPIEXEC, thenPATH, then the default MS-MPI folder. RaisesTauDemNotFoundErrordelineate(dem_path, dest_folder, *, stream_area_sqmi=0.1, cell_size=None, num_processes=4, edge_contamination_check=False, taudem_dir=None, mpiexec_path=None, overwrite=False, timeout=None)- ReturnsTauDemDelineation
TauDemDelineation.streams holds one row per link (schema taudem_streams):
LINKNO, DSLINKNO (-1 at an outlet), USLINKNO1, USLINKNO2, strmOrder,
Length, Slope, DSContArea (DEM units squared) and contributing_area_sqmi.
Each LineString starts at the link outlet. catchments (schema
taudem_catchments) is the polygonized StreamNet watershed grid. The DEM must
be in a projected CRS with square, north-up cells; geographic DEMs are refused.
cell_size resamples the DEM (average) before delineation, which keeps
HUC-scale runs tractable: the Salt Draw (HUC-8 13070004) 10 ft terrain at
cell_size=100 delineated 3,204 links in 18 s on a workstation.
The AreaD8 edge-contamination check is off by default (TauDEM -nc). A terrain
clipped at its drainage divide touches the DEM edge everywhere, and the check
would remove every stream. Turn it on only for a DEM buffered well past the
divide.
from ras_commander.terrain import RasTauDem
result = RasTauDem.delineate("Terrain/dem.tif", "work/taudem",
stream_area_sqmi=0.5, cell_size=100.0)
outlets = result.streams[result.streams["DSLINKNO"] < 0]
Related Examples¶
| Notebook | Description |
|---|---|
316_terrain_modifications.ipynb |
Terrain modification writer: high ground, channel, polygon |
321_terrain_modification_layer_writers.ipynb |
Every writer layer kind, read_layers / add_modification_layer round trip, pixel checks against RAS Mapper exports (6.6, 7.0.1) |
920_terrain_creation.ipynb |
Terrain HDF creation from rasters |
930_terrain_modification_analysis.ipynb |
Cut/fill analysis with RasTerrainMod |
931_native_rasmapper_terrain_export.ipynb |
Bounded native export, typed result, receipt, and visual grid evidence |
Notebooks 316, 920, 930, and 931 include freshly executed review outputs and figures for their bounded terrain workflows. Notebook 612 retains its coherent previously computed hydraulic outputs and four final maps; its four hydraulic simulations were deliberately not rerun for this terrain-export change.
Complete source reference¶
The sections above explain common operations. The source-derived reference below includes the remaining public methods and their full signatures. Method-specific prerequisites and return contracts take precedence over abbreviated summaries.
RasTerrain source reference¶
Static class for HEC-RAS terrain creation and manipulation.
All methods are static and designed to be called directly without instantiation, following the ras-commander coding pattern.
Primary Methods
compute_bank_lines(): Generate bank lines from XS bank stations compute_xs_interpolation_surface(): Build Delaunay TIN from XS data create_terrain_hdf(): Create HEC-RAS terrain HDF from input rasters vrt_to_tiff(): Convert VRT mosaic to single optimized TIFF
Helper Methods
_get_hecras_path(): Find HEC-RAS installation directory _get_hecras_gdal_path(): Find GDAL tools in HEC-RAS installation _generate_prj_from_raster(): Create ESRI PRJ file from raster CRS
Usage
from ras_commander.terrain import RasTerrain from pathlib import Path
Create terrain from TIFF¶
RasTerrain.create_terrain_hdf( input_rasters=[Path("dem.tif")], output_hdf=Path("Terrain/Terrain.hdf"), projection_prj=Path("Terrain/Projection.prj") )
compute_bank_lines
staticmethod
¶
Generate bank-line geometry from cross-section bank stations.
This is a non-mutating API equivalent to RASMapper's
Bank Lines layer -> Compute Bank Lines from XS Bank Stations workflow.
It reads existing cross-section bank station metadata and returns
reviewable line geometry without modifying .rasmap, text geometry,
or compiled geometry HDF bank-line layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geom_path
|
Union[str, Path]
|
Path to a plain-text |
required |
crs
|
CRS or str
|
Optional CRS to assign to the returned GeoDataFrame. If omitted and an HDF input exposes a CRS, that CRS is preserved. |
None
|
ras_object
|
RasPrj
|
Optional RasPrj instance for multi-project workflows. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Bank lines with columns: - river (str): River name - reach (str): Reach name - bank_side (str): "Left" or "Right" - xs_count (int): Number of cross sections used - rs_values (list[str]): River stations used in line order - geometry (LineString): Generated bank line - length (float): Line length in project coordinate units |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If geom_path does not exist. |
ImportError
|
If geopandas, shapely, pandas, or numpy are unavailable. |
compute_xs_interpolation_surface
staticmethod
¶
compute_xs_interpolation_surface(geom_path: Union[str, Path], output_gpkg: Optional[Union[str, Path]] = None, output_raster: Optional[Union[str, Path]] = None, raster_cell_size: Optional[float] = None, crs: Optional[Union[str, int]] = None, channel_only: bool = True, nodata: float = -9999.0, ras_object=None) -> Dict[str, Any]
Compute a cross-section interpolation surface for channel bathymetry.
This is the ras-commander API equivalent of the RASMapper workflow: Cross Sections -> Interpolation Surface -> Compute XS Interpolation Surface. It reads cross-section cut lines, station/elevation points, bank stations, river centerlines, and bank lines through existing HDF or plain-text geometry APIs, then returns reviewable GeoDataFrames and optionally persists review layers and a GeoTIFF raster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geom_path
|
Union[str, Path]
|
Geometry HDF path ( |
required |
output_gpkg
|
Optional[Union[str, Path]]
|
Optional GeoPackage path for review layers. |
None
|
output_raster
|
Optional[Union[str, Path]]
|
Optional GeoTIFF path for rasterized interpolation. |
None
|
raster_cell_size
|
Optional[float]
|
Cell size in project units. Required when
|
None
|
crs
|
CRS or str
|
Optional CRS override. Plain geometry files otherwise try to resolve CRS from the sibling geometry HDF/RASMapper projection. |
None
|
channel_only
|
bool
|
If True, clip/interpolate between left and right bank stations or RAS bank lines. If False, use full XS extents. |
True
|
nodata
|
float
|
NoData value for raster output. |
-9999.0
|
ras_object
|
RasPrj
|
Optional RasPrj instance for project context. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Contains |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
create_terrain_from_rasters
staticmethod
¶
create_terrain_from_rasters(input_rasters: List[Union[str, Path]], output_folder: Union[str, Path], terrain_name: str = 'Terrain', units: str = 'Feet', stitch: bool = True, hecras_version: str = '7.0', generate_prj: bool = True, gdal_num_threads: Optional[Union[int, str]] = None) -> Path
Create HEC-RAS terrain from input rasters with automatic PRJ generation.
This is a convenience method that combines PRJ generation and terrain creation. It automatically generates the projection file from the first input raster's CRS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_rasters
|
List[Union[str, Path]]
|
List of input raster file paths. |
required |
output_folder
|
Union[str, Path]
|
Folder for terrain output (HDF + PRJ files). |
required |
terrain_name
|
str
|
Base name for terrain files (e.g., "Terrain" creates Terrain.hdf). Defaults to "Terrain". |
'Terrain'
|
units
|
str
|
Vertical data units ("Feet" or "Meters"). |
'Feet'
|
stitch
|
bool
|
Enable terrain stitching. Defaults to True. |
True
|
hecras_version
|
str
|
HEC-RAS version. Defaults to "7.0". |
'7.0'
|
generate_prj
|
bool
|
Auto-generate PRJ from first raster. If False, expects Projection.prj to exist in output_folder. |
True
|
gdal_num_threads
|
Optional[Union[int, str]]
|
Threads made available to supported GDAL terrain preprocessing. Defaults to the HEC-RAS runtime setting. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created terrain HDF file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If input rasters not found. |
ImportError
|
If rasterio not available for PRJ generation. |
RuntimeError
|
If terrain creation fails. |
Example
terrain = RasTerrain.create_terrain_from_rasters( ... input_rasters=["lidar_dem.tif", "bathymetry.tif"], ... output_folder="Terrain", ... terrain_name="Terrain50", ... units="Feet" ... )
create_terrain_hdf
staticmethod
¶
create_terrain_hdf(input_rasters: List[Union[str, Path]], output_hdf: Union[str, Path], projection_prj: Union[str, Path], units: str = 'Feet', stitch: bool = True, hecras_version: str = '7.0', timeout_seconds: int = 600, gdal_num_threads: Optional[Union[int, str]] = None) -> Path
Create HEC-RAS terrain HDF from input rasters using RasProcess.exe.
This method uses the verified RasProcess.exe CreateTerrain command to create a terrain HDF file compatible with HEC-RAS. The created terrain includes: - Multi-resolution pyramid levels (7 levels, 0-6) - TIN stitching for seamless multi-source terrain - Tile-based storage optimized for HEC-RAS rendering
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_rasters
|
List[Union[str, Path]]
|
List of input raster file paths (GeoTIFF, FLT, etc.). Files are processed in priority order - first file has highest priority in overlapping areas. |
required |
output_hdf
|
Union[str, Path]
|
Path for output terrain HDF file. Parent directory will be created if it doesn't exist. |
required |
projection_prj
|
Union[str, Path]
|
Path to ESRI PRJ file defining the coordinate reference system. Must be an existing file. |
required |
units
|
str
|
Vertical data units. Options: "Feet" or "Meters". Defaults to "Feet". |
'Feet'
|
stitch
|
bool
|
Enable terrain stitching for multi-source terrains. Defaults to True. |
True
|
hecras_version
|
str
|
HEC-RAS version to use for RasProcess.exe. Defaults to "7.0". |
'7.0'
|
timeout_seconds
|
int
|
Maximum time to wait for RasProcess.exe to finish terrain creation. Defaults to 600 seconds (10 minutes). |
600
|
gdal_num_threads
|
Optional[Union[int, str]]
|
Threads made available to GDAL operations inside
CreateTerrain. Defaults to the HEC-RAS runtime setting. Set a positive
integer to cap threaded compression/warping, or |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created terrain HDF file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If HEC-RAS installation, input rasters, or PRJ file not found. |
ValueError
|
If units is not "Feet" or "Meters". |
RuntimeError
|
If terrain creation fails. |
Example
from pathlib import Path terrain = RasTerrain.create_terrain_hdf( ... input_rasters=[Path("Terrain/dem.tif")], ... output_hdf=Path("Terrain/Terrain.hdf"), ... projection_prj=Path("Terrain/Projection.prj"), ... units="Feet", ... stitch=True, ... hecras_version="7.0", ... timeout_seconds=1800, ... ) print(f"Terrain created: {terrain}")
Notes
- The RasProcess.exe command requires all paths to be quoted due to spaces in "Program Files".
- Input rasters are processed in order - first raster has priority in overlapping areas.
- The output folder will be created automatically if it doesn't exist.
- Verified working with HEC-RAS 6.6 (tested 2025-12-25).
- Threading applies only to GDAL operations that support
GDAL_NUM_THREADS; serial HEC-RAS terrain-HDF stages remain serial.
export_rasmapper_terrain
staticmethod
¶
export_rasmapper_terrain(ras_project_path: Union[str, Path], output_tif: Union[str, Path], terrain_name: Optional[str] = None, extent: Optional[Sequence[float]] = None, downsample_factor: int = 1, rasterize_modifications: bool = True, overwrite: bool = False, timeout_seconds: float = 1800.0, hecras_version: Optional[str] = None, ras_object=None, receipt_path: Optional[Union[str, Path]] = None, empty_extent: str = 'fail') -> TerrainExportResult
Export one registered RAS Mapper terrain to a validated GeoTIFF.
This is a supervised wrapper around HEC-RAS's own terrain
consolidation operation. It loads the selected terrain from the
project's .rasmap so registered source order, stitches, masks, and
vector modifications remain native RAS Mapper behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ras_project_path
|
Union[str, Path]
|
Project folder, |
required |
output_tif
|
Union[str, Path]
|
Destination single-band Float32 GeoTIFF. |
required |
terrain_name
|
Optional[str]
|
Exact registered terrain name. May be omitted only when the project registers exactly one terrain. |
None
|
extent
|
Optional[Sequence[float]]
|
Optional |
None
|
downsample_factor
|
int
|
Exact source-derived factor: 1, 2, 4, or 8. |
1
|
rasterize_modifications
|
bool
|
Apply native RAS Mapper vector terrain
modifications through |
True
|
overwrite
|
bool
|
Replace existing output and receipt when true. |
False
|
timeout_seconds
|
float
|
Total bounded runtime, including validation. |
1800.0
|
hecras_version
|
Optional[str]
|
Accepted HEC-RAS runtime: 6.4.1, 6.5, 6.6, 7.0.1, 7.0.2,
or forward-open 7.1. The existing |
None
|
ras_object
|
RasPrj
|
Optional initialized project object for multi-project
and runtime-version context. Its |
None
|
receipt_path
|
Optional[Union[str, Path]]
|
Machine-readable JSON receipt path. Defaults to
|
None
|
empty_extent
|
str
|
Behavior when RAS Mapper fails because the export
window holds no terrain data and a full-resolution scan of the
registered sources confirms it. |
'fail'
|
Returns:
| Type | Description |
|---|---|
TerrainExportResult
|
Bool-compatible typed result. Operational |
TerrainExportResult
|
failures and timeouts return a failed result and failure receipt; |
TerrainExportResult
|
invalid inputs raise before native execution. |
TerrainExportResult
|
classifies a failure (for example |
TerrainExportResult
|
|
TerrainExportResult
|
native helper request, exit code, response, and retained stderr. |
TerrainExportResult
|
The receipt holds the same records. A helper that reports success |
but exits non-zero is not treated as a failure
|
its output is |
TerrainExportResult
|
validated like any other, and |
Notes
Qualified releases are HEC-RAS 6.4.1, 6.5, 6.6, and 7.0.1.
HEC-RAS 6.3 lacks the required bounded contract, 6.4 has an
official terrain-elevation defect, 6.7 is beta-only, and 7.0.0
has an official terrain-modification export defect. HEC-RAS 7.0.1
fixes that defect. HEC-RAS 6.4.1, 6.5, 6.6, and 7.0.1 are qualified
on native Windows and under Wine. HEC-RAS 7.1
is forward-open for its future official binary, with the helper's
exact managed-contract check retained as the runtime safety gate.
HEC-RAS 7.0.2 is qualified on Windows for bounded two-source export;
its changed spatial-index overload is selected at runtime. Its
vector-modification exports were pixel-identical to 7.0.1's for
every form in the 2026-11-12 per-release qualification (bounded
and whole-terrain); Wine has not been qualified on 7.0.2.
The 6.7 betas and 7.0.0 stay refused by this export even though
that qualification found their modification rendering identical
to 6.6 (betas, on every form 6.6 renders) and 7.0.1 (7.0.0, which
did not show its documented defect on the one minimum-Y window
tried): prerelease builds are not production runtimes, and one
negative probe does not clear an official HEC known defect.
Projects on those releases can still take the native effective
terrain (RasFim.build_effective_terrain), whose rules were
qualified against their exports.
Windows-drive and UNC project/input paths are supported, but direct
output to a UNC share is not qualified because the task-local GDAL
junction may not be staged on a remote volume; use a local output
and copy the committed TIFF and receipt afterward. Fully qualified
helper response paths beyond the legacy .NET 260-character limit
are also unqualified; select a shorter local output path.
The base export is always nearest-neighbor. The derivative is not
registered in or otherwise written back to the source project.
RasTerrainMod.compute_modified_terrain_raster() is a deprecated
row-sampled compatibility method scheduled for removal in 1.1; it
is not used as a production fallback.
get_available_versions
staticmethod
¶
Get list of installed HEC-RAS versions with terrain creation support.
Scans standard HEC-RAS installation directories for versions that have RasProcess.exe available.
Returns:
| Type | Description |
|---|---|
List[str]
|
List of version strings (e.g., ["7.0", "6.5"]). Empty list if no compatible versions found. |
Example
versions = RasTerrain.get_available_versions() print(versions) ['6.6', '6.5', '6.4', '6.3']
profile_vrt_to_tiff
staticmethod
¶
profile_vrt_to_tiff(vrt_path: Union[str, Path], output_path: Union[str, Path], report_path: Optional[Union[str, Path]] = None, *, write_options: Optional[GeoTiffWriteOptions] = None, nodata_value: Optional[float] = None, hecras_version: str = '7.0', sample_interval_seconds: float = 0.2) -> RasterOperationProfileResult
Profile one VRT consolidation setting and persist its metrics.
vrt_to_tiff
staticmethod
¶
vrt_to_tiff(vrt_path: Union[str, Path], output_path: Union[str, Path], compression: str = 'LZW', create_overviews: bool = True, overview_levels: Optional[List[int]] = None, nodata_value: Optional[float] = None, hecras_version: str = '7.0', gdal_num_threads: Optional[Union[int, str]] = None, *, write_options: Optional[GeoTiffWriteOptions] = None) -> Path
Convert VRT (Virtual Raster) to single optimized TIFF.
Uses GDAL tools bundled with HEC-RAS installation to convert a VRT mosaic to a single GeoTIFF file. Optionally adds pyramid overviews for faster rendering in HEC-RAS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vrt_path
|
Union[str, Path]
|
Path to input VRT file. |
required |
output_path
|
Union[str, Path]
|
Path for output TIFF file. |
required |
compression
|
str
|
Compression algorithm for output TIFF. Options: "LZW", "DEFLATE", "ZSTD", "NONE". Defaults to "LZW". |
'LZW'
|
create_overviews
|
bool
|
Add pyramid overviews for faster rendering. Defaults to True. |
True
|
overview_levels
|
Optional[List[int]]
|
Custom overview levels (e.g., [2, 4, 8, 16, 32]). Defaults to [2, 4, 8, 16, 32] if None. |
None
|
nodata_value
|
Optional[float]
|
NoData value for output raster. If None, uses source NoData value. |
None
|
hecras_version
|
str
|
HEC-RAS version for GDAL tools path. Defaults to "7.0". |
'7.0'
|
gdal_num_threads
|
Optional[Union[int, str]]
|
Threads used for supported GeoTIFF compression
operations. Defaults to the GDAL runtime setting; use a positive integer
to cap usage or |
None
|
write_options
|
Optional[GeoTiffWriteOptions]
|
Typed creation, tiling, cache, compression, and overview settings. Do not combine with non-default legacy compression/overview/thread arguments. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created TIFF file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If VRT file or HEC-RAS GDAL tools not found. |
RuntimeError
|
If conversion fails. |
Example
output = RasTerrain.vrt_to_tiff( ... vrt_path="terrain/combined.vrt", ... output_path="terrain/combined.tif", ... compression="LZW", ... create_overviews=True ... )
Usgs3depAws source reference¶
Direct access to USGS 3DEP elevation data on AWS S3.
build_terrain_raster
staticmethod
¶
build_terrain_raster(output_raster: Union[str, Path], project_crs: str, geom_path: Optional[Union[str, Path]] = None, aoi_geometry: Optional[Any] = None, *, buffer_distance: float = 100.0, buffer_units: str = 'US survey foot', vertical_unit: Optional[str] = None, minimum_cell_size: float = 5.0, target_resolution: Optional[float] = None, backfill_resolutions: Sequence[int] = (10, 30), exclude_tile_ids: Optional[Sequence[str]] = None, download_folder: Optional[Union[str, Path]] = None, cache_folder: Optional[Union[str, Path]] = None, resampling_method: str = 'bilinear', nodata: float = -9999.0, src_nodata: Optional[float] = None, max_workers: int = 3, hecras_version: Optional[str] = None, hec_terrain_hdf: Optional[Union[str, Path]] = None, receipt_path: Optional[Union[str, Path]] = None, overwrite: bool = False, timeout_seconds: int = 7200, tile_plan: Optional[Union[Mapping[str, Any], str, Path]] = None, require_cached_tiles: bool = False) -> Dict[str, Any]
Build one gap-free GeoTIFF terrain in the project CRS for HEC-RAS.
RASMapper creates result rasters that mirror the structure of the terrain VRT: when the terrain references several rasters, every result output mirrors that multi-raster structure. This method therefore delivers exactly ONE raster, already in the project CRS (so HEC-RAS never reprojects), on one common grid, and verifies that the HEC-RAS terrain built from it has a single source member.
Pipeline:
- AOI. The buffered model extent in project CRS. From
geom_pathit is the union of the model footprint (HdfProject.get_project_extent(..., geometry_type="footprint"), which supports text-only 1D geometry) and the FULL cross-section cut lines, which can protrude beyond the edge-line footprint, then buffered by an ABSOLUTE distance. Alternatively passaoi_geometry(project CRS), which is buffered the same way. - Priority chain. 3DEP 1m project-based DEMs selected with
download_tiles(project_selection="coverage")(newest project per sub-area), then the seamless 1/3 arc-second (~10m) and 1 arc-second (~30m) products. A lower tier is downloaded only when the higher tiers leave AOI pixels uncovered, and only for the bounds of those pixels. - Cell size. The dominant resolution is the native resolution of
the tier contributing the most AOI area, converted to project CRS
linear units with exact fractions (1m in EPSG:2277 is 3937/1200 =
3.2808333333333333 US survey feet). The cell size is
k * dominant_resolutionfor the smallest integerk >= 1withk * dominant_resolution >= minimum_cell_size(default 5 project units): 1m in EPSG:2277 gives k=2 and 6.5616666666666667 ftUS, while a 10m source already exceeds 5 ft, so k=1.target_resolutionoverrides the rule; a value that is not an integer multiple of the dominant resolution is snapped to the nearest multiple (at least 1x) with a logged warning. - One composite. A single HEC-RAS bundled
gdalwarp.execall with every source ordered lowest priority first and highest last (later valid pixels overwrite earlier ones),-t_srs,-tr,-tap,-tesnapped outward, bilinear resampling for every tier, and a tiled, compressed GeoTIFF. - Vertical units. 3DEP heights are NAVD88 metres and reprojection
changes horizontal units only; the bundled GDAL 3.0.2
gdalwarpdoes not rescale Z even when given compound CRSs. Valid pixels are therefore explicitly scaled into the project vertical unit (x 3.2808333333333333 for US survey feet). - Hard gate. Nodata pixels inside the buffered AOI polygon (not
its bounding rectangle; any pixel touching the polygon counts) must
be zero. If backfill is exhausted,
TerrainBuildErroris raised withTERRAIN_REASON_AOI_NODATA, the count, and the locations. Terrain is never fabricated. - Receipt. Per tier: projects, tiles with provenance, contributed AOI pixels and area; plus the chosen resolution and why, vertical conversion, target CRS, grid origin, and the nodata-inside-AOI count.
- HEC-RAS handoff (optional). With
hec_terrain_hdf, the terrain is built byRasTerrain.create_terrain_hdffrom the single raster with stitching disabled, and the resulting Terrain.vrt must contain exactly one source member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_raster
|
Union[str, Path]
|
Output GeoTIFF path. |
required |
project_crs
|
str
|
Projected CRS of the HEC-RAS project, for example
|
required |
geom_path
|
Optional[Union[str, Path]]
|
Plain-text ( |
None
|
aoi_geometry
|
Optional[Any]
|
Shapely geometry of the model extent in project CRS. |
None
|
buffer_distance
|
float
|
Absolute AOI buffer. Default 100. Keyword-only. |
100.0
|
buffer_units
|
str
|
Units of |
'US survey foot'
|
vertical_unit
|
Optional[str]
|
Output elevation unit: |
None
|
minimum_cell_size
|
float
|
Minimum output cell size in project CRS linear units. Default 5.0. The cell size is the smallest integer multiple of the dominant resolution that reaches it. Keyword-only. |
5.0
|
target_resolution
|
Optional[float]
|
Cell size in project CRS units overriding the minimum-cell-size rule. Snapped, with a warning, to the nearest integer multiple (at least 1) of the dominant resolution. Keyword-only. |
None
|
backfill_resolutions
|
Sequence[int]
|
Lower-priority tiers, in priority order,
from |
(10, 30)
|
exclude_tile_ids
|
Optional[Sequence[str]]
|
Tile identifiers (filename stems) to withhold in every tier. Keyword-only. |
None
|
download_folder
|
Optional[Union[str, Path]]
|
Where source tiles are cached. Default is a
|
None
|
cache_folder
|
Optional[Union[str, Path]]
|
Tile index cache folder. Keyword-only. |
None
|
resampling_method
|
str
|
gdalwarp resampling applied to every tier.
Default |
'bilinear'
|
nodata
|
float
|
Output nodata value. Default -9999. Keyword-only. |
-9999.0
|
src_nodata
|
Optional[float]
|
Source nodata override. Default None uses each source's own nodata metadata, which differs between 3DEP products. Keyword-only. |
None
|
max_workers
|
int
|
Concurrent tile downloads. Default 3. Keyword-only. |
3
|
hecras_version
|
Optional[str]
|
HEC-RAS version whose bundled GDAL and RasProcess
are used. Default None picks the newest install with gdalwarp
(and |
None
|
hec_terrain_hdf
|
Optional[Union[str, Path]]
|
If given, build the HEC-RAS terrain HDF here and assert its Terrain.vrt has exactly one source. Keyword-only. |
None
|
receipt_path
|
Optional[Union[str, Path]]
|
Receipt JSON path. Default
|
None
|
overwrite
|
bool
|
Replace an existing output. Default False. Keyword-only. |
False
|
timeout_seconds
|
int
|
Timeout for each gdalwarp call and for HEC-RAS terrain creation. Default 7200. Keyword-only. |
7200
|
tile_plan
|
Optional[Union[Mapping[str, Any], str, Path]]
|
Plan dict (or JSON path) from |
None
|
require_cached_tiles
|
bool
|
Offline build. Requires |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
The receipt dict, also written to |
Raises:
| Type | Description |
|---|---|
ValueError
|
For invalid arguments, a non-projected project CRS, or an empty AOI. |
FileExistsError
|
If the output exists and |
FileNotFoundError
|
If the HEC-RAS bundled gdalwarp.exe is missing. |
RuntimeError
|
If gdalwarp fails. |
TerrainBuildError
|
With |
Example
>>> receipt = Usgs3depAws.build_terrain_raster(
... "Terrain/maha_creek_epsg2277.tif",
... project_crs="EPSG:2277",
... geom_path="MAHA CREEK.g01",
... hec_terrain_hdf="Terrain/hec-6.6/Terrain.hdf",
... hecras_version="6.6",
... )
>>> receipt["resolution"]["value"], receipt["resolution"]["multiple"]
(6.5616666666666665, 2)
>>> receipt["nodata"]["inside_aoi_count"]
0
>>> receipt["hec_terrain"]["source_member_count"]
1
create_vrt
staticmethod
¶
create_vrt(tile_files: Sequence[Union[str, Path]], output_vrt: Union[str, Path], hecras_version: Optional[str] = None) -> Path
Create a Virtual Raster (VRT) mosaic from multiple tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile_files
|
Sequence[Union[str, Path]]
|
List of TIFF files to mosaic |
required |
output_vrt
|
Union[str, Path]
|
Output VRT file path |
required |
hecras_version
|
Optional[str]
|
Optional HEC-RAS version to use for bundled GDAL discovery. If None, auto-detects the newest available install. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created VRT file |
download_tile_index
staticmethod
¶
download_tile_index(resolution: int, cache_folder: Optional[Union[str, Path]] = None) -> gpd.GeoDataFrame
Download tile index (spatial metadata) for a given resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resolution
|
int
|
DEM resolution in meters. Direct downloads currently
support only |
required |
cache_folder
|
Optional[Union[str, Path]]
|
Optional folder to cache the index. If None, downloads to temp. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with tile locations and metadata |
Raises:
| Type | Description |
|---|---|
ValueError
|
If resolution not supported |
HTTPError
|
If download fails |
download_tiles
staticmethod
¶
download_tiles(bbox: Any, resolution: int, output_folder: Union[str, Path], cache_folder: Optional[Union[str, Path]] = None, overwrite_dest: bool = False, max_workers: int = 3, project_name: Optional[str] = None, min_year: Optional[int] = None, buffer_distance: float = 0.0, *, project_selection: str = 'newest', min_coverage_fraction: float = 0.999, min_project_area_fraction: float = 0.0, return_provenance: bool = False, exclude_tile_ids: Optional[Sequence[str]] = None) -> Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
Download all DEM tiles for a bounding box with concurrent downloads.
Implements passive file caching: if a tile already exists with the correct file size, it will be reused instead of re-downloaded. This allows interrupted downloads to resume and repeated runs to use cached files.
Downloads are performed concurrently using multiple threads for improved performance (default 3 concurrent downloads).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Any
|
One valid Polygon or a legacy bounds-shaped input in WGS84. |
required |
resolution
|
int
|
DEM resolution in meters (1, 10, or 30) |
required |
output_folder
|
Union[str, Path]
|
Folder to save downloaded tiles |
required |
cache_folder
|
Optional[Union[str, Path]]
|
Optional folder to cache tile index |
None
|
overwrite_dest
|
bool
|
If True, re-download even if file exists with correct size. Default False (passive caching enabled). |
False
|
max_workers
|
int
|
Maximum number of concurrent downloads. Default 3. Set to 1 for sequential downloads. |
3
|
project_name
|
Optional[str]
|
Optional specific project name to download (e.g., 'PA_Northcentral_2019_B19'). If specified, downloads only from this project. Use list_projects_for_bbox() to see available projects. |
None
|
min_year
|
Optional[int]
|
Optional minimum year filter (e.g., 2019). Only considers projects from this year or newer. Ignored if project_name is specified. |
None
|
buffer_distance
|
float
|
Optional buffer in WGS84 degrees, applied before tile discovery and intersection. Default is 0.0. |
0.0
|
project_selection
|
str
|
How to choose among the projects that intersect
the bbox. |
'newest'
|
min_coverage_fraction
|
float
|
Coverage-mode stop condition; selection ends
once this fraction of the bbox is covered. Default 0.999.
Ignored when |
0.999
|
min_project_area_fraction
|
float
|
Coverage-mode minimum new contribution
required to pull in another project, as a fraction of bbox
area. Default 0.0 (accept any positive contribution). Ignored
when |
0.0
|
return_provenance
|
bool
|
If True, also return one provenance record per downloaded tile. Default False. Keyword-only. |
False
|
exclude_tile_ids
|
Optional[Sequence[str]]
|
Tile identifiers (filename stems, for example
|
None
|
Returns:
| Type | Description |
|---|---|
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
List of paths to downloaded TIFF files, or, when |
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
|
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
Each provenance record is a dict with |
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
|
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
|
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
|
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
folder, which can differ from the index collection name). |
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
In coverage mode the returned tiles are ordered oldest project |
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
first, so the newest tiles come last and win where projects |
Union[List[Path], Tuple[List[Path], List[Dict[str, Any]]]]
|
overlap in a |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If |
Example
# Default: Downloads tiles from most recent project (3 concurrent)
tiles = Usgs3depAws.download_tiles(bbox, 1, "Terrain")
# List available projects first
projects = Usgs3depAws.list_projects_for_bbox(bbox, 1)
print(projects[['proj_name', '_year']])
# Download from specific project by name
tiles = Usgs3depAws.download_tiles(bbox, 1, "Terrain",
project_name="PA_Northcentral_2019_B19")
# Download only from projects 2018 or newer
tiles = Usgs3depAws.download_tiles(bbox, 1, "Terrain", min_year=2018)
# Force re-download with 5 concurrent workers
tiles = Usgs3depAws.download_tiles(bbox, 1, "Terrain",
overwrite_dest=True, max_workers=5)
# Sequential downloads (no concurrency)
tiles = Usgs3depAws.download_tiles(bbox, 1, "Terrain", max_workers=1)
# Cover the whole bbox using the newest project per sub-area
tiles = Usgs3depAws.download_tiles(bbox, 1, "Terrain",
project_selection="coverage")
# Capture per-tile provenance for a terrain build record
tiles, provenance = Usgs3depAws.download_tiles(
bbox, 1, "Terrain",
project_selection="coverage",
return_provenance=True,
)
print(provenance[0]['source_url'], provenance[0]['etag'])
find_tiles_for_bbox
staticmethod
¶
find_tiles_for_bbox(bbox: Any, resolution: int, cache_folder: Optional[Union[str, Path]] = None, buffer_distance: float = 0.0) -> gpd.GeoDataFrame
Find all tiles that intersect with a bounding box.
Uses GeoPackage tile index (more reliable than API).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Any
|
One valid Polygon or a legacy bounds-shaped input in WGS84. |
required |
resolution
|
int
|
DEM resolution in meters (1, 10, or 30) |
required |
cache_folder
|
Optional[Union[str, Path]]
|
Optional folder to cache tile index |
None
|
buffer_distance
|
float
|
Optional buffer in WGS84 degrees. Default is 0.0. |
0.0
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with intersecting projects |
list_projects_for_bbox
staticmethod
¶
list_projects_for_bbox(bbox: Any, resolution: int, cache_folder: Optional[Union[str, Path]] = None, buffer_distance: float = 0.0) -> gpd.GeoDataFrame
List all USGS 3DEP projects that intersect with a bounding box.
Useful for exploring available data before downloading, or selecting specific projects by name or year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Any
|
One valid Polygon or a legacy bounds-shaped input in WGS84. |
required |
resolution
|
int
|
DEM resolution in meters (1, 10, or 30) |
required |
cache_folder
|
Optional[Union[str, Path]]
|
Optional folder to cache tile index |
None
|
buffer_distance
|
float
|
Optional buffer in WGS84 degrees. Default is 0.0. |
0.0
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame with project information including
|
|
GeoDataFrame
|
|
GeoDataFrame
|
|
GeoDataFrame
|
|
GeoDataFrame
|
|
Example
from shapely.geometry import box bbox = box(-77.5, 40.0, -76.5, 41.0) projects = Usgs3depAws.list_projects_for_bbox(bbox, resolution=1) print(projects[['proj_name', '_year', 'geometry']]) proj_name _year geometry 0 PA_Northcentral_2019_B19 2019 POLYGON(...) 1 PA_South_Central_2017_D17 2017 POLYGON(...)
plan_terrain_tiles
staticmethod
¶
plan_terrain_tiles(project_crs: str, geom_path: Optional[Union[str, Path]] = None, aoi_geometry: Optional[Any] = None, *, buffer_distance: float = 100.0, buffer_units: str = 'US survey foot', backfill_resolutions: Sequence[int] = (10, 30), min_coverage_fraction: float = 0.999, min_project_area_fraction: float = 0.0, cache_folder: Optional[Union[str, Path]] = None, exclude_tile_ids: Optional[Sequence[str]] = None) -> Dict[str, Any]
Plan every USGS 3DEP tile a terrain build needs, without downloading.
First step of the catalog workflow plan_terrain_tiles() ->
prefetch_terrain_tiles() -> build_terrain_raster(tile_plan=...,
require_cached_tiles=True), which lets many models share one
read-only tile store and build in parallel with no network access.
Network access is required here (tile index, S3 tile listings, and
HEAD requests for provenance).
The AOI is computed by the same private routine
build_terrain_raster() uses, so a plan and a direct build agree.
Tier 1 lists the 1m tiles chosen by coverage-aware selection, in
composite order (oldest project first, filename order within a
project), with the coverage residual. Every backfill tier lists EVERY
seamless 1-degree tile intersecting the AOI, unconditionally: interior
1m voids (water bodies, project edges) cannot be predicted from the
index, and listing all backfill tiles guarantees an offline build is
never missing one. Seamless tiles that do not exist on S3 (for example
over open water) are reported under unavailable_tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_crs
|
str
|
Projected CRS of the HEC-RAS project, e.g.
|
required |
geom_path
|
Optional[Union[str, Path]]
|
Model geometry ( |
None
|
aoi_geometry
|
Optional[Any]
|
Model extent geometry in project CRS. |
None
|
buffer_distance
|
float
|
Absolute AOI buffer. Default 100. Keyword-only. |
100.0
|
buffer_units
|
str
|
Units of |
'US survey foot'
|
backfill_resolutions
|
Sequence[int]
|
Backfill tiers in priority order, from
|
(10, 30)
|
min_coverage_fraction
|
float
|
Tier-1 coverage selection stop condition. Default 0.999. Keyword-only. |
0.999
|
min_project_area_fraction
|
float
|
Tier-1 minimum project contribution. Default 0.0. Keyword-only. |
0.0
|
cache_folder
|
Optional[Union[str, Path]]
|
Tile index cache folder. Keyword-only. |
None
|
exclude_tile_ids
|
Optional[Sequence[str]]
|
Tile ids (filename stems) to leave out of every tier. Keyword-only. |
None
|
Returns:
| Type | Description |
|---|---|
JSON-serializable plan dict
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
project-unit distance), |
Dict[str, Any]
|
CRS, |
Dict[str, Any]
|
|
Dict[str, Any]
|
highest priority first. Each tier has |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
For invalid backfill resolutions or AOI inputs. |
Example
plan = Usgs3depAws.plan_terrain_tiles( ... "EPSG:2277", geom_path="MAHA CREEK.g01" ... ) manifest = Usgs3depAws.prefetch_terrain_tiles(plan, "tile-store") receipt = Usgs3depAws.build_terrain_raster( ... "terrain.tif", "EPSG:2277", ... download_folder="tile-store", ... tile_plan=plan, ... require_cached_tiles=True, ... )
prefetch_terrain_tiles
staticmethod
¶
prefetch_terrain_tiles(plans: Union[Mapping[str, Any], Iterable[Mapping[str, Any]], str, Path], download_folder: Union[str, Path], *, max_workers: int = 4, overwrite: bool = False) -> Dict[str, Any]
Download every tile of one or more tile plans once into a shared store.
Tiles are deduplicated by URL across all plans and written to
download_folder/<product>/<filename>, the layout that
build_terrain_raster(tile_plan=..., require_cached_tiles=True)
reads. An existing file whose size matches the remote Content-Length
is kept (status="cached") unless overwrite is True. Failures
are reported per tile instead of being raised, and a partially written
or size-mismatched file is removed so it cannot be mistaken for a
cached tile. Run this with a single writer; builds may then read the
store concurrently (and read-only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plans
|
Union[Mapping[str, Any], Iterable[Mapping[str, Any]], str, Path]
|
One plan dict (or plan JSON path), or an iterable of them,
from |
required |
download_folder
|
Union[str, Path]
|
Tile store root. |
required |
max_workers
|
int
|
Concurrent tile downloads. Default 4. Keyword-only. |
4
|
overwrite
|
bool
|
Re-download tiles that are already present. Default False. Keyword-only. |
False
|
Returns:
| Type | Description |
|---|---|
JSON-serializable manifest
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no plan is given or a plan has the wrong schema. |
query_tiles_api
staticmethod
¶
Query USGS 3DEP Tile Index API for tiles intersecting a bounding box.
Uses the National Map ArcGIS REST API to get tile information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Any
|
One valid Polygon or a legacy bounds-shaped input in WGS84. |
required |
resolution
|
int
|
DEM resolution in meters (1, 3, 10, or 30) |
required |
buffer_distance
|
float
|
Optional buffer in WGS84 degrees. Default is 0.0. |
0.0
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with tile information including download URLs |
select_projects_for_coverage
staticmethod
¶
select_projects_for_coverage(projects: GeoDataFrame, bbox: Any, min_coverage_fraction: float = 0.999, min_project_area_fraction: float = 0.0) -> Tuple[gpd.GeoDataFrame, Dict[str, Any]]
Greedily select the newest USGS 3DEP project available per sub-area.
A single "most recent project" can be smaller than the requested
extent. Selecting only that project silently drops every sub-area it
does not cover, which shows up later as holes or seams in the terrain
mosaic. This method instead walks the candidate projects newest-first
and keeps each project that contributes new area, falling back to
progressively older projects only for the residual uncovered geometry.
Selection stops as soon as the bbox is covered (within
min_coverage_fraction) or no candidate projects remain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
projects
|
GeoDataFrame
|
Candidate projects, typically from
|
required |
bbox
|
Any
|
One valid Polygon or a legacy bounds-shaped input in WGS84. |
required |
min_coverage_fraction
|
float
|
Stop once this fraction of the bbox area is covered. Default 0.999 (99.9%). |
0.999
|
min_project_area_fraction
|
float
|
Skip a project whose new contribution is smaller than this fraction of the bbox area. Default 0.0, which keeps every project that contributes any positive area. |
0.0
|
Returns:
| Type | Description |
|---|---|
Tuple of ``(selected_projects, coverage_report)``
|
|
- ``selected_projects`` is a GeoDataFrame in EPSG
|
4326, newest
first, with three added columns: |
Tuple[GeoDataFrame, Dict[str, Any]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the coverage fractions are outside their valid ranges. |
Example
>>> from shapely.geometry import box
>>> bbox = box(-77.5, 40.0, -76.5, 41.0)
>>> projects = Usgs3depAws.list_projects_for_bbox(bbox, resolution=1)
>>> selected, report = Usgs3depAws.select_projects_for_coverage(
... projects, bbox
... )
>>> report['covered_fraction']
1.0
>>> [entry['project'] for entry in report['projects']]
['PA_Northcentral_2019_B19', 'PA_South_Central_2017_D17']
TauDEM source reference¶
TauDEM D8 terrain delineation: stream links and their catchments.
RasTauDem runs the TauDEM 5 command-line tools (PitRemove, D8FlowDir,
AreaD8, Threshold, StreamNet) as separate processes and reads their outputs
into GeoDataFrames. TauDEM is never imported, linked or redistributed; it is
GPL-3 software installed separately (https://hydrology.usu.edu/taudem/). MPI
(MS-MPI on Windows; MPICH or Open MPI on Linux) is optional: without
mpiexec each tool runs as a single process.
The stream links and catchments feed :class:ras_commander.subdomain.RasSubdomain,
which uses the downstream end of each link as a pour point and the union of a
link's catchment and every catchment upstream as its contributing area.
Ported from fim-commander fim_commander.methods.rog.delineate (same owner),
without its container and request layers.
Example
from ras_commander.terrain import RasTauDem info = RasTauDem.get_taudem_info() # doctest: +SKIP result = RasTauDem.delineate("Terrain/dem.tif", "work/taudem", ... stream_area_sqmi=0.5, cell_size=30.0) # doctest: +SKIP result.streams[["LINKNO", "DSLINKNO", "DSContArea"]].head() # doctest: +SKIP
RasTauDem
¶
Static wrapper around the TauDEM 5 D8 delineation tools.
get_taudem_info
staticmethod
¶
get_taudem_info(taudem_dir: Union[str, Path, None] = None, mpiexec_path: Union[str, Path, None] = None) -> Dict[str, Any]
Locate the TauDEM tools and the MPI launcher.
Search order for the tools: taudem_dir, then the
RAS_COMMANDER_TAUDEM_DIR environment variable, then PATH, then
the default Windows install folder. For the launcher: mpiexec_path,
then RAS_COMMANDER_MPIEXEC, then PATH, then the default MS-MPI
folder. A missing launcher is reported, not raised, unless one was
named explicitly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
taudem_dir
|
Union[str, Path, None]
|
Folder holding the TauDEM executables. |
None
|
mpiexec_path
|
Union[str, Path, None]
|
MPI launcher executable. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
dict with |
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
TauDemNotFoundError
|
A required TauDEM tool, or a named launcher, is missing. |
delineate
staticmethod
¶
delineate(dem_path: Union[str, Path], dest_folder: Union[str, Path], *, stream_area_sqmi: float = 0.1, cell_size: Optional[float] = None, num_processes: int = 4, edge_contamination_check: bool = False, taudem_dir: Union[str, Path, None] = None, mpiexec_path: Union[str, Path, None] = None, overwrite: bool = False, timeout: Optional[float] = None) -> TauDemDelineation
Delineate D8 stream links and catchments from a DEM.
Runs PitRemove, D8FlowDir, AreaD8, Threshold and StreamNet in
dest_folder, then reads the stream links and polygonizes the
watershed grid. The source DEM is never modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dem_path
|
Union[str, Path]
|
DEM raster in a projected CRS with square, north-up cells
(for example from |
required |
dest_folder
|
Union[str, Path]
|
Output folder. Must be empty or absent unless |
required |
stream_area_sqmi
|
float
|
Contributing area, in square miles, at which a stream begins (Threshold on D8 accumulation). |
0.1
|
cell_size
|
Optional[float]
|
Optional cell size, in DEM horizontal units, to resample
the DEM to (average) before delineation. |
None
|
num_processes
|
int
|
MPI ranks per tool. Ignored (1) without a launcher. |
4
|
edge_contamination_check
|
bool
|
Run AreaD8's edge check, which leaves no
accumulation (so no streams) wherever a cell's contributing area
touches the DEM edge or NoData. Off by default (TauDEM |
False
|
taudem_dir
|
Union[str, Path, None]
|
Folder of TauDEM executables (see |
None
|
mpiexec_path
|
Union[str, Path, None]
|
MPI launcher (see |
None
|
overwrite
|
bool
|
Allow a non-empty |
False
|
timeout
|
Optional[float]
|
Seconds allowed per tool, or |
None
|
Returns:
| Type | Description |
|---|---|
TauDemDelineation
|
TauDemDelineation |
Raises:
| Type | Description |
|---|---|
TauDemNotFoundError
|
TauDEM is not installed or not found. |
TauDemError
|
A tool failed, or the threshold produced no streams. |
ValueError
|
The DEM is not projected or its cells are not square and north-up. |
FileExistsError
|
|
TauDemDelineation
dataclass
¶
TauDEM D8 delineation of one DEM.
Attributes:
| Name | Type | Description |
|---|---|---|
streams |
Any
|
StreamNet links (schema |
catchments |
Any
|
Polygonized StreamNet watershed grid (schema
|
raster_paths |
Dict[str, Path]
|
Output rasters by role ( |
crs |
Any
|
DEM CRS ( |
cell_size |
float
|
DEM cell size used by TauDEM, in DEM horizontal units. |
stream_area_sqmi |
float
|
Contributing-area threshold that defines a stream. |
stream_threshold_cells |
float
|
The same threshold in D8 cells. |
commands |
Tuple[Tuple[str, ...], ...]
|
Exact argument lists that were run, in order. |
edge_contamination_check |
bool
|
Whether AreaD8 checked edge contamination. |
to_dict
¶
Return a JSON-ready summary (frames are summarized by row count).
TauDemNotFoundError
¶
Bases: FileNotFoundError
A TauDEM executable or the requested MPI launcher could not be found.
RAS Commander never downloads or installs TauDEM.
TauDemError
¶
Bases: RuntimeError
A TauDEM tool exited with an error or wrote unusable output.
TerrainBuildError source reference¶
Bases: RuntimeError
Raised when Usgs3depAws.build_terrain_raster() cannot deliver a valid
single-raster terrain.
Attributes:
| Name | Type | Description |
|---|---|---|
reason_code |
Stable machine-readable reason, one of the
|
|
details |
JSON-serializable context such as the nodata pixel count, the bounds of the uncovered pixels, sample pixel-centre locations, and the path of the failure receipt. |
RasTerrainMod source reference¶
Static class for terrain modification analysis via RasMapperLib.dll.
Provides headless terrain sampling with modifications applied, enabling cut/fill analysis and no-net-fill calculations without the RASMapper GUI.
All methods are static - call directly without instantiation
RasTerrainMod.get_terrain_profile(rasmap, geom_hdf, x, y)
Prerequisites
- HEC-RAS 6.6+ installed
- pythonnet installed (pip install pythonnet)
- HEC-RAS GDAL runtime available from the HEC-RAS install
Thread Safety
NOT thread-safe. The .NET RASMapperCom instance is shared and COM objects follow single-threaded apartment (STA) rules. Do not call methods concurrently from multiple threads.
compare_terrain_profiles
staticmethod
¶
compare_terrain_profiles(rasmap_existing: Union[str, Path], rasmap_proposed: Union[str, Path], geom_hdf_path: Union[str, Path], x_coords: List[float], y_coords: List[float], filter_tolerance: float = 0.01, ras_object=None) -> pd.DataFrame
Compare terrain profiles between existing and proposed conditions.
Computes cut/fill along a profile line by differencing terrain elevations from two .rasmap files (each referencing different terrain HDFs with different terrain modifications).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_existing
|
Union[str, Path]
|
Path to .rasmap with existing terrain |
required |
rasmap_proposed
|
Union[str, Path]
|
Path to .rasmap with proposed terrain (with modifications) |
required |
geom_hdf_path
|
Union[str, Path]
|
Path to geometry HDF (shared between both) |
required |
x_coords
|
List[float]
|
X coordinates of profile line |
required |
y_coords
|
List[float]
|
Y coordinates of profile line |
required |
filter_tolerance
|
float
|
Terrain sampling tolerance |
0.01
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
|
-station
|
float - distance along profile |
-existing_elevation
|
float - existing terrain elevation |
-proposed_elevation
|
float - proposed terrain elevation |
-difference
|
float - proposed - existing (positive = fill, negative = cut) |
Example
>>> df = RasTerrainMod.compare_terrain_profiles(
... "existing.rasmap", "proposed.rasmap", "project.g01.hdf",
... x_coords=[3400000, 3410000], y_coords=[612000, 612000]
... )
>>> cut_volume = df[df['difference'] < 0]['difference'].sum()
>>> fill_volume = df[df['difference'] > 0]['difference'].sum()
compare_terrain_volumes
staticmethod
¶
compare_terrain_volumes(rasmap_existing: Union[str, Path], rasmap_proposed: Union[str, Path], geom_hdf_path: Union[str, Path], x_coords: List[float], y_coords: List[float], filter_tolerance: float = 0.01, volume_factor: float = 1.0, ras_object=None) -> pd.DataFrame
Compare elevation-volume curves for no-net-fill analysis.
Computes volume differences between existing and proposed terrain within a polygon, enabling no-net-fill compliance checking.
At each elevation: - net_volume = proposed_volume - existing_volume - Positive net_volume = net fill added - Negative net_volume = net cut (excavation exceeds fill) - Zero net_volume = no-net-fill condition met
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_existing
|
Union[str, Path]
|
Path to .rasmap with existing terrain |
required |
rasmap_proposed
|
Union[str, Path]
|
Path to .rasmap with proposed terrain |
required |
geom_hdf_path
|
Union[str, Path]
|
Path to geometry HDF (shared) |
required |
x_coords
|
List[float]
|
Polygon X coordinates (must close) |
required |
y_coords
|
List[float]
|
Polygon Y coordinates (must close) |
required |
filter_tolerance
|
float
|
Terrain sampling tolerance |
0.01
|
volume_factor
|
float
|
Volume unit conversion (1.0 = cubic feet) |
1.0
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
|
-elevation
|
float - terrain elevation |
-existing_volume
|
float - volume below elevation (existing) |
-proposed_volume
|
float - volume below elevation (proposed) |
-net_volume
|
float - proposed - existing (positive = net fill) |
Example
df = RasTerrainMod.compare_terrain_volumes( ... "existing.rasmap", "proposed.rasmap", "project.g01.hdf", ... x_coords=pond_x, y_coords=pond_y, ... volume_factor=43560.0 # acre-feet ... )
Check no-net-fill at 100-year flood elevation¶
flood_elev = 10.0 row = df[df['elevation'] >= flood_elev].iloc[0] print(f"Net volume at {flood_elev} ft: {row['net_volume']:.1f} ac-ft")
compute_modified_terrain_raster
staticmethod
¶
compute_modified_terrain_raster(rasmap_path: Union[str, Path], geom_hdf_path: Union[str, Path], terrain_tif_path: Union[str, Path], output_tif_path: Optional[Union[str, Path]] = None, filter_tolerance: float = 0.0, ras_object=None) -> Optional[np.ndarray]
Compute a full-resolution raster of terrain with modifications applied.
.. deprecated:: 0.99.2
Use :meth:RasTerrain.export_rasmapper_terrain with
downsample_factor=1 and rasterize_modifications=True.
This compatibility method samples one horizontal terrain profile
per row and is not equivalent to RAS Mapper's native registered-
terrain consolidation.
Reads the original terrain GeoTIFF to determine the output grid (CRS, resolution, extent), then samples the modified terrain (with channels, levees, polygon overrides, etc.) at each cell center row-by-row via RasMapperLib. Where sampling succeeds, modified elevations replace the original; where it fails (e.g., outside the geometry extent), the original terrain value is preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_path
|
Union[str, Path]
|
Path to .rasmap project file |
required |
geom_hdf_path
|
Union[str, Path]
|
Path to geometry HDF file (.g##.hdf) |
required |
terrain_tif_path
|
Union[str, Path]
|
Path to original terrain GeoTIFF (defines output grid) |
required |
output_tif_path
|
Optional[Union[str, Path]]
|
If provided, writes result to GeoTIFF (deflate compressed) |
None
|
filter_tolerance
|
float
|
Douglas-Peucker vertical filter tolerance for profile sampling (default 0.0 = maximum detail, no filtering) |
0.0
|
Returns:
| Type | Description |
|---|---|
Optional[ndarray]
|
2D numpy array (float32) of modified terrain elevations, same shape as |
Optional[ndarray]
|
the input terrain raster. None if the terrain TIF cannot be read. |
Platform
Windows only (requires HEC-RAS 6.6+ and pythonnet).
Example
RasTerrainMod.setup_gdal_bridge() arr = RasTerrainMod.compute_modified_terrain_raster( ... "project.rasmap", "project.g01.hdf", ... "Terrain/Terrain.tif", ... output_tif_path="Terrain/Terrain_modified.tif" ... ) print(f"Shape: {arr.shape}, range: {arr.min():.1f} to {arr.max():.1f}")
get_terrain_extent
staticmethod
¶
get_terrain_extent(rasmap_path: Union[str, Path], geom_hdf_path: Union[str, Path], ras_object=None) -> dict
Get the terrain bounding box with modifications applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_path
|
Union[str, Path]
|
Path to .rasmap project file |
required |
geom_hdf_path
|
Union[str, Path]
|
Path to geometry HDF file (.g##.hdf) |
required |
Returns:
| Type | Description |
|---|---|
dict with keys
|
success, min_x, max_x, min_y, max_y |
Example
extent = RasTerrainMod.get_terrain_extent( ... "project.rasmap", "project.g01.hdf" ... ) print(f"Extent: {extent['min_x']:.0f} to {extent['max_x']:.0f}")
get_terrain_profile
staticmethod
¶
get_terrain_profile(rasmap_path: Union[str, Path], geom_hdf_path: Union[str, Path], x_coords: List[float], y_coords: List[float], filter_tolerance: float = 0.01, ras_object=None, *, isolated: bool = False, timeout_seconds: float = 7200, runtime_record: str | Path | None = None) -> pd.DataFrame
Sample terrain elevation along a polyline with modifications applied.
The terrain profile includes ALL terrain modifications (channels, levees, polygon overrides, etc.) that exist in the terrain HDF referenced by the .rasmap file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_path
|
Union[str, Path]
|
Path to .rasmap project file |
required |
geom_hdf_path
|
Union[str, Path]
|
Path to geometry HDF file (.g##.hdf) |
required |
x_coords
|
List[float]
|
X coordinates defining the profile polyline |
required |
y_coords
|
List[float]
|
Y coordinates defining the profile polyline |
required |
filter_tolerance
|
float
|
Douglas-Peucker vertical filter tolerance (default 0.01) |
0.01
|
isolated
|
bool
|
Use a native-only HEC-RAS 6.6 process with verified bundled HDF5. |
False
|
timeout_seconds
|
float
|
Positive session limit for isolated queries, in seconds. |
7200
|
runtime_record
|
str | Path | None
|
Optional new loader/control JSON record; completed requires restoration and exit zero. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
|
-station
|
float - distance along polyline (project units) |
-elevation
|
float - terrain elevation with modifications |
Example
profile = RasTerrainMod.get_terrain_profile( ... "project.rasmap", "project.g01.hdf", ... x_coords=[3400000, 3410000], ... y_coords=[612000, 612000] ... ) profile.plot(x='station', y='elevation')
iter_terrain_point_elevations
staticmethod
¶
iter_terrain_point_elevations(rasmap_path: str | Path, terrain_name: str, point_batches: Iterable[ndarray], cell_size: float, use_obstructions: bool = True, nodata_values: Sequence[float] = (-9999.0,), *, isolated: bool = False, timeout_seconds: float = 7200, runtime_record: str | Path | None = None) -> Iterator[np.ndarray]
Read native elevations at explicitly supplied binary64 coordinates.
Coordinates are bounded (n, 2) Float64 batches in the selected
registered terrain's horizontal CRS. Returned Float32 arrays preserve
point order and cardinality, in its vertical units/datum. Each caller
batch uses serial native calls of at most 65536 points; every internal
result is validated before yielding the complete caller batch. No coordinate
transform, profile interpolation or source-value fallback is performed.
cell_size is passed to the native evaluator in horizontal CRS units;
use_obstructions selects native modification/obstruction application.
Missing, nonfinite, caller-specified nodata and Single endpoint sentinel
values raise. Sources are read-only; only an optional runtime_record is written.
Requires the qualified public PointM-array overload in an isolated HEC-RAS 6.6 Windows runtime (also callable in an owned Wine worker). The layer is loaded once per iterator. Exhaust it serially; native SharedData is process-global and this API is not thread-safe. This is point readback, not a replacement registered-terrain consolidation API. With isolated=True, native evaluation runs in a native-only child process that verifies the bundled thread-safe HDF5 DLL before opening the layer. timeout_seconds bounds native worker lifetime and charges caller batch production time, but cannot preempt the caller's Python iterator itself. runtime_record writes a new loader/control JSON record; completed status requires verified restoration and exit zero, while failures retain initialized status; it is runtime identity evidence, not a query-completion or hydraulic receipt.
get_terrain_volume_elevation
staticmethod
¶
get_terrain_volume_elevation(rasmap_path: Union[str, Path], geom_hdf_path: Union[str, Path], x_coords: List[float], y_coords: List[float], filter_tolerance: float = 0.01, volume_factor: float = 1.0, ras_object=None) -> pd.DataFrame
Compute elevation-volume curve for a polygon with modifications applied.
Returns the volume of space below each elevation within the polygon, computed from the modified terrain surface (including channels, ponds, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rasmap_path
|
Union[str, Path]
|
Path to .rasmap project file |
required |
geom_hdf_path
|
Union[str, Path]
|
Path to geometry HDF file (.g##.hdf) |
required |
x_coords
|
List[float]
|
X coordinates of polygon vertices (must close - first == last) |
required |
y_coords
|
List[float]
|
Y coordinates of polygon vertices (must close - first == last) |
required |
filter_tolerance
|
float
|
Terrain sampling tolerance (default 0.01) |
0.01
|
volume_factor
|
float
|
Volume conversion factor: - 1.0 = cubic feet (if project units are feet) - 43560.0 = acre-feet - 0.0283168 = cubic meters (from cubic feet) |
1.0
|
Returns:
| Type | Description |
|---|---|
DataFrame with columns
|
|
-elevation
|
float - terrain elevation |
-volume
|
float - cumulative volume below that elevation |
Example
Define a pond polygon (must close)¶
x = [3400000, 3400500, 3400500, 3400000, 3400000] y = [612000, 612000, 612500, 612500, 612000] ev = RasTerrainMod.get_terrain_volume_elevation( ... "project.rasmap", "project.g01.hdf", x, y ... ) ev.plot(x='elevation', y='volume', title='Elev-Volume Curve')
setup_gdal_bridge
staticmethod
¶
setup_gdal_bridge(hecras_version: str = '7.0', python_dir: Optional[Union[str, Path]] = None, create_junction: bool = True) -> bool
Configure HEC-RAS GDAL runtime for pythonnet/RasMapperLib.
The default path points GDAL_DATA, PROJ_LIB, PATH, and Python DLL search
directories at HEC-RAS's bundled GDAL runtime, then verifies the legacy
python.exe sibling GDAL bridge before RasMapperLib is loaded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hecras_version
|
str
|
HEC-RAS version to use (default "7.0") |
'7.0'
|
python_dir
|
Optional[Union[str, Path]]
|
Python installation directory for legacy junction mode |
None
|
create_junction
|
bool
|
Verify/create the legacy python.exe sibling junction |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the process runtime was configured successfully. |
RasTerrainModification source reference¶
Bases: RasTerrainModWriter
User-facing alias for terrain modification writer APIs.
add_channel_modification
staticmethod
¶
add_channel_modification(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], name: str, polyline_points: Union[ndarray, Sequence[Sequence[float]]], width: float = 50.0, depth: Optional[float] = None, left_slope: float = 3.0, right_slope: float = 3.0, max_extent: float = 200.0, elev_pt_tolerance: float = 50.0, group_name: str = 'Modifications', *, elevation: Optional[float] = None, profile_points: Optional[Union[ndarray, Sequence[Sequence[float]]]] = None, mode: Union[str, int] = 'take_lower', transition_fraction: Optional[float] = None, system_name: Optional[str] = None, priority: Optional[int] = None) -> Path
Add a channel terrain modification along a polyline alignment.
Creates a trapezoidal channel cut into the terrain along the given polyline. The channel uses "TakeLower" mode - the terrain is lowered where the channel cross-section is below the existing ground.
RAS Mapper stores a channel invert as an absolute elevation
profile along the line. Give it as profile_points, elevation
or a Z column in polyline_points. Alternatively give depth:
the invert is then the terrain source elevation sampled at each
vertex minus depth (needs rasterio and the terrain's source
rasters). With no profile input, depth defaults to 10.
Parameters¶
terrain_hdf_path : Path
Path to the terrain HDF file (e.g., Terrain50.hdf).
rasmap_path : Path
Path to the .rasmap XML file.
name : str
Name for this channel modification (e.g., "Main Channel").
polyline_points : np.ndarray
Nx2 array of (x, y) coordinates defining the channel alignment,
or Nx3 with the absolute invert elevation as Z.
Must be in the same coordinate system as the terrain.
width : float
Bottom width of the trapezoidal channel in terrain units (default 50).
depth : float, optional
Invert depth below the sampled terrain surface at each vertex.
Mutually exclusive with elevation/profile_points/Z.
left_slope : float
Left side slope as H:V ratio (default 3.0 = 3H:1V).
right_slope : float
Right side slope as H:V ratio (default 3.0 = 3H:1V).
max_extent : float
Total footprint width in terrain units, half on each side of the
line (RAS Mapper's Max Reach; default 200).
elev_pt_tolerance : float
Elevation point tolerance (default 50).
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
elevation : float, optional
Constant absolute invert elevation.
profile_points : array-like, optional
Nx2 station/absolute-elevation invert profile, stations from 0
along the line.
mode : {"take_lower", "set_value"} or int
take_lower (default) only lowers the terrain.
transition_fraction : float, optional
Transition Percent; NaN by default, as RAS Mapper stores it.
system_name : str, optional
System Name; leave empty for an ordinary channel (see
:meth:add_high_ground_modification).
priority : int, optional
Position in the modification list; 0 (default) is the top layer.
Returns¶
Path Path to the modified terrain HDF file.
add_fill_surface_modification
staticmethod
¶
add_fill_surface_modification(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], name: str, polyline_points: Union[ndarray, Sequence[Sequence[float]]], top_width: float = 20.0, side_slope: float = 2.0, left_slope: Optional[float] = None, right_slope: Optional[float] = None, max_extent: float = 100.0, elevation: Optional[float] = None, profile_points: Optional[Union[ndarray, Sequence[Sequence[float]]]] = None, elev_pt_tolerance: float = 50.0, transition_fraction: Optional[float] = None, group_name: str = 'Modifications', system_name: Optional[str] = None, priority: Optional[int] = None) -> Path
Add a set-value fill-surface terrain modification along a line.
This is a convenience wrapper around :meth:add_high_ground_modification
with mode="fill_surface" for floodway and encroachment fill
workflows.
add_high_ground_modification
staticmethod
¶
add_high_ground_modification(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], name: str, polyline_points: Union[ndarray, Sequence[Sequence[float]]], top_width: float = 20.0, side_slope: float = 2.0, left_slope: Optional[float] = None, right_slope: Optional[float] = None, max_extent: float = 100.0, elevation: Optional[float] = None, profile_points: Optional[Union[ndarray, Sequence[Sequence[float]]]] = None, mode: Union[str, int] = 'take_higher', elev_pt_tolerance: float = 50.0, transition_fraction: Optional[float] = None, group_name: str = 'Modifications', system_name: Optional[str] = None, priority: Optional[int] = None) -> Path
Add a high-ground line terrain modification for levees or roads.
This writes the RAS Mapper Lines | High Ground style terrain
modification. The default mode is take_higher so the proposed
trapezoidal crest raises low ground but does not cut terrain that is
already higher. Pass mode="fill_surface" or use
:meth:add_fill_surface_modification for encroachment fill surfaces.
Parameters¶
terrain_hdf_path : Path
Path to the copied terrain HDF file to modify.
rasmap_path : Path
Path to the .rasmap XML file where the terrain layer is registered.
name : str
Name for this terrain modification layer.
polyline_points : array-like
Nx2 or Nx3 array of line coordinates. Nx3 input uses the third
column as the crest/fill elevation profile when elevation and
profile_points are omitted.
top_width : float
Flat crest/top width in terrain units.
side_slope : float
Default side slope as H:V ratio, used when left/right are omitted.
left_slope, right_slope : float, optional
Explicit left and right side slopes as H:V ratios.
max_extent : float
Total footprint width in terrain units, half on each side of the
line (RAS Mapper's Max Reach).
elevation : float, optional
Constant crest/fill elevation. Required when polyline_points has
no Z column and profile_points is not provided.
profile_points : array-like, optional
Nx2 station/elevation profile along the line (absolute
elevations; stations from 0 along the line). Overrides Z values in
polyline_points when provided.
mode : {"take_higher", "fill_surface"} or int
Terrain merge mode. take_higher writes Higher Terrain Value;
fill_surface writes Set Value.
elev_pt_tolerance : float
Elevation point tolerance.
transition_fraction : float, optional
Transition Percent. RAS Mapper uses it only for system joins;
the default stores NaN, as RAS Mapper does.
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
system_name : str, optional
System Name. Leave empty (default) for an ordinary line. Any
non-empty name makes RAS Mapper build the feature through its
system path, even a lone feature, which changes its footprint.
priority : int, optional
Position in the modification list; 0 (default) is the top layer,
applied last, so it wins where layers overlap.
Returns¶
Path Path to the modified terrain HDF file.
add_modification_group
staticmethod
¶
add_modification_group(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], group_name: str = 'Modifications') -> None
Add an empty modification group to terrain HDF and .rasmap.
This creates the group structure without any actual modifications. Use add_channel_modification() to add modifications to the group.
Parameters¶
terrain_hdf_path : Path
Path to the terrain HDF file.
rasmap_path : Path
Path to the .rasmap XML file.
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
add_modification_polygon
staticmethod
¶
add_modification_polygon(terrain_hdf_path: Union[str, Path], name: str, polygon_coords: Any, elevation_method: str = 'boundary_from_terrain', control_points: Optional[Sequence[Any]] = None, rasmap_path: Optional[Union[str, Path]] = None, boundary_elevations: Optional[Union[ndarray, Sequence[float]]] = None, mode: Union[str, int] = 'set_value', elev_pt_tolerance: float = 50.0, group_name: str = 'Modifications', elevation: Optional[float] = None, priority: Optional[int] = None, perimeter_control_points: Optional[Sequence[Any]] = None) -> Path
Add a polygon multipoint terrain modification.
This writes the RAS Mapper Polygons | Multipoint style sidecar
data. Boundary elevations can be sampled from the terrain source raster
references stored in the terrain HDF, supplied from polygon Z values, or
passed explicitly. Interior control points are persisted as point
features with their elevations for detention pond and wetland grading
workflows.
Parameters¶
terrain_hdf_path : Path
Path to the copied terrain HDF file to modify.
name : str
Name for this terrain modification layer.
polygon_coords : array-like or GeoJSON-like
Polygon boundary as an Nx2/Nx3 ring or a sequence of rings. Rings
are closed automatically when needed.
elevation_method : {"boundary_from_terrain", "shape_z", "provided", "constant"}
Source for polygon boundary elevations. boundary_from_terrain
samples the terrain source raster(s); shape_z uses the third
coordinate from polygon_coords; provided uses
boundary_elevations; constant (implied by elevation)
sets the whole polygon to one elevation.
How RAS Mapper applies each form (HEC-RAS 6.6 and 7.0.1):
a constant or level boundary is stored as RAS Mapper's constant
``Elevation Value``. A varying ``shape_z``/``provided`` boundary
is stored as vertex Z with ``Use ShapeFile Z Elevations`` on and
``Generate Boundary Elevations`` off, which every version
interpolates from the vertices. ``boundary_from_terrain`` sets
``Generate Boundary Elevations``: 6.7 (betas), 7.0, 7.0.1 and
7.0.2 use the stored sampled profile, while 6.6 stores no polygon
profile and samples the terrain itself. With
``perimeter_control_points`` every version from 6.6 to 7.0.2
takes the boundary from those points instead.
control_points : sequence, optional
Interior elevation points as (x, y, elevation) tuples or dicts
with x, y, and elevation/z keys. They must lie
inside or on the polygon exterior; RAS Mapper uses them as
interior mass points.
perimeter_control_points : sequence, optional
Boundary elevation points in the same forms, each strictly
outside the polygon exterior and within elev_pt_tolerance of
it (RAS Mapper ignores a point farther away). RAS Mapper projects
them onto the perimeter and interpolates the boundary profile
between them, so the boundary does not depend on the terrain.
This is the one boundary-elevation form that HEC-RAS 6.6 renders
like the later releases, and the only one the native engine
accepts under its 6.6 rule. Needs
elevation_method="boundary_from_terrain" (Generate Boundary
Elevations on) and a single-ring polygon. They are written to
the layer's Control Points group after control_points,
in the layout RAS Mapper itself reads (exported identically by
HEC-RAS 6.6, 6.7 Beta 4/5, 7.0, 7.0.1 and 7.0.2).
rasmap_path : Path, optional
Path to the .rasmap XML file. When omitted, the writer searches the
terrain folder and project folder for a .rasmap referencing this
terrain HDF.
boundary_elevations : array-like, optional
Explicit boundary elevations matching the closed polygon point
count. Used with elevation_method="provided".
mode : str or int
Terrain merge mode. Multipoint polygon pond workflows typically use
set_value.
elev_pt_tolerance : float
Elevation point tolerance written to HDF and .rasmap metadata.
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
elevation : float, optional
Constant polygon elevation (elevation_method="constant").
priority : int, optional
Position in the modification list; 0 (default) is the top layer.
Returns¶
Path Path to the modified terrain HDF file.
apply_modification_to_profile
staticmethod
¶
apply_modification_to_profile(terrain_hdf_path: Union[str, Path], name: str, profile: DataFrame, x_coords: Optional[Sequence[float]] = None, y_coords: Optional[Sequence[float]] = None, station_col: str = 'station', elevation_col: str = 'elevation', x_col: str = 'x', y_col: str = 'y') -> pd.DataFrame
Apply a line terrain modification to an existing terrain profile.
The profile can either include XY coordinate columns or be paired with the original profile polyline coordinates. The returned DataFrame keeps the original profile station and adds proposed elevation and difference columns suitable for before/after profile plots.
compare_before_after_profiles
staticmethod
¶
compare_before_after_profiles(rasmap_existing: Union[str, Path], rasmap_modified: Union[str, Path], geom_hdf_path: Union[str, Path], x_coords: List[float], y_coords: List[float], filter_tolerance: float = 0.01) -> pd.DataFrame
Compare terrain profiles before and after a terrain modification.
This delegates to :meth:RasTerrainMod.compare_terrain_profiles, so it
requires HEC-RAS/RasMapperLib on the host. The writer itself remains
cross-platform and does not import pythonnet until this helper is used.
get_modification_profile
staticmethod
¶
Read a terrain modification station/elevation profile from HDF.
This helper verifies the writer output and gives users a lightweight
way to inspect levee or fill-surface elevations before sampling the
modified terrain with :class:RasTerrainMod.
list_modifications
staticmethod
¶
List terrain modifications stored in a terrain HDF sidecar group.
Returns¶
pandas.DataFrame One row per modification with name, subtype, merge mode, width, slopes, max extent, and profile point count.
sample_modification_surface
staticmethod
¶
sample_modification_surface(terrain_hdf_path: Union[str, Path], name: str, points: Union[ndarray, Sequence[Sequence[float]], DataFrame], existing_elevations: Optional[Union[ndarray, Sequence[float], Series]] = None, x_col: str = 'x', y_col: str = 'y') -> pd.DataFrame
Evaluate a line terrain modification at XY points.
This helper reads the ground-line sidecar data written under
/Modifications/<name> and computes the proposed trapezoidal
surface at each supplied XY point. When existing_elevations are
supplied, the terrain merge mode is applied and the returned
modified_elevation and difference columns provide a lightweight
before/after check without invoking the RAS Mapper GUI.
Parameters¶
terrain_hdf_path : Path
Terrain HDF containing the modification sidecar group.
name : str
Modification layer name under /Modifications.
points : array-like or pandas.DataFrame
Nx2 XY coordinates or a DataFrame with x_col/y_col.
existing_elevations : array-like, optional
Existing terrain elevations at the same points.
x_col, y_col : str
DataFrame coordinate column names used when points is a
DataFrame.
Returns¶
pandas.DataFrame Columns include XY coordinates, projected line station, signed offset, proposed modification surface, merge-mode-applied elevation, and before/after difference when existing elevations are supplied.
RasTerrainModWriter source reference¶
Write terrain modifications to HEC-RAS terrain HDF and .rasmap files.
add_channel_modification
staticmethod
¶
add_channel_modification(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], name: str, polyline_points: Union[ndarray, Sequence[Sequence[float]]], width: float = 50.0, depth: Optional[float] = None, left_slope: float = 3.0, right_slope: float = 3.0, max_extent: float = 200.0, elev_pt_tolerance: float = 50.0, group_name: str = 'Modifications', *, elevation: Optional[float] = None, profile_points: Optional[Union[ndarray, Sequence[Sequence[float]]]] = None, mode: Union[str, int] = 'take_lower', transition_fraction: Optional[float] = None, system_name: Optional[str] = None, priority: Optional[int] = None) -> Path
Add a channel terrain modification along a polyline alignment.
Creates a trapezoidal channel cut into the terrain along the given polyline. The channel uses "TakeLower" mode - the terrain is lowered where the channel cross-section is below the existing ground.
RAS Mapper stores a channel invert as an absolute elevation
profile along the line. Give it as profile_points, elevation
or a Z column in polyline_points. Alternatively give depth:
the invert is then the terrain source elevation sampled at each
vertex minus depth (needs rasterio and the terrain's source
rasters). With no profile input, depth defaults to 10.
Parameters¶
terrain_hdf_path : Path
Path to the terrain HDF file (e.g., Terrain50.hdf).
rasmap_path : Path
Path to the .rasmap XML file.
name : str
Name for this channel modification (e.g., "Main Channel").
polyline_points : np.ndarray
Nx2 array of (x, y) coordinates defining the channel alignment,
or Nx3 with the absolute invert elevation as Z.
Must be in the same coordinate system as the terrain.
width : float
Bottom width of the trapezoidal channel in terrain units (default 50).
depth : float, optional
Invert depth below the sampled terrain surface at each vertex.
Mutually exclusive with elevation/profile_points/Z.
left_slope : float
Left side slope as H:V ratio (default 3.0 = 3H:1V).
right_slope : float
Right side slope as H:V ratio (default 3.0 = 3H:1V).
max_extent : float
Total footprint width in terrain units, half on each side of the
line (RAS Mapper's Max Reach; default 200).
elev_pt_tolerance : float
Elevation point tolerance (default 50).
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
elevation : float, optional
Constant absolute invert elevation.
profile_points : array-like, optional
Nx2 station/absolute-elevation invert profile, stations from 0
along the line.
mode : {"take_lower", "set_value"} or int
take_lower (default) only lowers the terrain.
transition_fraction : float, optional
Transition Percent; NaN by default, as RAS Mapper stores it.
system_name : str, optional
System Name; leave empty for an ordinary channel (see
:meth:add_high_ground_modification).
priority : int, optional
Position in the modification list; 0 (default) is the top layer.
Returns¶
Path Path to the modified terrain HDF file.
add_fill_surface_modification
staticmethod
¶
add_fill_surface_modification(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], name: str, polyline_points: Union[ndarray, Sequence[Sequence[float]]], top_width: float = 20.0, side_slope: float = 2.0, left_slope: Optional[float] = None, right_slope: Optional[float] = None, max_extent: float = 100.0, elevation: Optional[float] = None, profile_points: Optional[Union[ndarray, Sequence[Sequence[float]]]] = None, elev_pt_tolerance: float = 50.0, transition_fraction: Optional[float] = None, group_name: str = 'Modifications', system_name: Optional[str] = None, priority: Optional[int] = None) -> Path
Add a set-value fill-surface terrain modification along a line.
This is a convenience wrapper around :meth:add_high_ground_modification
with mode="fill_surface" for floodway and encroachment fill
workflows.
add_high_ground_modification
staticmethod
¶
add_high_ground_modification(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], name: str, polyline_points: Union[ndarray, Sequence[Sequence[float]]], top_width: float = 20.0, side_slope: float = 2.0, left_slope: Optional[float] = None, right_slope: Optional[float] = None, max_extent: float = 100.0, elevation: Optional[float] = None, profile_points: Optional[Union[ndarray, Sequence[Sequence[float]]]] = None, mode: Union[str, int] = 'take_higher', elev_pt_tolerance: float = 50.0, transition_fraction: Optional[float] = None, group_name: str = 'Modifications', system_name: Optional[str] = None, priority: Optional[int] = None) -> Path
Add a high-ground line terrain modification for levees or roads.
This writes the RAS Mapper Lines | High Ground style terrain
modification. The default mode is take_higher so the proposed
trapezoidal crest raises low ground but does not cut terrain that is
already higher. Pass mode="fill_surface" or use
:meth:add_fill_surface_modification for encroachment fill surfaces.
Parameters¶
terrain_hdf_path : Path
Path to the copied terrain HDF file to modify.
rasmap_path : Path
Path to the .rasmap XML file where the terrain layer is registered.
name : str
Name for this terrain modification layer.
polyline_points : array-like
Nx2 or Nx3 array of line coordinates. Nx3 input uses the third
column as the crest/fill elevation profile when elevation and
profile_points are omitted.
top_width : float
Flat crest/top width in terrain units.
side_slope : float
Default side slope as H:V ratio, used when left/right are omitted.
left_slope, right_slope : float, optional
Explicit left and right side slopes as H:V ratios.
max_extent : float
Total footprint width in terrain units, half on each side of the
line (RAS Mapper's Max Reach).
elevation : float, optional
Constant crest/fill elevation. Required when polyline_points has
no Z column and profile_points is not provided.
profile_points : array-like, optional
Nx2 station/elevation profile along the line (absolute
elevations; stations from 0 along the line). Overrides Z values in
polyline_points when provided.
mode : {"take_higher", "fill_surface"} or int
Terrain merge mode. take_higher writes Higher Terrain Value;
fill_surface writes Set Value.
elev_pt_tolerance : float
Elevation point tolerance.
transition_fraction : float, optional
Transition Percent. RAS Mapper uses it only for system joins;
the default stores NaN, as RAS Mapper does.
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
system_name : str, optional
System Name. Leave empty (default) for an ordinary line. Any
non-empty name makes RAS Mapper build the feature through its
system path, even a lone feature, which changes its footprint.
priority : int, optional
Position in the modification list; 0 (default) is the top layer,
applied last, so it wins where layers overlap.
Returns¶
Path Path to the modified terrain HDF file.
add_modification_group
staticmethod
¶
add_modification_group(terrain_hdf_path: Union[str, Path], rasmap_path: Union[str, Path], group_name: str = 'Modifications') -> None
Add an empty modification group to terrain HDF and .rasmap.
This creates the group structure without any actual modifications. Use add_channel_modification() to add modifications to the group.
Parameters¶
terrain_hdf_path : Path
Path to the terrain HDF file.
rasmap_path : Path
Path to the .rasmap XML file.
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
add_modification_polygon
staticmethod
¶
add_modification_polygon(terrain_hdf_path: Union[str, Path], name: str, polygon_coords: Any, elevation_method: str = 'boundary_from_terrain', control_points: Optional[Sequence[Any]] = None, rasmap_path: Optional[Union[str, Path]] = None, boundary_elevations: Optional[Union[ndarray, Sequence[float]]] = None, mode: Union[str, int] = 'set_value', elev_pt_tolerance: float = 50.0, group_name: str = 'Modifications', elevation: Optional[float] = None, priority: Optional[int] = None, perimeter_control_points: Optional[Sequence[Any]] = None) -> Path
Add a polygon multipoint terrain modification.
This writes the RAS Mapper Polygons | Multipoint style sidecar
data. Boundary elevations can be sampled from the terrain source raster
references stored in the terrain HDF, supplied from polygon Z values, or
passed explicitly. Interior control points are persisted as point
features with their elevations for detention pond and wetland grading
workflows.
Parameters¶
terrain_hdf_path : Path
Path to the copied terrain HDF file to modify.
name : str
Name for this terrain modification layer.
polygon_coords : array-like or GeoJSON-like
Polygon boundary as an Nx2/Nx3 ring or a sequence of rings. Rings
are closed automatically when needed.
elevation_method : {"boundary_from_terrain", "shape_z", "provided", "constant"}
Source for polygon boundary elevations. boundary_from_terrain
samples the terrain source raster(s); shape_z uses the third
coordinate from polygon_coords; provided uses
boundary_elevations; constant (implied by elevation)
sets the whole polygon to one elevation.
How RAS Mapper applies each form (HEC-RAS 6.6 and 7.0.1):
a constant or level boundary is stored as RAS Mapper's constant
``Elevation Value``. A varying ``shape_z``/``provided`` boundary
is stored as vertex Z with ``Use ShapeFile Z Elevations`` on and
``Generate Boundary Elevations`` off, which every version
interpolates from the vertices. ``boundary_from_terrain`` sets
``Generate Boundary Elevations``: 6.7 (betas), 7.0, 7.0.1 and
7.0.2 use the stored sampled profile, while 6.6 stores no polygon
profile and samples the terrain itself. With
``perimeter_control_points`` every version from 6.6 to 7.0.2
takes the boundary from those points instead.
control_points : sequence, optional
Interior elevation points as (x, y, elevation) tuples or dicts
with x, y, and elevation/z keys. They must lie
inside or on the polygon exterior; RAS Mapper uses them as
interior mass points.
perimeter_control_points : sequence, optional
Boundary elevation points in the same forms, each strictly
outside the polygon exterior and within elev_pt_tolerance of
it (RAS Mapper ignores a point farther away). RAS Mapper projects
them onto the perimeter and interpolates the boundary profile
between them, so the boundary does not depend on the terrain.
This is the one boundary-elevation form that HEC-RAS 6.6 renders
like the later releases, and the only one the native engine
accepts under its 6.6 rule. Needs
elevation_method="boundary_from_terrain" (Generate Boundary
Elevations on) and a single-ring polygon. They are written to
the layer's Control Points group after control_points,
in the layout RAS Mapper itself reads (exported identically by
HEC-RAS 6.6, 6.7 Beta 4/5, 7.0, 7.0.1 and 7.0.2).
rasmap_path : Path, optional
Path to the .rasmap XML file. When omitted, the writer searches the
terrain folder and project folder for a .rasmap referencing this
terrain HDF.
boundary_elevations : array-like, optional
Explicit boundary elevations matching the closed polygon point
count. Used with elevation_method="provided".
mode : str or int
Terrain merge mode. Multipoint polygon pond workflows typically use
set_value.
elev_pt_tolerance : float
Elevation point tolerance written to HDF and .rasmap metadata.
group_name : str
.rasmap modification group. Only "Modifications" (the
default) is accepted: RAS Mapper applies a terrain's
modifications only from a group with that exact name, so any
other name raises :class:ValueError.
elevation : float, optional
Constant polygon elevation (elevation_method="constant").
priority : int, optional
Position in the modification list; 0 (default) is the top layer.
Returns¶
Path Path to the modified terrain HDF file.
apply_modification_to_profile
staticmethod
¶
apply_modification_to_profile(terrain_hdf_path: Union[str, Path], name: str, profile: DataFrame, x_coords: Optional[Sequence[float]] = None, y_coords: Optional[Sequence[float]] = None, station_col: str = 'station', elevation_col: str = 'elevation', x_col: str = 'x', y_col: str = 'y') -> pd.DataFrame
Apply a line terrain modification to an existing terrain profile.
The profile can either include XY coordinate columns or be paired with the original profile polyline coordinates. The returned DataFrame keeps the original profile station and adds proposed elevation and difference columns suitable for before/after profile plots.
compare_before_after_profiles
staticmethod
¶
compare_before_after_profiles(rasmap_existing: Union[str, Path], rasmap_modified: Union[str, Path], geom_hdf_path: Union[str, Path], x_coords: List[float], y_coords: List[float], filter_tolerance: float = 0.01) -> pd.DataFrame
Compare terrain profiles before and after a terrain modification.
This delegates to :meth:RasTerrainMod.compare_terrain_profiles, so it
requires HEC-RAS/RasMapperLib on the host. The writer itself remains
cross-platform and does not import pythonnet until this helper is used.
get_modification_profile
staticmethod
¶
Read a terrain modification station/elevation profile from HDF.
This helper verifies the writer output and gives users a lightweight
way to inspect levee or fill-surface elevations before sampling the
modified terrain with :class:RasTerrainMod.
list_modifications
staticmethod
¶
List terrain modifications stored in a terrain HDF sidecar group.
Returns¶
pandas.DataFrame One row per modification with name, subtype, merge mode, width, slopes, max extent, and profile point count.
sample_modification_surface
staticmethod
¶
sample_modification_surface(terrain_hdf_path: Union[str, Path], name: str, points: Union[ndarray, Sequence[Sequence[float]], DataFrame], existing_elevations: Optional[Union[ndarray, Sequence[float], Series]] = None, x_col: str = 'x', y_col: str = 'y') -> pd.DataFrame
Evaluate a line terrain modification at XY points.
This helper reads the ground-line sidecar data written under
/Modifications/<name> and computes the proposed trapezoidal
surface at each supplied XY point. When existing_elevations are
supplied, the terrain merge mode is applied and the returned
modified_elevation and difference columns provide a lightweight
before/after check without invoking the RAS Mapper GUI.
Parameters¶
terrain_hdf_path : Path
Terrain HDF containing the modification sidecar group.
name : str
Modification layer name under /Modifications.
points : array-like or pandas.DataFrame
Nx2 XY coordinates or a DataFrame with x_col/y_col.
existing_elevations : array-like, optional
Existing terrain elevations at the same points.
x_col, y_col : str
DataFrame coordinate column names used when points is a
DataFrame.
Returns¶
pandas.DataFrame Columns include XY coordinates, projected line station, signed offset, proposed modification surface, merge-mode-applied elevation, and before/after difference when existing elevations are supplied.
TerrainExportResult source reference¶
Result of a supervised native RAS Mapper terrain export.
bool(result) is true only when the native output passed semantic
validation and both the GeoTIFF and machine-readable receipt were
promoted to their requested paths.
failure_kind classifies a failed export so callers can choose a
response without parsing error text:
"out_of_memory": the native helper raised .NETSystem.OutOfMemoryException. A retry with more memory may succeed."empty_extent": RAS Mapper could not compute statistics for the export window, and a host-side scan confirmed that no registered source has a valid cell in it."empty_extent_unconfirmed": RAS Mapper reported the same statistics error, but the source coverage scan could not be completed."no_response"/"invalid_response": the helper wrote no response file, or a response that failed schema validation."native_error": any other exception reported by the helper."timeout": the bounded runtime expired."error": a host-side failure, such as GeoTIFF validation.
helper_invocations records each helper call: its request, exit code,
parsed response, retained stderr, and status. A status of
"success_nonzero_exit" means the helper reported success but its
process exited non-zero; the output was kept and validated as usual.
empty_extent is true when empty_extent="nodata" was requested and
an all-nodata GeoTIFF was written for a confirmed empty window.
Isolated serial native sampling¶
RasTerrainMod.run_serial_native_sampling(operation) runs an eager callback on
one CLR ThreadPool worker and returns (result, execution_evidence). Use it only
inside a caller-owned fresh Windows or Wine process without other native/CLR
work. Exhaust point iterators inside the callback; do not return a lazy iterator
or await separately queued CLR work. Calls cannot be concurrent or nested.
The helper selects one already-available processor through the public process
API, lowers the public CLR worker and completion-port limits to one, verifies
both controls, and dispatches the callback onto that sole pool worker. Native
nested Parallel.For work then cannot obtain a second pool worker. No HEC private
cache, coordinates, source records, profile tolerance, cell size or obstruction
parameter is changed. Runtime limitations fail before the callback is invoked.
Affinity and original minimum/maximum thread counts are restored and read back
on success or exception; restoration failure cannot yield a successful result.
Execution evidence records the mode single-clr-pool-worker-v1, original and
sampling processor-affinity masks, reported processor count, original minimum
and maximum thread limits, the sampling minimum and maximum [1, 1], pool dispatch and
runtime restoration. The helper writes no artifacts. Units, CRS, mutation policy
and artifacts remain those of the callback. The caller retains this evidence.
The CLR may reject a requested thread limit; actual return values and readback are required, not a presumed one-thread environment. See the public ThreadPool limit contract and default Parallel scheduler behavior. Source-parent first-profile controls under the qualified HEC-RAS 6.6 Wine runtime crashed in native parallel HDF reads under the ordinary execution mode and returned finite nonempty profiles under the verified serial mode. These controls qualify the execution experiment; they do not establish complete-support, corpus, hydraulic mesh or engineering acceptance.