raster¶
Raster utilities for HEC-RAS mesh rendering and export workflows.
- rivia.geo.raster.rasterize_results(variable, cell_wse, cell_min_elevation, face_min_elevation, face_cell_indexes, cell_face_info, cell_face_values, face_facepoint_indexes, fp_coords, face_normals, fp_face_info, fp_face_values, cell_polygons, face_normal_velocity=None, output_path=None, *, cell_centers=None, cell_surface_area=None, reference_raster=None, cell_size=None, crs=None, nodata=-9999.0, render_mode='sloping', use_depth_weights=False, shallow_to_flat=False, depth_threshold=0.001, tight_extent=True, perimeter=None, use_numba=None)[source]¶
Rasterize HEC-RAS 2D mesh results using the RASMapper-exact algorithm.
Implements the pixel-perfect pipeline reverse-engineered from
RasMapperLib/(decompiled C# source, HEC-RAS 6.6). Produces output matching RASMapper’s"Horizontal","Sloping Cell Corners", and"Sloping Cell Corners + Face Centers"render modes.Pipeline summary¶
water_surface / depth — horizontal (
render_mode="horizontal")build_cell_id_raster— scan-line rasterize wet cell polygons (Numba, mirrorsRasterizePolygon.ComputeCells).(pixel loop) — write
cell_wsedirectly; every pixel in a cell gets the same flat value.
water_surface / depth — sloping (
render_mode="sloping")Matches RasMapperLib
SetSlopingRenderingMode()(SharedData.cs:1778):CellStencilMethod.JustFacepoints+ShallowBehavior.None. GUI label: “Sloping (Cell Corners)”. The “Shallow Water reduces to Horizontal” checkbox is a sub-option of WithFaces only and does not apply to this mode.A.
compute_face_wss— hydraulic connectivity (face_connected), per-face WSE values (face_value_a,face_value_b), and full connection classification (face_hconn, one of theHC_*constants).B.
compute_facepoint_wse— planar regression fitting a plane through the face midpoint WSE samples; the interceptcat each facepoint is the corner WSE.4a.
build_cell_id_raster— scan-line rasterize wet cell polygons.4b.
sample_terrain_at_facepoints— terrain elevation at facepoints for depth rebalancing (only when a DEM is supplied).4c.
rasterize_rasmap— per-pixel barycentric interpolation of the facepoint WSE values within each cell’s triangles (with_faces=False,shallow_to_flat=False).water_surface / depth — hybrid (
render_mode="hybrid")Matches RasMapperLib
WithFacespath. Same steps asslopingbut callsrasterize_rasmapwithwith_faces=True;use_depth_weightsandshallow_to_flatare user-configurable.velocity / velocity_vector — sloping / hybrid
A.
compute_face_wss— hydraulic connectivity +face_hconn(same as WSE pipeline).2.
reconstruct_face_velocities— C-stencil least-squares reconstruction of full(Vx, Vy)at each face from the stored face-normal velocity scalar.3.
compute_facepoint_velocities— inverse-face-length weighted averaging of face velocity vectors to facepoints.3.5.
replace_face_velocities_sloped— replace each face velocity with the average of its two endpoint facepoint velocities.4a.
build_cell_id_raster— scan-line rasterize wet cell polygons.4c.
rasterize_rasmap— per-pixel barycentric interpolation of facepoint velocity vectors; speed magnitudesqrt(Vx²+Vy²)computed per pixel."velocity"returns the speed band only;"velocity_vector"returns all four bands.velocity / velocity_vector — horizontal (
render_mode="horizontal")RASMapper uses its stencil pipeline (
Render2D_8Stencil) for velocity even in horizontal mode whenever cells are large relative to the pixel size (threshold =pixel_size² × 5,MeshFV2D.csline 1431). For typical HEC-RAS 2D meshes all cells exceed this threshold, so this implementation routes horizontal-velocity requests through the same sloping stencil pipeline (Steps A, 2, 3, 3.5, 4) as"sloping"mode.shallow_to_flatis alwaysFalsefor this route. WSE and depth still use the flat per-cell paint path.- type variable:
Literal[‘wse’, ‘water_surface’, ‘depth’, ‘velocity’, ‘velocity_vector’]
- param variable:
"wse"/"water_surface"— water-surface elevation (aliases)."depth"— water depth (WSE minus terrain); requires reference_raster (DEM)."velocity"— 1-band speed rastersqrt(Vx²+Vy²); requires face_normal_velocity."velocity_vector"— 4-band velocity raster[Vx, Vy, speed, direction_deg](bands 1–4); requires face_normal_velocity.direction_degis degrees clockwise from north.- type cell_wse:
np.ndarray
- param cell_wse:
(n_cells,)water-surface elevation per cell.- type cell_min_elevation:
np.ndarray
- param cell_min_elevation:
(n_cells + n_ghost,)minimum bed elevation per cell including ghost (virtual boundary) cell rows. Must be the full unsliced array (cell_min_elevationreturns only real cells — pass the raw HDF dataset or append ghost rows). Ghost rows haveNaNin HEC-RAS output. The extra rows are required becausecompute_face_wss()indexes into this array usingface_cell_indexeswhich contains ghost cell indices on the cellB side of perimeter faces.- type face_min_elevation:
np.ndarray
- param face_min_elevation:
(n_faces,)minimum bed elevation at each face (face_min_elevation).- type face_cell_indexes:
np.ndarray
- param face_cell_indexes:
(n_faces, 2)—[cellA, cellB](face_cell_indexes).- type cell_face_info:
np.ndarray
- param cell_face_info:
(n_cells, 2)[start, count](first element ofcell_face_infotuple).- type cell_face_values:
np.ndarray
- param cell_face_values:
(total, 2)[face_idx, orientation](second element ofcell_face_infotuple).- type face_facepoint_indexes:
np.ndarray
- param face_facepoint_indexes:
(n_faces, 2)(face_facepoint_indexes).- type fp_coords:
np.ndarray
- param fp_coords:
(n_fp, 2)(facepoint_coordinates).- type face_normals:
np.ndarray
- param face_normals:
(n_faces, 3)[nx, ny, length](face_normals). Columns 0–1 are used as unit normal vectors; column 2 as face lengths.- type fp_face_info:
np.ndarray
- param fp_face_info:
(n_fp, 2)angle-sorted CSR start/count fromfacepoint_face_orientation.- type fp_face_values:
np.ndarray
- param fp_face_values:
(total, 2)angle-sorted[face_idx, orientation]fromfacepoint_face_orientation.- type cell_polygons:
list[np.ndarray]
- param cell_polygons:
Per-cell polygon vertex arrays from
cell_polygons.- type face_normal_velocity:
np.ndarray | None
- param face_normal_velocity:
(n_faces,)signed face-normal velocity scalars. Required forvariable="velocity".- type output_path:
str | Path | None
- param output_path:
Destination
.tiffile path.Nonereturns an open in-memoryrasterio.DatasetReader; the caller must close it.- type cell_centers:
np.ndarray | None
- param cell_centers:
(n_cells, 2)cell-centre XY coordinates (cell_centers). When provided, face application points for the PlanarRegressionZ in Step B are computed as the intersection of the cell-centre-to-cell-centre line with each face chord (the RASMapper-exactGetFaceMidSidealgorithm). WhenNonethe chord midpoint of the two endpoint facepoints is used instead, which is adequate for orthogonal meshes.- type cell_surface_area:
np.ndarray | None
- param cell_surface_area:
(n_cells,)plan-view cell areas in model area units (cell_surface_area). Used to split cells into “flat” (area ≤pixel_size² × 5) and “sloping” groups, matching RASMapper’sSplitCellsOnThreshold/PixelRenderingCutoff = 5logic. WhenNoneall cells are treated as sloping (current behaviour, correct for typical meshes but incorrect for fine-resolution refinement areas such as channels). Only relevant for velocity variables.- type reference_raster:
str | Path | None
- param reference_raster:
Existing GeoTIFF whose transform and CRS are inherited. Also used as the terrain DEM for depth computation and per-pixel wet/dry masking. Mutually exclusive with cell_size.
- type cell_size:
float | None
- param cell_size:
Output pixel size in model coordinate units. Used when no reference_raster is provided; the grid origin is derived from perimeter (if given) or from the facepoint bounding box.
- type crs:
Any | None
- param crs:
Output CRS. Inherited from reference_raster when
None.- type nodata:
float
- param nodata:
Fill value for dry / out-of-domain pixels.
- type render_mode:
Literal[‘horizontal’, ‘sloping’, ‘hybrid’]
- param render_mode:
"sloping"(default) — RASMapper “Sloping (Cell Corners)” pipeline; N-point barycentric interpolation using corner facepoints only (with_faces=False,shallow_to_flat=False). MatchesSetSlopingRenderingMode()(SharedData.cs:1778) andstore_map(render_mode="sloping")."hybrid"— RASMapper “Sloping Cell Corners + Face Centers” (with_faces=True); more accurate near cell edges.use_depth_weightsandshallow_to_flatare honoured as supplied. Matchesstore_map(render_mode="hybrid")."horizontal"— flat per-cell value painted over each owned pixel; facepoint interpolation is skipped entirely. Matchesstore_map(render_mode="horizontal").- type use_depth_weights:
bool
- param use_depth_weights:
When
True, face weights in thehybridstencil are proportional to water depth at each face. Ignored (forcedFalse) for"sloping"and"horizontal"modes. Requires reference_raster whenTrue.- type shallow_to_flat:
bool
- param shallow_to_flat:
When
True, cells with no hydraulically-connected faces are rendered flat (horizontal). Ignored for"horizontal"and"sloping"modes (forcedFalse— “Shallow Water reduces to Horizontal” is a WithFaces-only sub-option in the RASMapper GUI). Only user-configurable for"hybrid"mode.- type depth_threshold:
float
- param depth_threshold:
Minimum depth for a pixel to be considered wet (default
0.001). MatchesRASResults.MinWSPlotTolerance.- type tight_extent:
bool
- param tight_extent:
When
True(default), pixels outside perimeter are set to nodata. Has no effect when perimeter isNone.- type perimeter:
np.ndarray | None
- param perimeter:
(n_pts, 2)boundary polygon used for extent and clipping. Passperimeterhere. WhenNonethe bounding box of fp_coords is used for the grid extent and no polygon clipping is applied.- type use_numba:
bool | None
- param use_numba:
True— require Numba JIT (raisesImportErrorif absent).False— force pure-Python fallback.None(default) — use Numba if available, otherwise fall back silently. (Numba path not yet implemented; reserved for future.)- rtype:
Path | rasterio.io.DatasetReader
- returns:
Path – Written GeoTIFF path when output_path is given.
rasterio.io.DatasetReader – Open in-memory dataset when output_path is
None.
- raises ImportError:
If
rasterioorshapelyare not installed.- raises ValueError:
If
variable="depth"and reference_raster isNone. Ifvariable="velocity"and face_normal_velocity isNone. Ifuse_depth_weights=Trueand reference_raster isNone. If both reference_raster and cell_size areNone.
- Parameters:
variable (Literal['wse', 'water_surface', 'depth', 'velocity', 'velocity_vector'])
cell_wse (np.ndarray)
cell_min_elevation (np.ndarray)
face_min_elevation (np.ndarray)
face_cell_indexes (np.ndarray)
cell_face_info (np.ndarray)
cell_face_values (np.ndarray)
face_facepoint_indexes (np.ndarray)
fp_coords (np.ndarray)
face_normals (np.ndarray)
fp_face_info (np.ndarray)
fp_face_values (np.ndarray)
cell_polygons (list[np.ndarray])
face_normal_velocity (np.ndarray | None)
output_path (str | Path | None)
cell_centers (np.ndarray | None)
cell_surface_area (np.ndarray | None)
reference_raster (str | Path | None)
cell_size (float | None)
crs (Any | None)
nodata (float)
render_mode (Literal['horizontal', 'sloping', 'hybrid'])
use_depth_weights (bool)
shallow_to_flat (bool)
depth_threshold (float)
tight_extent (bool)
perimeter (np.ndarray | None)
use_numba (bool | None)
- Return type:
Path | rasterio.io.DatasetReader