Skip to content

Meshing: Generation, Diagnostics and Repair

GeomMesh authors computation points and invokes the native RASMapper mesh engine. Import it from ras_commander.geom (also exported at package root). Use HdfMesh to inspect meshes; use RasCmdr to compute hydraulic plans.

For HEC-RAS 6.6 and later, generate(min_face_length_ratio=...) starts at the requested positive, finite ratio, then escalates to larger values in the repair ladder if needed. A successful generation persists the used ratio in geometry text and the RASMapper workspace. Before 6.6, the mesh constructor does not accept this ratio.

MeshResult.ok reports mesh authoring success. Validate the saved geometry with native preprocessing through GeomPreprocessor.run_geometry_preprocessor() or RasCmdr.compute_plan(force_geompre=True) before accepting it for computation. Passing an in-memory mesh check at one or several ratios does not establish native preprocessing success.

Stage API Input → output
Bootstrap points generate_computation_points Authored perimeter text and spacing -> regular-grid computation points in text; no existing HDF required
Explicit points write_computation_points Authored perimeter text and supplied XY coordinates -> validated native text seed block; no native DLL or existing HDF required
Compile geometry RasCmdr preprocessing Referencing project/plan and authored geometry -> native compiled HDF workspace
Author controls Breakline/refinement methods Names, spacing and polygons/flowlines → updated text or compiled-HDF controls, as specified per method
Check domain audit_domain_containment Selected 2D area and cell spacing → DomainContainmentResult
Regenerate mesh generate, generate_all Current compiled HDF, domain, breaklines/refinements and spacing -> MeshResult records and updated computation points
Build properties compute_property_tables Mesh and terrain/classification associations → native property tables; Boolean result
Check boundary conflicts detect_bc_conflicts, fix_bc_conflicts Compiled perimeter faces and BC lines → conflicts or BCFixResult. fix_bc_conflicts reads and writes only the old per-area Geometry/2D Flow Areas/<area>/BC Lines layout, so on HEC-RAS 6.x/7.x geometry HDFs (Geometry/Boundary Condition Lines) it finds no conflicts and changes nothing; use detect_bc_conflicts for detection

write_computation_points preserves UTF-8 or legacy CP1252 encoding, including non-ASCII area names. Undecodable text is refused before backup or replacement. Unrelated record contents are preserved; model writes use CRLF line endings.

flowchart LR
    A[Geometry text and spatial inputs] --> S[Bootstrap points if no mesh exists]
    S --> B[Native geometry preprocessing]
    B --> C[Author and audit mesh controls]
    C --> D[Generate computation points and mesh]
    D --> E[Review repairs and associations]
    E --> F[Build property tables]
    F --> G[Prepare and compute hydraulic plan]

generate_computation_points() creates a breakline-unaware regular grid from the authored perimeter. HEC-RAS preprocessing then builds the full mesh. GeomMesh.compile_geometry() is a disabled compatibility shim and never returns successfully; it is documented below only for compatibility. RASMapper completion of an existing HDF is not text-to-HDF compilation.

Retain an exact subset of parent cells

Use GeomMesh.plan_cell_subset() when a child domain is the union of explicit physical parent cells and must retain their faces and vertices. The parent must be a geometry-only HDF with complete native topology; a plan/results HDF is rejected. Prepare an owned child text/HDF pair with one matching area, consistent CRS, and the selected union as its perimeter. Cell IDs are zero-based physical IDs from HdfMesh; ghost cells, duplicate IDs, holes, disconnected components, and boundary pinch points are rejected. The API never expands the selection. Native completion can stamp the owned geometry target HEC-RAS Results. Planning accepts that target only if its sole root group is Geometry. The parent source follows the same rule: HEC-RAS Geometry, or a natively compiled HEC-RAS Results stamp whose sole root group is Geometry. Plan HDFs and any file holding result data are rejected.

Python
from ras_commander.geom import GeomMesh, GeomPreprocessor
from ras_commander import RasPreprocess

subset = GeomMesh.plan_cell_subset(
    "source/Model.g01.hdf", "review-copy/Model.g02",
    parent_cell_ids=selected_ids, mesh_name="Area",
)
review_record = subset.to_dict()  # ras-mesh-cell-subset/v1; no writes
# Review the IDs, source hashes, CRS and counts before applying.
# review_project is initialized for the owned copy and selected HEC-RAS 6.6;
# plan 08 references g02. Reuse that exact runtime for both native phases.
written = GeomMesh.apply_cell_subset(subset, ras_object=review_project)
assert written.ok and written.operation == "cell_subset"

geometry = GeomPreprocessor.run_geometry_preprocessor(
    "08", ras_object=review_project, require_complete_products=True,
)
assert geometry.success
assert GeomMesh.validate_cell_subset(subset)["topology_exact"]
event = RasPreprocess.preprocess_plan(
    "08", ras_object=review_project, clear_existing=True,
)
assert event.success
assert GeomMesh.validate_cell_subset(subset)["topology_exact"]

Planning binds source HDF, child text and child HDF hashes. Applying refuses stale inputs, preserves physical cell coordinates and face polylines, reindexes native incidence tables, and creates one ghost cell per new perimeter face. HEC-RAS 6.6 or 6.4.1 serializes the mesh in an isolated worker. The text perimeter is written from the exact native ring with the existing 16-character formatter. Completion checks can bind the full-precision ring only when that formatter reproduces the authored polygon exactly; the bound ring must remain unchanged and all mesh segments must remain inside it. This adds no containment tolerance.

With ras_object, application uses that project's exact ras_exe_path. An optional hecras_dir must identify the same installation; conflicting paths are rejected. Without an explicit project, the active global project's runtime is retained. The declared hecras_version="6.6" is discovered only when neither project selects a runtime. The caller controls serialization timeout in seconds (default 1800); an expired worker raises RuntimeError and preserves the inputs. The native worker verifies the selected executable's file version: 6.6, or exactly 6.4.1 (file version 6.4.0.1; 6.4.0 is refused). 6.4.1 was qualified on the FEMA eBFE Salt Draw delivery, a 6.4.1 model: a 2,592-cell cut of the delivered mesh serialized, preprocessed and ran in 6.4.1, and reproduced the parent's maximum WSE to 0.017 ft at the 95th percentile. Cutting in the model's own version avoids re-meshing a delivered mesh that a newer version rejects. Returned cell_subset.native_serialization records the install directory, executable file version, executable SHA-256, and RasMapperLib DLL SHA-256.

Native staging resolves associated sidecars against the original geometry folder, retains calibration overrides, then restores the original relative association spelling. Inherited hydraulic property tables are invalidated for fresh native computation. Two unique sibling backups support exception rollback if either file replacement fails. Exclusive access is required: the text/HDF pair is not crash atomic. Restore both backups after an interrupted replacement.

MeshResult.ok here means topology writing completed. Retain the strict geometry receipt, fresh Event Conditions completion, independent HdfMesh cell/face readback, boundary attachments, and spatial review before accepting a child for simulation. The library does not produce an engineering approval or a review map.

For an already planned breakout, pass parent_cell_ids=selected_ids to RasBreakout2D.prepare_cloned_geometry() with refresh_method="rasexe", remesh=False, and require_complete_products=True. This applies the exact subset before the first native completion pass and validates source-bound face coordinates, endpoints, cell ownership, counts and reciprocal incidence again after preprocessing. Evidence is retained in cell_subset.post_preprocess_validation. Native remeshing from the same seeds and perimeter cannot pass this gate if it changes the exact topology. It cannot be combined with computation_points or grid anchoring.

validate_cell_subset() returns ras-mesh-cell-subset-validation/v1 evidence only on success; failed identity, array, count or incidence checks raise RuntimeError. Both source and child hashes must remain stable across the read. Cell vertices may rotate/reverse or change padding only when their edges still follow the same incident faces. Packed cell/face memberships may reorder when their sets and orientations remain reciprocal. Face coordinates, endpoints, cell ownership, polylines, normals/lengths and perimeter flags remain unchanged.

Validation field Type Meaning
schema, status string ras-mesh-cell-subset-validation/v1, pass
source_sha256 string Immutable planned parent geometry identity
geometry_hdf_sha256 string Stable child HDF bytes inspected by this validation
physical_cells, total_cells integer Physical and physical-plus-boundary-ghost counts
faces, facepoints integer Exact selected face and vertex counts
topology_exact boolean Always true in returned evidence; failed checks raise
hydraulic_acceptance string Always not_established

The opt-in tests/test_mesh_cell_subset_native.py test copies a prepared real project and checks strict Geometry, Event completion and topology after each native phase. It skips cleanly without Windows/Wine, HEC-RAS 6.6, pythonnet, or the explicitly configured RAS_EXACT_SUBSET_NATIVE_CASE fixture.

MeshCellSubsetPlan dataclass

Read-only plan for copying exact physical cells into an owned geometry.

Coordinates retain the source horizontal CRS and units. The selection is explicit and sorted; it is never expanded, repaired or reseeded. Hashes bind both inputs to application. This plan establishes no native completion or hydraulic acceptance.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class MeshCellSubsetPlan:
    """Read-only plan for copying exact physical cells into an owned geometry.

    Coordinates retain the source horizontal CRS and units. The selection is
    explicit and sorted; it is never expanded, repaired or reseeded. Hashes
    bind both inputs to application. This plan establishes no native completion
    or hydraulic acceptance.
    """

    source_geometry_hdf: str
    geometry_path: str
    mesh_name: str
    parent_cell_ids: Tuple[int, ...]
    source_sha256: str
    geometry_sha256: str
    geometry_hdf_sha256: str
    face_count: int
    facepoint_count: int
    boundary_tolerance: float
    crs_wkt: str

    def to_dict(self) -> Dict[str, Any]:
        """Return the planned source identities and topology counts."""
        return {
            "schema": "ras-mesh-cell-subset/v1",
            "source_geometry_hdf": self.source_geometry_hdf,
            "geometry_path": self.geometry_path,
            "mesh_name": self.mesh_name,
            "parent_cell_ids": list(self.parent_cell_ids),
            "source_sha256": self.source_sha256,
            "geometry_sha256": self.geometry_sha256,
            "geometry_hdf_sha256": self.geometry_hdf_sha256,
            "physical_cell_count": len(self.parent_cell_ids),
            "face_count": self.face_count,
            "facepoint_count": self.facepoint_count,
            "boundary_tolerance": self.boundary_tolerance,
            "horizontal_crs": self.crs_wkt,
            "native_completion": "not_run",
            "hydraulic_acceptance": "not_established",
        }

to_dict

Python
to_dict() -> Dict[str, Any]

Return the planned source identities and topology counts.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return the planned source identities and topology counts."""
    return {
        "schema": "ras-mesh-cell-subset/v1",
        "source_geometry_hdf": self.source_geometry_hdf,
        "geometry_path": self.geometry_path,
        "mesh_name": self.mesh_name,
        "parent_cell_ids": list(self.parent_cell_ids),
        "source_sha256": self.source_sha256,
        "geometry_sha256": self.geometry_sha256,
        "geometry_hdf_sha256": self.geometry_hdf_sha256,
        "physical_cell_count": len(self.parent_cell_ids),
        "face_count": self.face_count,
        "facepoint_count": self.facepoint_count,
        "boundary_tolerance": self.boundary_tolerance,
        "horizontal_crs": self.crs_wkt,
        "native_completion": "not_run",
        "hydraulic_acceptance": "not_established",
    }

Diagnose before repairing

Symptom or question Inspection Supported next step
Missing mesh arrays or older HDF layout HdfMesh.diagnose_mesh_layout() Inspect capability status and source paths; preprocess a copy when topology is absent. A recovered perimeter does not supply face connectivity.
Omitted or ambiguous cell polygons HdfMesh.diagnose_mesh_cell_polygons(); get_mesh_cell_polygons(strict=True) Review native cell/face IDs. The reader does not repair topology or substitute a convex hull.
Breakline or structure outside the domain; invalid refinement polygon GeomMesh.audit_domain_containment() Correct the source controls or perimeter and recompile through ras-commander before regeneration.
BC lines near the same perimeter face GeomMesh.detect_bc_conflicts(); fix_bc_conflicts(dry_run=True) Review candidate overlaps; supported repair trims BC endpoints in the copied HDF. detect_bc_conflicts() reads Geometry/Boundary Condition Lines and the ghost-cell perimeter faces HEC-RAS writes; fix_bc_conflicts() still reads per-area BC Lines groups, which HEC-RAS does not write, so it finds nothing to repair in HEC-RAS output.
Native generation fails GeomMesh.generate() result or raised exception Review the bounded retry/repair evidence below; persisted perimeter changes have a separate failure contract.
Extreme areas, aspect ratios, or face velocities RasCheck.check_mesh_quality(plan_hdf, geom_hdf) Inspect messages and source outputs; these checks do not select an acceptable mesh resolution.
Unusual subgrid sampling settings RasCheck.check_subgrid_sampling(geom_file) Review geometry-text settings against terrain resolution and the intended study.

The BC conflict detector uses a geometric proximity buffer of 0.01 * cell_size. It is different from HdfMesh.get_mesh_perimeter_faces(), which reads native BC ownership. Use both when association evidence matters. BC repair prefers a Normal Depth endpoint, otherwise the longer BC. It writes HDF coordinates in place, does not create a backup or update geometry text, and does not prove that native associations or a later preprocessing run will preserve the edit. Keep a project copy, inspect the trims, and recheck native ownership before use.

RasCheck.check_mesh_quality() currently compares native areas and velocities with thresholds named in square feet and feet per second, without converting SI values. It uses bounding-box aspect ratios, aggregates returned cells under the first mesh name, and catches some reader failures. Its informational "no issues" result is not proof that every dataset was inspected. Check layout and polygon completeness first; interpret thresholds in the actual source units. General connectivity validation is not implemented by this check.

Python
from pathlib import Path
from ras_commander import HdfMesh, GeomMesh

# Existing compiled geometry; inspection does not alter it.
geom_hdf = Path("review-copy/Model.g01.hdf")
layout = HdfMesh.diagnose_mesh_layout(geom_hdf)
polygon_issues = HdfMesh.diagnose_mesh_cell_polygons(geom_hdf)
print(layout)
print(polygon_issues)

# Set spacing from this model's geometry, in project length units.
cell_size = 100.0
conflicts = GeomMesh.detect_bc_conflicts(geom_hdf, cell_size)
preview = GeomMesh.fix_bc_conflicts(geom_hdf, cell_size, dry_run=True)
print(preview.conflicts_found, preview.modified_hdf)

The dry run reports candidates without computing a repair: conflicts_fixed remains zero, and every detected conflict is placed in unresolvable. Therefore BCFixResult.ok is false when a dry run finds conflicts. These entries are unattempted candidates, not evidence that repair is impossible. Inspect conflicts_found, unresolvable, and modified_hdf explicitly.

Repair and its dry run use a proximity buffer of max(0.1, 0.01 * cell_size) in project length units. The detection-only method uses 0.01 * cell_size without that minimum, so the two methods can report different candidate counts for small cells.

Repair on a project copy

The following fragment assumes an initialized review_project for a disposable copy, a plan referencing geometry 01, and a current compiled HDF. Select the installed runtime explicitly; these values must come from the actual project.

Python
from ras_commander import GeomMesh

result = GeomMesh.generate(
    "01",
    ras_object=review_project,
    hecras_dir=installed_hecras_directory,
    recompile_via_rasexe=True,
)
print(result.status, result.error_message)
print(result.fixes_applied, result.perimeter_repairs)

Review text/HDF changes, geometry associations, diagnostics, and final cell properties before computing a hydraulic plan. A completed mesh is not a hydraulic validation result.

Diagnostic method reference

A class for handling mesh-related operations on HEC-RAS HDF files.

This class provides methods to extract and analyze mesh data from HEC-RAS HDF files, including mesh area names, mesh areas, cell polygons, cell points, cell faces, and 2D flow area attributes.

Methods in this class are designed to work with the mesh geometry data stored in HEC-RAS HDF files, providing functionality to retrieve and process various aspects of the 2D flow areas and their associated mesh structures.

Note: This class relies on HdfBase and HdfUtils for some underlying operations.

diagnose_mesh_layout staticmethod

Python
diagnose_mesh_layout(hdf_path: Path, program_version: Optional[str] = None) -> pd.DataFrame

Inspect mesh-layout capabilities without modifying the HDF.

Parameters

hdf_path : Path Geometry or plan HDF containing the Geometry/2D Flow Areas group. program_version : str, optional Program version read from the companion plan or geometry text file. For example, HEC-RAS 6.2 commonly stores "6.20".

Returns

pandas.DataFrame One row per 2D flow area. Capability status columns use standard, collection_fallback, not_present, malformed, or read_error. Dataset-path columns identify the evidence used for each decision.

Notes

Collection-level Cell Info and Cell Points are reported as evidence only. They are never promoted to face connectivity or cell polygon topology.

Source code in ras_commander/hdf/HdfMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='geom_hdf')
def diagnose_mesh_layout(
    hdf_path: Path,
    program_version: Optional[str] = None,
) -> pd.DataFrame:
    """Inspect mesh-layout capabilities without modifying the HDF.

    Parameters
    ----------
    hdf_path : Path
        Geometry or plan HDF containing the ``Geometry/2D Flow Areas`` group.
    program_version : str, optional
        Program version read from the companion plan or geometry text file.
        For example, HEC-RAS 6.2 commonly stores ``"6.20"``.

    Returns
    -------
    pandas.DataFrame
        One row per 2D flow area. Capability status columns use
        ``standard``, ``collection_fallback``, ``not_present``,
        ``malformed``, or ``read_error``. Dataset-path columns identify the
        evidence used for each decision.

    Notes
    -----
    Collection-level ``Cell Info`` and ``Cell Points`` are reported as
    evidence only. They are never promoted to face connectivity or cell
    polygon topology.
    """
    base = "Geometry/2D Flow Areas"
    records: List[Dict[str, Any]] = []
    try:
        with h5py.File(hdf_path, "r") as hdf_file:
            geometry_group = hdf_file.get("Geometry")
            hdf_file_version = _decode_hdf_scalar(
                read_attr(hdf_file, "File Version", None)
            )
            geometry_version = _decode_hdf_scalar(
                read_attr(geometry_group, "Geometry Version", None)
                if geometry_group is not None
                else None
            )
            complete_geometry = _decode_hdf_scalar(
                read_attr(geometry_group, "Complete Geometry", None)
                if geometry_group is not None
                else None
            )
            common = {
                "hdf_file_version": hdf_file_version,
                "geometry_version": geometry_version,
                "complete_geometry": complete_geometry,
                "program_version": program_version,
            }

            if base not in hdf_file:
                return pd.DataFrame(
                    [{
                        **common,
                        "mesh_name": None,
                        "layout": "not_present",
                        "area_names_status": "not_present",
                        "area_names_paths": f"{base}/Attributes",
                        "perimeter_status": "not_present",
                        "perimeter_paths": "",
                        "cell_centers_status": "not_present",
                        "cell_centers_paths": "",
                        "face_topology_status": "not_present",
                        "face_topology_paths": "",
                        "cell_polygons_status": "not_present",
                        "cell_polygons_paths": "",
                        "reason_codes": "no_2d_flow_areas_group",
                        "compatibility_warning": None,
                    }]
                )

            group = hdf_file[base]
            attributes_path = f"{base}/" + ("Attributes" if "Attributes" in group else "Names")
            mesh_names = HdfMesh._mesh_area_names(hdf_file)

            collection_paths = [
                f"{base}/Polygon Info",
                f"{base}/Polygon Parts",
                f"{base}/Polygon Points",
            ]
            collection_status = "not_present"
            collection_reason = None
            if "Polygon Info" in group or "Polygon Points" in group:
                try:
                    _strict_collection_perimeters(group, mesh_names)
                    collection_status = "collection_fallback"
                except (KeyError, _MeshLayoutError) as exc:
                    collection_status = "malformed"
                    collection_reason = str(exc)

            version_text = " ".join(
                str(value or "")
                for value in (program_version, hdf_file_version, geometry_version)
            ).lower()
            legacy_signature = (
                str(program_version or "").strip() == "6.20"
                or "hec-ras 6.3 august 2022" in version_text
                or str(geometry_version or "").strip() == "1.0.18"
            )

            for mesh_name in mesh_names:
                mesh_base = f"{base}/{mesh_name}"
                reasons = []
                perimeter_path = f"{mesh_base}/Perimeter"
                if perimeter_path in hdf_file:
                    perimeter_status = "standard"
                    perimeter_paths = perimeter_path
                else:
                    perimeter_status = collection_status
                    perimeter_paths = ";".join(collection_paths)
                    if collection_reason:
                        reasons.append(f"collection_perimeter:{collection_reason}")

                center_path = f"{mesh_base}/Cells Center Coordinate"
                if center_path in hdf_file:
                    center_status = "standard"
                    center_paths = center_path
                else:
                    center_status = "not_present"
                    evidence = [
                        f"{base}/Cell Info",
                        f"{base}/Cell Points",
                    ]
                    center_paths = ";".join(
                        path for path in evidence if path in hdf_file
                    )
                    reasons.append("named_cell_centers_not_present")

                face_names = (
                    "Faces FacePoint Indexes",
                    "FacePoints Coordinate",
                    "Faces Perimeter Info",
                    "Faces Perimeter Values",
                )
                face_paths = [f"{mesh_base}/{name}" for name in face_names]
                face_present = [path in hdf_file for path in face_paths]
                if all(face_present):
                    face_status = "standard"
                elif any(face_present):
                    face_status = "malformed"
                    reasons.append("partial_face_topology")
                else:
                    face_status = "not_present"
                    reasons.append("face_topology_not_present")

                cell_names = (
                    "Cells Face and Orientation Info",
                    "Cells Face and Orientation Values",
                )
                cell_paths = [f"{mesh_base}/{name}" for name in cell_names]
                cell_present = [path in hdf_file for path in cell_paths]
                if face_status == "standard" and all(cell_present):
                    cell_polygon_status = "standard"
                elif any(cell_present) or face_status == "malformed":
                    cell_polygon_status = "malformed"
                    reasons.append("partial_cell_polygon_topology")
                else:
                    cell_polygon_status = "not_present"
                    reasons.append("cell_polygon_topology_not_present")

                statuses = (
                    perimeter_status,
                    center_status,
                    face_status,
                    cell_polygon_status,
                )
                if "malformed" in statuses:
                    layout = "malformed"
                elif perimeter_status == "collection_fallback":
                    layout = "collection_fallback"
                elif perimeter_status == "standard":
                    layout = "standard"
                else:
                    layout = "not_present"

                compatibility_warning = None
                if legacy_signature and face_status != "standard":
                    compatibility_warning = (
                        "This HEC-RAS 6.2/6.3-era geometry reports 2D data "
                        "but omits named-area face topology. The perimeter "
                        "may be recoverable; faces and cell polygons are not."
                    )
                    logger.warning("%s Mesh: %s", compatibility_warning, mesh_name)

                records.append({
                    **common,
                    "mesh_name": mesh_name,
                    "layout": layout,
                    "area_names_status": "standard",
                    "area_names_paths": attributes_path,
                    "perimeter_status": perimeter_status,
                    "perimeter_paths": perimeter_paths,
                    "cell_centers_status": center_status,
                    "cell_centers_paths": center_paths,
                    "face_topology_status": face_status,
                    "face_topology_paths": ";".join(face_paths),
                    "cell_polygons_status": cell_polygon_status,
                    "cell_polygons_paths": ";".join(cell_paths),
                    "reason_codes": ";".join(dict.fromkeys(reasons)),
                    "compatibility_warning": compatibility_warning,
                })
    except Exception as exc:
        reraise_required(exc)
        logger.error("Error diagnosing mesh layout from %s: %s", hdf_path, exc)
        return pd.DataFrame([{
            "hdf_file_version": None,
            "geometry_version": None,
            "complete_geometry": None,
            "program_version": program_version,
            "mesh_name": None,
            "layout": "read_error",
            "area_names_status": "read_error",
            "area_names_paths": f"{base}/Attributes",
            "perimeter_status": "read_error",
            "perimeter_paths": "",
            "cell_centers_status": "read_error",
            "cell_centers_paths": "",
            "face_topology_status": "read_error",
            "face_topology_paths": "",
            "cell_polygons_status": "read_error",
            "cell_polygons_paths": "",
            "reason_codes": str(exc),
            "compatibility_warning": None,
        }])
    return pd.DataFrame(records)

diagnose_mesh_cell_polygons staticmethod

Python
diagnose_mesh_cell_polygons(hdf_path: Path, *, engine: str = 'auto') -> pd.DataFrame

Return cells not reconstructed as exactly one polygon.

The result contains the native mesh_name and zero-based cell_id, face and polygon counts, a status and reason code, and the referenced face IDs. boundary_only rows identify validated native one- or two-face records and do not make strict reconstruction fail. omitted and ambiguous rows identify physical-cell problems; not_present and read_error distinguish unavailable or malformed topology from a clean reconstruction. An empty result means every named mesh supplied topology and every processed physical cell produced exactly one polygon.

engine is as in :meth:get_mesh_cell_polygons. engine="auto" falls back to the reference polygonizer on any native failure, and whenever the native records cannot be proven equal to the reference's, so its rows, statuses, reason codes and warnings are the reference ones. engine="native" (or RAS_COMMANDER_FAST_HDF=native) never falls back; there the native records can differ from the reference's as described under diagnostics in :meth:get_mesh_cell_polygons.

Source code in ras_commander/hdf/HdfMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='geom_hdf')
def diagnose_mesh_cell_polygons(hdf_path: Path, *, engine: str = "auto") -> pd.DataFrame:
    """Return cells not reconstructed as exactly one polygon.

    The result contains the native ``mesh_name`` and zero-based ``cell_id``,
    face and polygon counts, a status and reason code, and the referenced
    face IDs. ``boundary_only`` rows identify validated native one- or
    two-face records and do not make strict reconstruction fail. ``omitted``
    and ``ambiguous`` rows identify physical-cell problems;
    ``not_present`` and ``read_error`` distinguish unavailable or malformed
    topology from a clean reconstruction. An empty result means every
    named mesh supplied topology and every processed physical cell produced
    exactly one polygon.

    ``engine`` is as in :meth:`get_mesh_cell_polygons`. ``engine="auto"``
    falls back to the reference polygonizer on any native failure, and
    whenever the native records cannot be proven equal to the reference's,
    so its rows, statuses, reason codes and warnings are the reference
    ones. ``engine="native"`` (or ``RAS_COMMANDER_FAST_HDF=native``) never
    falls back; there the native records can differ from the reference's
    as described under ``diagnostics`` in :meth:`get_mesh_cell_polygons`.
    """
    polygons = HdfMesh.get_mesh_cell_polygons(
        hdf_path, strict=False, engine=engine, diagnostics=True)
    diagnostic_records = polygons.attrs.get("cell_polygon_diagnostics")
    columns = [
        "mesh_name",
        "cell_id",
        "face_count",
        "polygon_count",
        "status",
        "reason_code",
        "face_ids",
        "missing_face_ids",
    ]
    result = pd.DataFrame.from_records(
        () if diagnostic_records is None else diagnostic_records, columns=columns
    )
    return result

get_mesh_cell_polygons staticmethod

Python
get_mesh_cell_polygons(hdf_path: Path, *, strict: bool = False, engine: str = 'auto', threads: Optional[int] = None, diagnostics: bool = False) -> GeoDataFrame

Return 2D flow mesh cell polygons.

Parameters

hdf_path : Path Path to the HEC-RAS geometry HDF file. strict : bool, default False Raise :class:MeshCellPolygonError when a native cell produces no polygon or more than one polygon. The default preserves the legacy return behavior and emits a warning for omitted cells. engine : str, default "auto" "auto": native first, with the Python reference polygonizer on any native refusal or failure, so results and exceptions are the reference ones. "h5py": the reference polygonizer only. "native": native execution or :class:~ras_commander.fast_hdf.FastHdfError. threads : int, optional Maximum threads for native extraction and polygon construction. diagnostics : bool, default False Attach anomaly rows to result.attrs["cell_polygon_diagnostics"] as an equality-safe tuple of record dictionaries. Off by default (behaviour change from ras-commander 0.106.1, which always attached them); :meth:diagnose_mesh_cell_polygons returns them as a DataFrame. Native and Python diagnostics: with engine="auto" the records are always the Python reference's (native results are used only when every record is proven equal, else the Python polygonizer runs). With engine="native" (or RAS_COMMANDER_FAST_HDF=native) the native records are returned as produced and can differ: the engine labels a cell it did not assemble omitted/no_polygon only when it detected an invalid ring, otherwise boundary_only/insufficient_faces even if the cell has three or more faces; it never reports ambiguous/ multiple_polygons, invalid_face_span or missing_face_reference (the reference polygonizes the faces and can). The polygons themselves are unaffected.

Returns

GeoDataFrame A GeoDataFrame containing the 2D flow mesh cell polygons with columns: - mesh_name: str - Name of the 2D flow area - cell_id: int - Unique cell identifier (0-indexed) - geometry: Polygon - Cell polygon geometry constructed from face edges Returns an empty GeoDataFrame if no 2D areas exist or if there's an error.

Notes

Cell IDs are native, zero-based IDs within each mesh. The returned row index must not be treated as a complete or positional cell identifier. Use :meth:diagnose_mesh_cell_polygons or strict=True whenever an exhaustive physical-cell mask is required.

Source code in ras_commander/hdf/HdfMesh.py
Python
@staticmethod
@log_call
@standardize_input(file_type='geom_hdf')
def get_mesh_cell_polygons(
    hdf_path: Path,
    *,
    strict: bool = False,
    engine: str = "auto",
    threads: Optional[int] = None,
    diagnostics: bool = False,
) -> 'GeoDataFrame':
    """
    Return 2D flow mesh cell polygons.

    Parameters
    ----------
    hdf_path : Path
        Path to the HEC-RAS geometry HDF file.
    strict : bool, default False
        Raise :class:`MeshCellPolygonError` when a native cell produces no
        polygon or more than one polygon. The default preserves the legacy
        return behavior and emits a warning for omitted cells.
    engine : str, default "auto"
        ``"auto"``: native first, with the Python reference polygonizer on
        any native refusal or failure, so results and exceptions are the
        reference ones. ``"h5py"``: the reference polygonizer only.
        ``"native"``: native execution or
        :class:`~ras_commander.fast_hdf.FastHdfError`.
    threads : int, optional
        Maximum threads for native extraction and polygon construction.
    diagnostics : bool, default False
        Attach anomaly rows to ``result.attrs["cell_polygon_diagnostics"]``
        as an equality-safe tuple of record dictionaries. Off by default
        (behaviour change from ras-commander 0.106.1, which always attached
        them); :meth:`diagnose_mesh_cell_polygons` returns them as a
        DataFrame.
        Native and Python diagnostics: with ``engine="auto"`` the records
        are always the Python reference's (native results are used only
        when every record is proven equal, else the Python polygonizer
        runs). With ``engine="native"`` (or
        ``RAS_COMMANDER_FAST_HDF=native``) the native records are returned
        as produced and can differ: the engine labels a cell it did not
        assemble ``omitted``/``no_polygon`` only when it detected an invalid
        ring, otherwise ``boundary_only``/``insufficient_faces`` even if the
        cell has three or more faces; it never reports ``ambiguous``/
        ``multiple_polygons``, ``invalid_face_span`` or
        ``missing_face_reference`` (the reference polygonizes the faces
        and can). The polygons themselves are unaffected.

    Returns
    -------
    GeoDataFrame
        A GeoDataFrame containing the 2D flow mesh cell polygons with columns:
        - mesh_name: str - Name of the 2D flow area
        - cell_id: int - Unique cell identifier (0-indexed)
        - geometry: Polygon - Cell polygon geometry constructed from face edges
        Returns an empty GeoDataFrame if no 2D areas exist or if there's an error.

    Notes
    -----
    Cell IDs are native, zero-based IDs within each mesh. The returned row
    index must not be treated as a complete or positional cell identifier.
    Use :meth:`diagnose_mesh_cell_polygons` or ``strict=True`` whenever an
    exhaustive physical-cell mask is required.
    """
    from ..fast_hdf import _normalize_backend, _try_mesh_polygons
    backend = _normalize_backend(engine)
    result = _try_mesh_polygons(hdf_path, backend=backend, threads=threads, strict=strict)
    if result is None:
        with backend_scope(backend):
            result = HdfMesh._reference_mesh_cell_polygons(
                hdf_path, strict=strict, backend=backend)
    if not diagnostics:
        result.attrs.pop("cell_polygon_diagnostics", None)
    return result

get_mesh_perimeter_faces staticmethod

Python
get_mesh_perimeter_faces(hdf_path: str | Path, mesh_name: str, *, ras_object=None, on_duplicate_ownership: Literal['raise', 'report'] = 'raise') -> GeoDataFrame

Read every perimeter face of a named 2D area, including unassigned faces.

hdf_path accepts geometry/plan HDF paths, open HDF handles, or project numbers resolved by the standard HDF decorator. ras_object selects the project used for number resolution. No files are modified.

Returns a GeoDataFrame with mesh_name, face_id, cell0, cell1, interior_cell_id, exterior_cell_id, fp_start_index, fp_end_index, face_length, bc_line_id, bc_line_name, bc_line_type, and geometry. IDs retain their native zero-based numbering. Exterior cells retain ghost IDs (or -1). Length is the native Faces NormalUnitVector and Length value in model units, falling back to complete face geometry length if absent. BC columns are nullable for confirmed unassigned faces. on_duplicate_ownership="report" keeps one row per face and adds duplicate_ownership (bool), owning_bc_line_ids and owning_bc_line_names (parallel lists in native encounter order). Duplicate-owned faces have null scalar BC ID, name and type; unassigned faces have empty owner lists. Repeated native associations are also marked, even for the same owner. Default "raise" retains strict validation and the original columns. Other validations remain active. attrs['duplicate_ownership'] lists duplicate faces and owners for the requested mesh, with duplicate face and association-row counts.

Physical cells are identified by collection Attributes/Cell Count; higher cell IDs identify native ghost cells. Surface area and the sometimes stale Cell Maximum Index attribute are not used. Faces with one physical cell and one exterior cell form the inventory, including any mesh interior-hole boundary faces. It does not classify perimeter rings or infer associations from geometric proximity.

Raises KeyError for an unknown mesh or missing required native tables. Raises ValueError for malformed topology, duplicate BC ownership, stale BC face/endpoints, or missing native association evidence when the selected area has boundary lines. Missing preprocessing is never reported as confirmed unassigned ownership. Association availability is also retained in attrs['association_status'].

Source code in ras_commander/hdf/HdfMesh.py
Python
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
@staticmethod
@log_call
@standardize_input(file_type="geom_hdf")
def get_mesh_perimeter_faces(
    hdf_path: str | Path,
    mesh_name: str,
    *,
    ras_object=None,
    on_duplicate_ownership: Literal["raise", "report"] = "raise",
) -> "GeoDataFrame":
    """Read every perimeter face of a named 2D area, including unassigned faces.

    ``hdf_path`` accepts geometry/plan HDF paths, open HDF handles, or
    project numbers resolved by the standard HDF decorator. ``ras_object``
    selects the project used for number resolution. No files are modified.

    Returns a GeoDataFrame with ``mesh_name``, ``face_id``, ``cell0``,
    ``cell1``, ``interior_cell_id``, ``exterior_cell_id``,
    ``fp_start_index``, ``fp_end_index``, ``face_length``, ``bc_line_id``,
    ``bc_line_name``, ``bc_line_type``, and ``geometry``. IDs retain their
    native zero-based numbering. Exterior cells retain ghost IDs (or -1).
    Length is the native ``Faces NormalUnitVector and Length`` value in
    model units, falling back to complete face geometry length if absent.
    BC columns are nullable for confirmed unassigned faces.
    ``on_duplicate_ownership="report"`` keeps one row per face and adds
    ``duplicate_ownership`` (bool), ``owning_bc_line_ids`` and
    ``owning_bc_line_names`` (parallel lists in native encounter order).
    Duplicate-owned faces have null scalar BC ID, name and type; unassigned
    faces have empty owner lists. Repeated native associations are also
    marked, even for the same owner. Default ``"raise"`` retains strict
    validation and the original columns. Other validations remain active.
    ``attrs['duplicate_ownership']`` lists duplicate faces and owners for
    the requested mesh, with duplicate face and association-row counts.

    Physical cells are identified by collection ``Attributes/Cell Count``;
    higher cell IDs identify native ghost cells. Surface area and the
    sometimes stale ``Cell Maximum Index`` attribute are not used.
    Faces with one physical cell and one exterior cell form the inventory,
    including any mesh interior-hole boundary faces. It does not classify
    perimeter rings or infer associations from geometric proximity.

    Raises KeyError for an unknown mesh or missing required native tables.
    Raises ValueError for malformed topology, duplicate BC ownership,
    stale BC face/endpoints, or missing native association evidence when
    the selected area has boundary lines. Missing preprocessing is never
    reported as confirmed unassigned ownership. Association availability
    is also retained in ``attrs['association_status']``.
    """
    from geopandas import GeoDataFrame
    from shapely.geometry import LineString

    from .HdfBndry import HdfBndry

    if on_duplicate_ownership not in ("raise", "report"):
        raise ValueError("on_duplicate_ownership must be 'raise' or 'report'")
    with h5py.File(hdf_path, "r") as hdf:
        base = "Geometry/2D Flow Areas"
        attributes = read_typed(hdf[f"{base}/Attributes"])
        names = [_decode_hdf_scalar(value).rstrip() for value in attributes["Name"]]
        if mesh_name not in names:
            raise KeyError(f"Unknown 2D flow area {mesh_name!r} in {hdf_path}")
        if names.count(mesh_name) != 1:
            raise ValueError(f"Duplicate mesh name {mesh_name!r} in {hdf_path}")
        if "Cell Count" not in attributes.dtype.names:
            raise KeyError(f"Missing native Cell Count for {mesh_name!r} in {hdf_path}")
        count_value = attributes["Cell Count"][names.index(mesh_name)]
        if (
            not np.isfinite(count_value)
            or count_value != int(count_value)
            or count_value <= 0
        ):
            raise ValueError(
                f"Invalid native Cell Count for {mesh_name!r}: {count_value}"
            )
        cell_count = int(count_value)
        mesh = hdf[f"{base}/{mesh_name}"]
        adjacency_raw = np.asarray(read_typed(mesh["Faces Cell Indexes"]))
        if adjacency_raw.ndim != 2 or adjacency_raw.shape[1] != 2:
            raise ValueError(f"Faces Cell Indexes must be Nx2 for {mesh_name!r}")
        if (
            not np.isfinite(adjacency_raw).all()
            or not np.equal(adjacency_raw, np.floor(adjacency_raw)).all()
        ):
            raise ValueError(f"Nonintegral face adjacency for {mesh_name!r}")
        adjacency = adjacency_raw.astype(np.int64)
        if (adjacency < -1).any():
            raise ValueError(f"Invalid negative cell ID for {mesh_name!r}")
        centers = mesh["Cells Center Coordinate"]
        if cell_count > len(centers) or (adjacency >= len(centers)).any():
            raise ValueError(
                f"Cell adjacency exceeds native cell table for {mesh_name!r}"
            )
        if "Cells Face and Orientation Info" in mesh:
            cell_info = _integral_rows(
                read_typed(mesh["Cells Face and Orientation Info"]),
                2,
                "Cells Face and Orientation Info",
            )
            if len(cell_info) != len(centers) or (cell_info[cell_count:, 1] != 1).any():
                raise ValueError(
                    f"Native Cell Count disagrees with ghost-cell topology for {mesh_name!r}"
                )
        physical = (adjacency >= 0) & (adjacency < cell_count)
        if (~physical.any(axis=1)).any() or (adjacency[:, 0] == adjacency[:, 1]).any():
            raise ValueError(
                f"Face without distinct physical-cell adjacency for {mesh_name!r}"
            )
        face_ids = np.flatnonzero(physical.sum(axis=1) == 1)
        endpoints_table = mesh["Faces FacePoint Indexes"]
        if endpoints_table.shape != adjacency.shape:
            raise ValueError(
                f"Face endpoint and adjacency counts differ for {mesh_name!r}"
            )
        endpoints = _integral_rows(
            read_typed(endpoints_table, face_ids), 2, "Faces FacePoint Indexes"
        )
        coordinates = mesh["FacePoints Coordinate"]
        if (endpoints >= len(coordinates)).any():
            raise ValueError(
                f"Face endpoint exceeds FacePoints Coordinate for {mesh_name!r}"
            )
        has_info = "Faces Perimeter Info" in mesh
        if has_info != ("Faces Perimeter Values" in mesh):
            raise ValueError(f"Partial face perimeter tables for {mesh_name!r}")
        if has_info and len(mesh["Faces Perimeter Info"]) != len(adjacency):
            raise ValueError(
                f"Face perimeter and adjacency counts differ for {mesh_name!r}"
            )
        perimeter = (
            _integral_rows(
                read_typed(mesh["Faces Perimeter Info"], face_ids), 2, "Faces Perimeter Info"
            )
            if has_info
            else np.zeros((len(face_ids), 2), dtype=np.int64)
        )
        geometries = []
        for (start_point, end_point), (start, size) in zip(endpoints, perimeter):
            if has_info and start + size > len(mesh["Faces Perimeter Values"]):
                raise ValueError(
                    f"Face perimeter range exceeds values for {mesh_name!r}"
                )
            vertices = [read_typed(coordinates, (start_point, slice(None, 2)))]
            if size:
                vertices.extend(
                    read_typed(mesh["Faces Perimeter Values"], (slice(start, start + size), slice(None, 2)))
                )
            vertices.append(read_typed(coordinates, (end_point, slice(None, 2))))
            if not np.isfinite(vertices).all():
                raise ValueError(f"Nonfinite perimeter coordinates for {mesh_name!r}")
            line = LineString(vertices)
            if line.length <= 0:
                raise ValueError(f"Degenerate perimeter face for {mesh_name!r}")
            geometries.append(line)
        if "Faces NormalUnitVector and Length" in mesh:
            lengths_table = mesh["Faces NormalUnitVector and Length"]
            if (
                lengths_table.ndim != 2
                or lengths_table.shape[1] < 3
                or len(lengths_table) != len(adjacency)
            ):
                raise ValueError(f"Malformed native face lengths for {mesh_name!r}")
            lengths = np.asarray(read_typed(lengths_table, (face_ids, 2)), dtype=np.float64)
            length_source = "native"
        else:
            lengths = np.asarray([line.length for line in geometries])
            length_source = "geometry"
        if not np.isfinite(lengths).all() or (lengths <= 0).any():
            raise ValueError(f"Invalid perimeter face lengths for {mesh_name!r}")
        selected = adjacency[face_ids]
        interior_side = np.argmax(physical[face_ids], axis=1)
        result = GeoDataFrame(
            {
                "mesh_name": pd.Series([mesh_name] * len(face_ids), dtype="string"),
                "face_id": face_ids,
                "cell0": selected[:, 0],
                "cell1": selected[:, 1],
                "interior_cell_id": selected[np.arange(len(face_ids)), interior_side],
                "exterior_cell_id": selected[
                    np.arange(len(face_ids)), 1 - interior_side
                ],
                "fp_start_index": endpoints[:, 0],
                "fp_end_index": endpoints[:, 1],
                "face_length": lengths,
                "geometry": geometries,
            },
            geometry="geometry",
            crs=HdfBase.get_projection(hdf),
        )
        association = HdfBndry.get_bc_external_faces(
            hdf_path, on_duplicate_ownership=on_duplicate_ownership
        )
        if len(association) and association["mesh_name"].isna().any():
            raise ValueError(f"Native BC ownership lacks mesh metadata in {hdf_path}")
        if association.attrs["association_status"] == "absent":
            bc_path = "Geometry/Boundary Condition Lines/Attributes"
            if "Geometry/Boundary Condition Lines" in hdf and bc_path not in hdf:
                raise ValueError(
                    f"BC lines lack Attributes needed to establish ownership in {hdf_path}"
                )
            if bc_path in hdf:
                bc_attrs = read_typed(hdf[bc_path])
                mesh_field = HdfBndry._find_structured_field(
                    bc_attrs.dtype.names or (), "SA-2D", "Mesh Name"
                )
                if len(bc_attrs) and (
                    mesh_field is None
                    or any(
                        HdfBndry._decode_bc_text(value) == mesh_name
                        for value in bc_attrs[mesh_field]
                    )
                ):
                    raise ValueError(
                        f"Native BC external faces absent for {mesh_name!r}; preprocess geometry first"
                    )
        owners = association.loc[association["mesh_name"] == mesh_name].copy()
        if not owners["face_id"].isin(face_ids).all():
            raise ValueError(
                f"BC ownership references non-perimeter faces for {mesh_name!r}"
            )
        indexed = result.set_index("face_id")
        for row in owners.itertuples():
            if pd.isna(row.bc_line_id) or pd.isna(row.bc_line_name):
                raise ValueError(f"Incomplete native BC ownership for {mesh_name!r}")
            expected = indexed.loc[
                row.face_id, ["fp_start_index", "fp_end_index"]
            ].tolist()
            if (
                not pd.isna(row.fp_start_index)
                and not pd.isna(row.fp_end_index)
                and sorted(expected) != sorted([row.fp_start_index, row.fp_end_index])
            ):
                raise ValueError(
                    f"Stale native BC face/endpoints for {mesh_name!r}, face {row.face_id}"
                )
        owner_columns = ["face_id", "bc_line_id", "bc_line_name", "bc_line_type"]
        if on_duplicate_ownership == "report":
            owner_columns += [
                "duplicate_ownership",
                "owning_bc_line_ids",
                "owning_bc_line_names",
            ]
            # Every native row was validated above. Collapse only the
            # perimeter join; the association reader remains lossless.
            duplicate_rows = owners["duplicate_ownership"]
            owners.loc[
                duplicate_rows, ["bc_line_id", "bc_line_name", "bc_line_type"]
            ] = pd.NA
            owners = owners.drop_duplicates("face_id")
        result = result.merge(
            owners[owner_columns],
            on="face_id",
            how="left",
            validate="one_to_one",
        )
        columns = [
            "mesh_name",
            "face_id",
            "cell0",
            "cell1",
            "interior_cell_id",
            "exterior_cell_id",
            "fp_start_index",
            "fp_end_index",
            "face_length",
            "bc_line_id",
            "bc_line_name",
            "bc_line_type",
            "geometry",
        ]
        if on_duplicate_ownership == "report":
            result["duplicate_ownership"] = result["duplicate_ownership"].eq(True)
            for column in ("owning_bc_line_ids", "owning_bc_line_names"):
                result[column] = result[column].map(
                    lambda value: value if isinstance(value, list) else []
                )
            columns += [
                "duplicate_ownership",
                "owning_bc_line_ids",
                "owning_bc_line_names",
            ]
        result = result[columns]
        summary = [
            record
            for record in association.attrs.get("duplicate_ownership", [])
            if record["mesh_name"] == mesh_name
        ]
        if on_duplicate_ownership == "report":
            native_duplicates = association.loc[
                (association["mesh_name"] == mesh_name)
                & association["duplicate_ownership"]
            ]
            result.attrs.update(
                duplicate_ownership=summary,
                duplicate_face_count=len(summary),
                duplicate_face_row_count=len(native_duplicates),
            )
        result.attrs.update(
            association_status=association.attrs["association_status"],
            face_ownership_unique=not summary,
            length_source=length_source,
            physical_cell_count=cell_count,
        )
        return result

Quality assurance validation for HEC-RAS 6.x models.

Supports both steady flow and unsteady flow plans. Flow type is auto-detected from the plan HDF file.

All methods are static and follow ras-commander conventions. Use @standardize_input decorator for flexible path handling.

This class is a facade that delegates to domain-specific check classes: - CheckUnsteady: Mass balance, computation, peaks, stability, mesh quality - CheckNt: Manning's n values, HTAB parameters - CheckXs: Cross section validation - CheckStructures: Bridge, culvert, inline weir validation - CheckFloodways: Floodway encroachment validation - CheckProfiles: Multiple profile consistency

check_mesh_quality staticmethod

Python
check_mesh_quality(plan_hdf, geom_hdf, thresholds=None)

Delegate to CheckUnsteady.check_mesh_quality.

Source code in ras_commander/check/RasCheck.py
Python
@staticmethod
def check_mesh_quality(plan_hdf, geom_hdf, thresholds=None):
    """Delegate to CheckUnsteady.check_mesh_quality."""
    return CheckUnsteady.check_mesh_quality(plan_hdf, geom_hdf, thresholds)

check_subgrid_sampling staticmethod

Python
check_subgrid_sampling(geom_file, thresholds=None)

Delegate to CheckNt.check_subgrid_sampling.

Source code in ras_commander/check/RasCheck.py
Python
@staticmethod
def check_subgrid_sampling(geom_file, thresholds=None):
    """Delegate to CheckNt.check_subgrid_sampling."""
    return CheckNt.check_subgrid_sampling(geom_file, thresholds)

For full check-result and threshold behavior, see the quality-assurance guide.

Runtime and persisted changes

Native mesh generation uses Windows Python, pythonnet and the selected installed HEC-RAS RasMapperLib.dll. The version matrix and qualification notes cover 6.0–7.0.1 and the specifically tested Windows-Python-under-Wine setup; this does not make native Linux Python a supported CLR runtime. Select hecras_dir explicitly for reproducibility: generate() otherwise discovers the newest installation, which need not match the project's version. Use a fresh process when changing the loaded DLL version.

generate() needs a content-current compiled HDF workspace. Its recompile_via_rasexe=True option refreshes missing/stale HDF through the library's preprocessor and requires an initialized project with a referencing plan. Computation points are written into geometry text. Automatic perimeter repairs can also change text and HDF: work on a disposable project copy and inspect MeshResult.perimeter_repairs, backups, displacement and area changes. See the repair contract for failure semantics.

The domain gate checks breaklines and structures against the exact perimeter buffered inward by one base-cell spacing. Valid refinement regions can touch or extend beyond the perimeter. strict_refinement_containment=True applies the earlier inward margin to regions too. BC lines need separate association and overlap checks. Property-table success does not prove that intended land-cover assignments were used: validate associations and inspect final cell properties.

Refinement-region spacing_dy is stored for schema fidelity, not evidence of independent anisotropic Y refinement. Retain the release-specific refinement caveats and flowline-refinement workflow when designing an authoring workflow. GUI mesh-refresh/import operations are separate from computation-point generation.

Examples with retained outputs

These notebooks retain outputs for their demonstrated models and runtimes; they do not qualify every geometry, release or hydraulic configuration.

Repair persistence and failure contract

  • audit_domain_containment(geom_number, mesh_name=..., cell_size=..., ras_object=...) checks the breakline/structure margin and region validity. strict_refinement_containment=True also checks region extents against the inward margin. BC lines require a separate audit.
  • generate(geom_number, mesh_name=..., ras_object=...) runs that gate before loading native RAS Mapper dependencies.

When the existing automatic-repair loop removes perimeter vertices or applies Douglas–Peucker simplification, generate() writes the repaired perimeter through GeomStorage.set_2d_flow_area_perimeter(create_backup=True), regenerates initial computation points, and runs GeomPreprocessor.run_geometry_preprocessor() with geometry_only=True, force=True, and clear_geompre=True. Supply an initialized ras_object with a plan referencing that geometry. Work on a disposable project copy: repair changes the geometry text and compiled HDF. The loop reloads the HDF, checks text/HDF consistency and feature containment, then retries within max_iterations. recompile_via_rasexe still controls the initial missing/stale HDF refresh; it is not required for this automatic repair handoff.

MeshResult.perimeter_repairs contains one record per persisted repair: reason, original_perimeter_hash, repaired_perimeter_hash, max_vertex_displacement, area_change, and backup_path. SHA-256 hashes cover ordered closed XY rings as compact JSON floating-point pairs, using actual persisted coordinates after writer rounding. Displacement is the maximum vertex-to-opposite-boundary distance in both directions, in project length units; signed area change is repaired minus original polygon area in squared project units. CRS and units remain those of the project. Evidence is logged before preprocessing so failures remain traceable. Failed repair handoffs and retries raise RuntimeError chained to the original mesh repair reason, including iteration exhaustion. Ordinary failures before any repair retain the existing MeshResult behavior. These records describe geometry changes; they do not establish hydraulic acceptance.

  • compute_property_tables(geom_number, mesh_name=..., ras_object=...) - Compute face profiles, Manning's n assignments, face hydraulic tables, and cell properties against the restored geometry associations. A missing or broken land-cover link emits a non-fatal warning because HEC-RAS may still return success while populating every cell with the 2D area's scalar default.

Before property-table generation, use RasMap.list_geometry_associations() to inspect every compiled geometry and RasMap.validate_geometry_associations() to require the exact terrain and land-cover paths needed by the workflow. Registration in .rasmap does not prove that a geometry HDF is associated. After preprocessing, validate the temporary plan HDF; after computation, repeat the check on the final plan HDF with HdfLandCover.audit_final_mannings_n() and explicit cell-center criteria.

Saved-point compilation and RAS Mapper constraints

generate() and generate_all() default to refinement_region_constraints=False. Breaklines and structures remain constraints. Refinement regions shape computation-point generation through native RAS Mapper, including interior spacing, perimeter spacing, near repeats, far spacing and protection radius. Region edges are excluded from the mesh used to classify and repair the saved computation points. Set refinement_region_constraints=True to retain the earlier RAS Mapper mesh with region-edge constraints.

Qualification with HEC-RAS 6.6 distinguishes a cached RAS Mapper mesh from a fresh geometry-text point compile. Mapper can retain region-edge constraints in a compiled HDF; a text-point rebuild can produce different face counts. An unchanged cache is therefore insufficient evidence of compile agreement. Point writes refresh Storage Area 2D PointsPerimeterTime, and successful generation persists the face-length ratio used by the repair loop. Native region generation can also return points outside a smaller flow area; generate() removes outside and boundary points before meshing and records the removal in fixes_applied.

The trimmed 26-point regression has a nine-face cell with breakline constraints and a seven-face cell with region-edge constraints. The latter reports Complete; the saved-point mesh reports MaxFacesPerCellExceeded. This qualification concerns mesh classification in 6.6. Inspect fresh compiled HDF face counts and native data errors after preprocessing, particularly with other releases or internal structures.

HEC's HEC-RAS 6.6 Mapper manual, 2D Flow Areas describes the point-generation controls and Mapper's enforcement workflow. The saved-point/cache distinction above comes from RAS Commander qualification.

Optional multi-configuration screening

Enable robustness_screening=True in GeomMesh.generate() or generate_all() to run an additional RAS Commander optimization:

Python
result = GeomMesh.generate(
    "02", cell_size=125, min_face_length_ratio=0.0025,
    robustness_screening=True, ras_object=ras, hecras_dir=hecras_dir,
)
if not result.ok:
    raise RuntimeError(result.error_message)
print(result.robustness_screening)

The default is False, with no extra mesh builds. The option requires a single 2D flow area, known HDF length units and the ratio-aware native constructor introduced in HEC-RAS 6.6. Screening checks native MeshFV2D.CellFacesCount at the requested ratio, the successful generation ratio, 0.05 and 0.1 (duplicates removed). Each ratio is checked with:

  • breakline and structure constraints;
  • breakline, structure and refinement-region boundary constraints;
  • no constraints, as a stress case only.

Refinement-generated points remain in all three cases. The unconstrained mesh is never saved as the production mesh. The saved mesh uses the successful generation ratio and the caller's refinement_region_constraints setting. This retains the structure constraints while testing the influence of region edges separately.

Each round checks the same points in every configuration. Cells with more than eight faces propose midpoint additions; additions must be distinct and strictly inside a 0.5 ft (0.1524 m) inward perimeter buffer. All configurations are rechecked after additions. Screening permits at most max_iterations repair rounds plus a final check, and at most 50% seed growth. Unsupported states, unreadable constraints, failed native point generation, unavailable counts or exhausted budgets fail the operation before the screened mesh is saved. Ordinary generation may already have updated spacing or repaired a perimeter; use a project copy as described above. MeshResult.robustness_screening records checks, counts, additions, convergence and elapsed time. It is empty when screening is disabled.

This is an independent RAS Commander optimization, not a HEC-RAS preprocessor replica or an HEC-endorsed method. It deliberately has no fallback that reports successful screening after an unresolved check. Run the native preprocessor and inspect its data errors and fresh topology before accepting the mesh.

Qualification used HEC-RAS 6.6 and the public BaldEagleCrkMulti2D geometry 02: seven breaklines, internal structures Dam and Upper Levee, and an added 500 ft square refinement region with 25 ft spacing. Tests included 100 ft base spacing and 125 ft base spacing with 12.5 ft near-breakline spacing. Both structures retained verified attachments and the region retained 400 interior points after native preprocessing and a one-minute connectivity solve. A controlled nine-face cell in the finer mesh failed native preprocessing; midpoint repair cleared all nine screening configurations and passed native preprocessing. This tests the repair path, not a naturally occurring defect that appears only at another ratio, and does not establish flood-simulation accuracy or support for every structure type. The library screening run on the 125 ft case added about 41 seconds for the clean mesh and 89 seconds for the two-round repair on two CPU cores. These are single-run timings, not a benchmark; runtime varies with model and hardware.

Carry refinement regions into a child area

Prepare the collection from a content-current source HDF, then replace the collection in a disposable child geometry:

Python
regions, report = GeomMesh.clip_refinement_regions(
    source_geom,
    child_perimeter,
    min_area=0.0,
)
GeomMesh.replace_refinement_regions(child_geom, regions)

Coordinates must use the source CRS and project units. The source remains unchanged. replace_refinement_regions() stages the child HDF update atomically and makes a backup by default. It retains X/Y spacing, shifts, perimeter spacing, near repeats, far spacing and protection radius from the returned mappings. Regenerate points and preprocess the child afterward.

The report has one row per source region: source_fid, name, status, reason, source_area, retained_area, output_fids, touches_perimeter and below_one_cell_area. Disconnected intersections become separate regions with the source name and properties. A line-only intersection is dropped as no_polygon_overlap. Every positive-area fragment is retained by default; small regions need not generate an interior grid point. A caller-selected min_area drops smaller fragments with a recorded reason. Areas use squared project units.

Invalid source polygons and interior rings raise by default. To retain a reviewable report while omitting unsupported source regions, pass invalid_regions="drop" and inspect every dropped row. The replacement writer rejects holes rather than filling them.

Clipping changes the region extent used as the interior grid origin and adds new perimeter transitions. Preserving spacing and shift fields does not reproduce the full region's original points or transitions exactly. A region that surrounds the child can therefore produce different points when clipped to the child boundary.

Anchor a child's regular grid to its parent

RAS Mapper starts a 2D area's regular computation-point grid half a cell inside the area's own bounding box, at (min x + dx/2, max y - dy/2). The Shift dx and Shift dy attributes stored with the 2D area are not used by the point generator (decompiled RasMapperLib 6.5 through 7.0.1). A child area cut from a parent therefore gets a grid offset from the parent's by a sub-cell vector, even with the parent's spacing, breaklines and refinement regions.

Pass the parent's lattice point to generate() to keep the parent's grid:

Python
anchor = GeomMesh.get_grid_anchor(parent_geometry_hdf, mesh_name="Parent")
result = GeomMesh.generate("02", mesh_name="Parent", ras_object=child_ras,
                           grid_anchor=anchor)
print(result.grid_anchor)  # anchor, lattice and enforced point counts

get_grid_anchor() reads the stored perimeter and Spacing dx/dy from a compiled geometry HDF; it uses h5py only. With an anchor, generate() builds the lattice through the anchor and filters it with RAS Mapper's own perimeter rules. That lattice replaces the area's points in memory. RAS Mapper's RegenerateMeshPoints then runs with the area active but not regenerated, the same call RAS Mapper's breakline and refinement-region editors make. It adds the refinement-region points and enforces the breaklines on the anchored lattice. The anchor spacing must equal the mesh cell size, and there is no unanchored fallback. An (x, y) pair is accepted and takes the cell size as its spacing. With the area's own anchor, the result equals RAS Mapper's regeneration exactly.

RasBreakout2D.prepare_cloned_geometry(anchor_grid_to_parent=True) applies the parent's anchor to the child remesh. Use it with Breakout2DSpec(max_breakline_perimeter_crossings=2) (recommended; the default None clips every line). That drops, rather than clips, a source breakline that weaves across the child's one-cell trim boundary, crossing it more than twice (reason exceeds_child_perimeter_crossing_limit). Crossings are inside/outside transitions along the line; running along the boundary is not a crossing. A line that ends inside or passes straight through is clipped as usual.

The feature notes in feature_dev_notes/Mesh_Grid_Anchor/ record the evidence and the comparison with a translate-and-restore workaround.

HEC-RAS Version Support for Headless Mesh Generation

GeomMesh.generate() and GeomMesh.compute_property_tables() support HEC-RAS 6.0 through 7.0.1, including the 6.7 betas. They run RASMapper's own mesh engine (RasMapperLib.dll) from the HEC-RAS installation they load, so each release produces its own RASMapper result.

HEC-RAS Headless mesh generation Notes
6.6, 6.7 Beta 4, 6.7 Beta 5, 7.0, 7.0.1 Supported Full retry ladder, including minimum face-length ratio escalation.
6.3 – 6.5 Supported No minimum face-length ratio escalation (see below).
6.0 – 6.2 Supported As above. Preprocessing needs every land-cover, infiltration, and sediment file the geometry references (see below).

Why older releases need different calls. Two RasMapperLib members changed their parameters between releases, and generate() adapts to whichever form the loaded release has:

RasMapperLib member 6.0 – 6.2 6.3 – 6.3.1 6.4.1 – 6.5 6.6 and later
MeshFV2D(perimeter, points, breaklines, progress, ...) constructor 4 parameters 4 4 5 (adds minFaceLengthRatio)
PointGenerator.RegenerateMeshPoints (breakline-aware seeding) 4 parameters 6 (adds progress reporters) 7 (adds treatInactiveAsNotPresent) 7
RASD2FlowArea.CreatePropertyTables (used by compute_property_tables) 3 parameters 4 (adds per-task reporters) 4 4

Before 6.6, MeshFV2D has no minimum face-length ratio, so generate() skips the ratio-escalation step of its retry ladder. A mesh that 6.6 completes only after raising the ratio can therefore fail on 6.0 – 6.5; the other retry steps still apply.

Known limitations.

  • HEC-RAS 6.0 – 6.2 and missing referenced files. If a land-cover, infiltration, or sediment file referenced by the geometry is missing, HEC-RAS 6.0 – 6.2 skip the geometry during preprocessing without an error, and the plan HDF has no 2D mesh. With these releases, RasPreprocess.preprocess_plan() checks for the files first and fails, naming each missing file, instead of reporting success. HEC-RAS 6.3 and later preprocess the mesh anyway, so the check does not apply to them.
  • Property-table values differ by release. compute_property_tables() writes tables on every supported release, but HEC-RAS changed its property-table computation over time. Values from 6.0 – 6.3.1 differ from 6.4.1 and later, which match each other.
  • Terms and Conditions for Use. A release must have its TCU accepted for the current user before Ras.exe can preprocess headlessly.

Selecting the HEC-RAS version. Without hecras_dir, generate() loads the newest installed release it finds (7.0.1, 7.0, 6.6, 6.7 Beta 5, then 6.5 down to 6.0), regardless of the project's version. Pass hecras_dir to pin the release. Only one RasMapperLib version can be loaded per Python process.

Linux / Wine. The same behavior applies under Wine (rascommander/hec-ras-wine-precompute_{version} images). Loading RasMapperLib there also requires the C:\Python311\GDAL link to the HEC-RAS GDAL folder, prepared from the Linux side.

How refinement regions were tested. A region-only A/B test uses the real RasExamples Chippewa_2D project: a 200-ft base mesh (357 cells), followed by a 1,600-ft-square refinement region requesting 40-ft spacing. RAS Mapper must reload the authored region before regeneration, the refined mesh must contain 2,118 cells, and median nearest-neighbor spacing inside the region must be 40 ft. Native Windows produced the same result on every locally installed 6.x runtime: 6.0, 6.1, 6.2, 6.3, 6.3.1, 6.5, 6.6, and 6.7 Beta 5. A 6.4/6.4.1 installation was not available for this qualification. The private RegenerateMeshPoints API was also reflected independently in each process: activeRegions is parameter 2 in every tested release; only the documented trailing argument count changes.

HEC-RAS 6.6 was also qualified under Wine 11.0 on CLB07 using the pinned rascommander/hec-ras-wine-precompute_6.6 runtime. Both the RAS Mapper product-layer writer and the native-schema fallback produced 2,118 generated computation points (also the HDF Cell Count), 2,209 compiled cell-center rows, 4,376 faces, and 1,600 centers inside the region at exactly 40-ft median nearest-neighbor spacing; outside-region spacing was 122.327 ft. The run used an isolated writable prefix and the Linux-side C:\Python311\GDAL link noted above.

HEC-RAS Refinement-Region Caveats

  • Independent Y spacing is not implemented by HEC-RAS. RAS Mapper stores both X and Y spacing, but the 6.6 Mapper manual labels Cell Spacing Y as "not implemented yet." spacing_dy is preserved for schema fidelity; do not interpret a different Y value as verified anisotropic refinement.
  • HEC-RAS 6.2 GUI row reordering. HEC documented that reordering the Refinement Region Editor table could create duplicate regions and deleting those duplicates could crash. The documented workaround was the feature Send... command; HEC lists the defect as fixed in 6.3. ras-commander does not drive that GUI reorder path.
  • HEC-RAS 6.4 breakline interactions. HEC fixed lost properties after splitting breaklines, incorrect one-cell protection-radius behavior when breakline/region inclusion was disabled, and some breaklines that failed to enforce. Prefer 6.4 or later for models combining these behaviors.
  • HEC-RAS 6.6 perimeter-loss symptom. HEC documented exceptional cases in which a 2D perimeter disappeared and the mesh stopped updating or selecting. Product-backed authoring therefore backs up the geometry HDF and requires a fresh RAS Mapper reload before reporting success.
  • HEC-RAS 6.7 betas. Beta 2/3 had an initial mesh-recompute "Unknown Error"/arithmetic-overflow issue. Beta 5 passes the region-only qualification above, but a stable release is preferable for production.

See HEC's official 6.2 known issues, 6.3 fixes, 6.4 fixes, 6.6 known issues, 7.0's archived beta fixes, and the 6.6 Mapper manual.

Mesh methods

Headless 2D mesh generation, repair, and BC conflict resolution.

Uses RasMapperLib.dll via pythonnet to generate finite volume meshes without the RAS Mapper GUI. Includes a 5-tier auto-fix pipeline that mirrors TryAutoFix behavior from the GUI.

All methods are static — no instantiation needed.

Example

from ras_commander.geom import GeomMesh GeomMesh.setup_gdal_bridge() # optional explicit preflight result = GeomMesh.generate("01") # by geometry number result = GeomMesh.generate("project.g01") # or by file path if result: ... print(f"Mesh: {result.cell_count} cells")

setup_gdal_bridge staticmethod

Python
setup_gdal_bridge(hecras_dir: Optional[Union[str, Path]] = None, python_dir: Optional[Union[str, Path]] = None, create_junction: bool = True) -> bool

Configure HEC-RAS GDAL runtime for RasMapperLib.

The default path points GDAL environment variables and DLL search paths at the GDAL runtime bundled with HEC-RAS, then verifies the legacy python.exe sibling GDAL bridge before RasMapperLib is loaded.

Returns True if the process runtime was configured successfully.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def setup_gdal_bridge(
    hecras_dir: Optional[Union[str, Path]] = None,
    python_dir: Optional[Union[str, Path]] = None,
    create_junction: bool = True,
) -> bool:
    """
    Configure HEC-RAS GDAL runtime for RasMapperLib.

    The default path points GDAL environment variables and DLL search paths
    at the GDAL runtime bundled with HEC-RAS, then verifies the legacy
    ``python.exe`` sibling GDAL bridge before RasMapperLib is loaded.

    Returns True if the process runtime was configured successfully.
    """
    if platform.system() != "Windows":
        logger.warning("setup_gdal_bridge() is Windows-only")
        return False

    if hecras_dir is None:
        hecras_dir = _find_hecras_dir()

    try:
        configure_hecras_gdal_runtime(hecras_dir)
    except FileNotFoundError as exc:
        logger.error(str(exc))
        return False

    if create_junction:
        try:
            configure_rasmapper_gdal_bridge(hecras_dir, python_dir)
        except (FileNotFoundError, RuntimeError) as exc:
            logger.error(str(exc))
            return False

    return True

audit_domain_containment staticmethod

Python
audit_domain_containment(geom_number: Union[str, Number, Path], mesh_name: Optional[str] = None, mesh_index: int = 0, cell_size: Optional[float] = None, ras_object=None, recompile_via_rasexe: bool = False, strict_refinement_containment: bool = False, require_complete_products: bool = False) -> DomainContainmentResult

Audit mesh features before point generation.

Packed refinement regions retain interior rings, disjoint shells and islands using feature-local Parts offsets. Malformed ranges raise.

The admissible geometry is the exact compiled 2D perimeter buffered inward by one base mesh-cell spacing. Every breakline and structure associated with the selected 2D area must be wholly covered by that eroded polygon. Boundary-condition lines are intentionally excluded because external BC lines are authored at the perimeter and require a separate association audit.

Valid refinement regions may touch or extend beyond the perimeter; generate() removes native points outside the 2D area. Set strict_refinement_containment=True to apply the earlier one-cell inward margin to regions as well.

This read-only check is cross-platform and does not load RasMapperLib. A missing, stale, malformed, or ambiguous geometry HDF fails closed. require_complete_products defaults to False and is forwarded to native preprocessing when recompile_via_rasexe=True permits mutation.

Packed polyline Parts offsets resolve for each complete feature. Native local offsets, valid when every part lies within the feature's point count, take precedence over legacy whole-feature global offsets.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def audit_domain_containment(
    geom_number: Union[str, Number, Path],
    mesh_name: Optional[str] = None,
    mesh_index: int = 0,
    cell_size: Optional[float] = None,
    ras_object=None,
    recompile_via_rasexe: bool = False,
    strict_refinement_containment: bool = False,
    require_complete_products: bool = False,
) -> DomainContainmentResult:
    """Audit mesh features before point generation.

    Packed refinement regions retain interior rings, disjoint shells and
    islands using feature-local Parts offsets. Malformed ranges raise.

    The admissible geometry is the exact compiled 2D perimeter buffered
    *inward* by one base mesh-cell spacing. Every breakline and
    structure associated with the selected 2D area must be
    wholly covered by that eroded polygon. Boundary-condition lines are
    intentionally excluded because external BC lines are authored at the
    perimeter and require a separate association audit.

    Valid refinement regions may touch or extend beyond the perimeter;
    ``generate()`` removes native points outside the 2D area. Set
    ``strict_refinement_containment=True`` to apply the earlier one-cell
    inward margin to regions as well.

    This read-only check is cross-platform and does not load RasMapperLib.
    A missing, stale, malformed, or ambiguous geometry HDF fails closed.
    ``require_complete_products`` defaults to False and is forwarded to
    native preprocessing when ``recompile_via_rasexe=True`` permits mutation.

    Packed polyline Parts offsets resolve for each complete feature. Native
    local offsets, valid when every part lies within the feature's point
    count, take precedence over legacy whole-feature global offsets.
    """
    geom_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_path,
        require_current=True,
        ras_object=ras_object,
        mesh_name=mesh_name,
        recompile_via_rasexe=recompile_via_rasexe,
        ignore_seed_count=True,
        require_complete_products=require_complete_products,
    )
    hdf_metadata = _read_mesh_metadata_from_hdf(hdf_path)
    area_names = list(hdf_metadata)
    if mesh_name is None:
        if not isinstance(mesh_index, int) or isinstance(mesh_index, bool):
            raise TypeError("mesh_index must be an integer")
        if mesh_index < 0 or mesh_index >= len(area_names):
            raise IndexError(
                f"mesh_index {mesh_index} is outside the {len(area_names)} "
                "compiled 2D flow area(s)"
            )
        mesh_name = area_names[mesh_index]
    elif mesh_name not in hdf_metadata:
        raise ValueError(
            f"2D flow area {mesh_name!r} is not present exactly once in "
            f"{hdf_path.name}"
        )

    if cell_size is None:
        cell_size = _read_cell_size_from_text(
            geom_path,
            mesh_name=mesh_name,
            mesh_index=mesh_index,
        )
        if cell_size is None:
            hdf_spacing = hdf_metadata[mesh_name].get("spacing_dx")
            if isinstance(hdf_spacing, (int, float)) and hdf_spacing > 0:
                cell_size = float(hdf_spacing)
    if cell_size is None:
        raise ValueError(
            f"Base mesh spacing is unavailable for 2D flow area {mesh_name!r}"
        )
    cell_size = _normalize_positive_value(cell_size, "cell_size")
    return _audit_domain_containment_hdf(
        hdf_path,
        mesh_name,
        cell_size,
        strict_refinement_containment=strict_refinement_containment,
    )

set_breakline_spacing staticmethod

Python
set_breakline_spacing(geom_number: Union[str, Number, Path], near: Optional[float] = None, far: Optional[float] = None, near_repeats: Optional[int] = None, protection_radius: Optional[int] = None, breakline_name: Optional[str] = None, breakline_fid: Optional[int] = None, all_breaklines: bool = False, ras_object=None) -> Path

Edit BreakLine spacing properties in a .g## text file.

Target a single breakline by breakline_name or breakline_fid (0-based index in file order). Set all_breaklines=True for bulk changes (model building, sensitivity analysis).

HEC-RAS allows duplicate breakline names (including empty names). When duplicates exist, breakline_name matches the first occurrence. Use breakline_fid for reliable targeting — call get_breakline_names() to inspect the FID-to-name mapping and check for duplicates before editing by name.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01", 1) or path to .g## text file.

required
near Optional[float]

BreakLine near-spacing in project units. None keeps existing.

None
far Optional[float]

BreakLine far-spacing in project units. None keeps existing.

None
near_repeats Optional[int]

Number of offset seed rows on each side of breaklines. None keeps existing value.

None
protection_radius Optional[int]

Enable 1-cell protection radius (0 or 1). None keeps existing value.

None
breakline_name Optional[str]

Name of the breakline to modify.

None
breakline_fid Optional[int]

0-based index of the breakline in file order. Most reliable selector — breaklines can be unnamed or have duplicate names.

None
all_breaklines bool

If True, apply spacing to every breakline.

False
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None

Returns:

Type Description
Path

Path to .bak backup file created before writing.

Raises:

Type Description
ValueError

If no target is specified, or if the target is not found in the file.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def set_breakline_spacing(
    geom_number: Union[str, Number, Path],
    near: Optional[float] = None,
    far: Optional[float] = None,
    near_repeats: Optional[int] = None,
    protection_radius: Optional[int] = None,
    breakline_name: Optional[str] = None,
    breakline_fid: Optional[int] = None,
    all_breaklines: bool = False,
    ras_object=None,
) -> Path:
    """
    Edit BreakLine spacing properties in a .g## text file.

    Target a single breakline by *breakline_name* or *breakline_fid*
    (0-based index in file order).  Set ``all_breaklines=True`` for
    bulk changes (model building, sensitivity analysis).

    HEC-RAS allows duplicate breakline names (including empty names).
    When duplicates exist, *breakline_name* matches the **first**
    occurrence.  Use *breakline_fid* for reliable targeting — call
    ``get_breakline_names()`` to inspect the FID-to-name mapping and
    check for duplicates before editing by name.

    Args:
        geom_number: Geometry number ("01", 1) or path to .g## text file.
        near: BreakLine near-spacing in project units. None keeps existing.
        far: BreakLine far-spacing in project units. None keeps existing.
        near_repeats: Number of offset seed rows on each side of breaklines.
            None keeps existing value.
        protection_radius: Enable 1-cell protection radius (0 or 1).
            None keeps existing value.
        breakline_name: Name of the breakline to modify.
        breakline_fid: 0-based index of the breakline in file order.
            Most reliable selector — breaklines can be unnamed or
            have duplicate names.
        all_breaklines: If True, apply spacing to every breakline.
        ras_object (RasPrj, optional): Optional RasPrj instance for multi-project support.

    Returns:
        Path to .bak backup file created before writing.

    Raises:
        ValueError: If no target is specified, or if the target is
            not found in the file.
    """
    if not all_breaklines and breakline_name is None and breakline_fid is None:
        raise ValueError(
            "Provide breakline_name or breakline_fid for single-breakline "
            "edits, or set all_breaklines=True for bulk changes."
        )
    if all_breaklines and (breakline_name is not None or breakline_fid is not None):
        raise ValueError(
            "all_breaklines=True cannot be combined with "
            "breakline_name or breakline_fid."
        )
    if breakline_name is not None and breakline_fid is not None:
        raise ValueError(
            "Provide breakline_name or breakline_fid, not both."
        )
    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    return _set_breakline_spacing_impl(
        geom_text_path, near, far,
        near_repeats=near_repeats,
        protection_radius=protection_radius,
        breakline_name=breakline_name,
        breakline_fid=breakline_fid,
        all_breaklines=all_breaklines,
    )

get_breakline_names staticmethod

Python
get_breakline_names(geom_number: Union[str, Number, Path], ras_object=None) -> list[tuple[int, str]]

Read breakline names from a .g## text file.

HEC-RAS allows duplicate and empty breakline names. Use this method to inspect the FID-to-name mapping before calling set_breakline_spacing() or set_breakline_name() by name. When duplicates exist, targeting by breakline_fid is the most reliable approach.

Returns:

Type Description
list[tuple[int, str]]

List of (fid, name) tuples in file order. fid is the

list[tuple[int, str]]

0-based index. Unnamed breaklines have name="".

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def get_breakline_names(
    geom_number: Union[str, Number, Path],
    ras_object=None,
) -> list[tuple[int, str]]:
    """
    Read breakline names from a .g## text file.

    HEC-RAS allows duplicate and empty breakline names.  Use this
    method to inspect the FID-to-name mapping before calling
    ``set_breakline_spacing()`` or ``set_breakline_name()`` by name.
    When duplicates exist, targeting by *breakline_fid* is the most
    reliable approach.

    Returns:
        List of (fid, name) tuples in file order.  *fid* is the
        0-based index.  Unnamed breaklines have ``name=""``.
    """
    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    return _read_breakline_names_from_text(geom_text_path)

set_breakline_name staticmethod

Python
set_breakline_name(geom_number: Union[str, Number, Path], new_name: str, breakline_fid: Optional[int] = None, old_name: Optional[str] = None, ras_object=None) -> Path

Rename a breakline in a .g## text file.

HEC-RAS allows duplicate and empty breakline names. breakline_fid (0-based index in file order) is the most reliable selector. When using old_name, this method raises ValueError if multiple breaklines share that name — use get_breakline_names() to inspect duplicates first, then target by FID or assign unique descriptive names.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number or path to .g## text file.

required
new_name str

New name to assign.

required
breakline_fid Optional[int]

0-based index of the breakline in file order. Most reliable selector — breaklines can be unnamed or have duplicate names.

None
old_name Optional[str]

Current name of the breakline. Raises if multiple breaklines share this name.

None
ras_object RasPrj

Optional RasPrj instance.

None

Returns:

Type Description
Path

Path to .bak backup file created before writing.

Raises:

Type Description
ValueError

If neither selector is given, both are given, the target is not found, or old_name matches multiple breaklines.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def set_breakline_name(
    geom_number: Union[str, Number, Path],
    new_name: str,
    breakline_fid: Optional[int] = None,
    old_name: Optional[str] = None,
    ras_object=None,
) -> Path:
    """
    Rename a breakline in a .g## text file.

    HEC-RAS allows duplicate and empty breakline names.
    *breakline_fid* (0-based index in file order) is the most
    reliable selector.  When using *old_name*, this method raises
    ``ValueError`` if multiple breaklines share that name — use
    ``get_breakline_names()`` to inspect duplicates first, then
    target by FID or assign unique descriptive names.

    Args:
        geom_number: Geometry number or path to .g## text file.
        new_name: New name to assign.
        breakline_fid: 0-based index of the breakline in file order.
            Most reliable selector — breaklines can be unnamed or
            have duplicate names.
        old_name: Current name of the breakline.  Raises if
            multiple breaklines share this name.
        ras_object (RasPrj, optional): Optional RasPrj instance.

    Returns:
        Path to .bak backup file created before writing.

    Raises:
        ValueError: If neither selector is given, both are given,
            the target is not found, or *old_name* matches multiple
            breaklines.
    """
    if breakline_fid is None and old_name is None:
        raise ValueError("Provide breakline_fid or old_name.")
    if breakline_fid is not None and old_name is not None:
        raise ValueError("Provide breakline_fid or old_name, not both.")
    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    return _set_breakline_name_impl(
        geom_text_path, new_name,
        breakline_fid=breakline_fid,
        old_name=old_name,
    )

get_breakline_spacing staticmethod

Python
get_breakline_spacing(geom_number: Union[str, Number, Path], ras_object=None) -> list[tuple[int, str, float, float, int, int]]

Read per-breakline spacing from a .g## text file.

HEC-RAS allows duplicate and empty breakline names. The fid in each tuple is the most reliable identifier — use it with set_breakline_spacing(breakline_fid=...) when names are ambiguous.

Returns:

Type Description
list[tuple[int, str, float, float, int, int]]

List of (fid, name, near, far, near_repeats, protection_radius)

list[tuple[int, str, float, float, int, int]]

tuples in file order. fid is the 0-based index.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def get_breakline_spacing(
    geom_number: Union[str, Number, Path],
    ras_object=None,
) -> list[tuple[int, str, float, float, int, int]]:
    """
    Read per-breakline spacing from a .g## text file.

    HEC-RAS allows duplicate and empty breakline names.  The *fid*
    in each tuple is the most reliable identifier — use it with
    ``set_breakline_spacing(breakline_fid=...)`` when names are
    ambiguous.

    Returns:
        List of (fid, name, near, far, near_repeats, protection_radius)
        tuples in file order.  *fid* is the 0-based index.
    """
    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    return _read_breakline_spacing_from_text(geom_text_path)

get_refinement_region_names staticmethod

Python
get_refinement_region_names(geom_number: Union[str, Number, Path], hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> list[tuple[int, str]]

Read refinement region names from the compiled HDF.

HEC-RAS allows duplicate and empty refinement region names. Use this method to inspect the FID-to-name mapping before calling set_refinement_region_spacing() or set_refinement_region_name() by name. When duplicates exist, targeting by region_fid is the most reliable approach.

Refinement regions are stored in HDF, not .g## text. The compiled HDF must already exist.

Returns:

Type Description
list[tuple[int, str]]

List of (fid, name) tuples in HDF order. fid is the

list[tuple[int, str]]

0-based index.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def get_refinement_region_names(
    geom_number: Union[str, Number, Path],
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> list[tuple[int, str]]:
    """
    Read refinement region names from the compiled HDF.

    HEC-RAS allows duplicate and empty refinement region names.
    Use this method to inspect the FID-to-name mapping before
    calling ``set_refinement_region_spacing()`` or
    ``set_refinement_region_name()`` by name.  When duplicates
    exist, targeting by *region_fid* is the most reliable approach.

    Refinement regions are stored in HDF, not .g## text.  The compiled
    HDF must already exist.

    Returns:
        List of (fid, name) tuples in HDF order.  *fid* is the
        0-based index.
    """
    import h5py

    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )

    rr_key = "Geometry/2D Flow Area Refinement Regions/Attributes"
    result = []
    with h5py.File(str(hdf_path), "r") as hf:
        if rr_key not in hf:
            return result
        data = read_typed(hf[rr_key], slice(None))
        for i, row in enumerate(data):
            name = row["Name"].decode("utf-8", errors="replace").strip()
            result.append((i, name))
    return result

set_refinement_region_name staticmethod

Python
set_refinement_region_name(geom_number: Union[str, Number, Path], new_name: str, region_fid: Optional[int] = None, old_name: Optional[str] = None, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> None

Rename a refinement region in the compiled HDF.

HEC-RAS allows duplicate and empty refinement region names. region_fid (0-based index in HDF order) is the most reliable selector. When using old_name, this method raises ValueError if multiple regions share that name — use get_refinement_region_names() to inspect duplicates first, then target by FID or assign unique descriptive names.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number or path to .g## text file.

required
new_name str

New name to assign.

required
region_fid Optional[int]

0-based index of the region in HDF order. Most reliable selector — regions can be unnamed or have duplicate names.

None
old_name Optional[str]

Current name of the region. Raises if multiple regions share this name.

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance.

None

Raises:

Type Description
ValueError

If neither selector is given, both are given, the target is not found, or old_name matches multiple regions.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def set_refinement_region_name(
    geom_number: Union[str, Number, Path],
    new_name: str,
    region_fid: Optional[int] = None,
    old_name: Optional[str] = None,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> None:
    """
    Rename a refinement region in the compiled HDF.

    HEC-RAS allows duplicate and empty refinement region names.
    *region_fid* (0-based index in HDF order) is the most reliable
    selector.  When using *old_name*, this method raises
    ``ValueError`` if multiple regions share that name — use
    ``get_refinement_region_names()`` to inspect duplicates first,
    then target by FID or assign unique descriptive names.

    Args:
        geom_number: Geometry number or path to .g## text file.
        new_name: New name to assign.
        region_fid: 0-based index of the region in HDF order.
            Most reliable selector — regions can be unnamed or
            have duplicate names.
        old_name: Current name of the region.  Raises if multiple
            regions share this name.
        hecras_dir: Override HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance.

    Raises:
        ValueError: If neither selector is given, both are given,
            the target is not found, or *old_name* matches multiple
            regions.
    """
    import h5py

    if region_fid is None and old_name is None:
        raise ValueError("Provide region_fid or old_name.")
    if region_fid is not None and old_name is not None:
        raise ValueError("Provide region_fid or old_name, not both.")

    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )

    rr_key = "Geometry/2D Flow Area Refinement Regions/Attributes"
    with h5py.File(str(hdf_path), "r+") as hf:
        if rr_key not in hf:
            raise ValueError("No refinement regions in geometry HDF.")
        data = hf[rr_key][:]

        found_idx = None
        for i in range(len(data)):
            name = data["Name"][i].decode("utf-8", errors="replace").strip()
            match = False
            if region_fid is not None:
                match = i == region_fid
            elif old_name is not None:
                match = name == old_name
            if match:
                if found_idx is not None:
                    raise ValueError(
                        f"Multiple refinement regions match {repr(old_name)}; "
                        f"use region_fid for disambiguation."
                    )
                found_idx = i

        if found_idx is None:
            target = (
                f"FID {region_fid}" if region_fid is not None
                else repr(old_name)
            )
            raise ValueError(
                f"Refinement region {target} not found in HDF."
            )

        name_len = data.dtype["Name"].itemsize
        encoded = new_name.encode("utf-8")
        if len(encoded) > name_len:
            encoded = new_name.encode("utf-8")[:name_len]
            encoded = encoded.decode("utf-8", errors="ignore").encode("utf-8")
        data["Name"][found_idx] = encoded
        hf[rr_key][:] = data

    logger.info(
        f"Renamed refinement region FID {found_idx} → '{new_name}' "
        f"in {hdf_path.name}"
    )

get_refinement_regions staticmethod

Python
get_refinement_regions(geom_number: Union[str, Number, Path], hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> list[dict]

Read refinement region names and spacing from the compiled HDF.

HEC-RAS allows duplicate and empty refinement region names. The fid in each dict is the most reliable identifier — use it with set_refinement_region_spacing(region_fid=...) or set_refinement_region_name(region_fid=...) when names are ambiguous.

Refinement regions are stored in HDF, not .g## text. The compiled HDF must already exist.

Returns:

Type Description
List of dicts with keys

fid, name, spacing_dx, spacing_dy.

list[dict]

Empty list if no refinement regions exist.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def get_refinement_regions(
    geom_number: Union[str, Number, Path],
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> list[dict]:
    """
    Read refinement region names and spacing from the compiled HDF.

    HEC-RAS allows duplicate and empty refinement region names.
    The *fid* in each dict is the most reliable identifier — use it
    with ``set_refinement_region_spacing(region_fid=...)`` or
    ``set_refinement_region_name(region_fid=...)`` when names are
    ambiguous.

    Refinement regions are stored in HDF, not .g## text.  The compiled
    HDF must already exist.

    Returns:
        List of dicts with keys: fid, name, spacing_dx, spacing_dy.
        Empty list if no refinement regions exist.
    """
    import h5py

    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )

    rr_key = "Geometry/2D Flow Area Refinement Regions/Attributes"
    result = []
    with h5py.File(str(hdf_path), "r") as hf:
        if rr_key not in hf:
            return result
        data = read_typed(hf[rr_key], slice(None))
        has_dx = "Spacing dx" in data.dtype.names
        has_dy = "Spacing dy" in data.dtype.names
        for i, row in enumerate(data):
            name = row["Name"].decode("utf-8", errors="replace").strip()
            dx = float(row["Spacing dx"]) if has_dx else 0.0
            dy = float(row["Spacing dy"]) if has_dy else 0.0
            result.append({
                "fid": i, "name": name,
                "spacing_dx": dx, "spacing_dy": dy,
            })
    return result

set_refinement_region_spacing staticmethod

Python
set_refinement_region_spacing(geom_number: Union[str, Number, Path], spacing_dx: Optional[float] = None, spacing_dy: Optional[float] = None, region_name: Optional[str] = None, region_fid: Optional[int] = None, all_regions: bool = False, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> None

Set refinement region cell spacing in the compiled HDF.

Refinement regions override the base cell size within their polygon boundaries. Target a single region by region_name or region_fid (0-based index in HDF order). Set all_regions=True for bulk changes.

HEC-RAS allows duplicate and empty refinement region names. When duplicates exist, region_name matches the first occurrence. Use region_fid for reliable targeting — call get_refinement_region_names() to inspect the FID-to-name mapping and check for duplicates before editing by name.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number or path to .g## text file.

required
spacing_dx Optional[float]

Cell spacing in the X direction (project units). None keeps existing value.

None
spacing_dy Optional[float]

Cell spacing in the Y direction (project units). None keeps existing value. Defaults to spacing_dx if spacing_dx is provided and spacing_dy is None.

None
region_name Optional[str]

Name of the refinement region to modify.

None
region_fid Optional[int]

0-based index of the region in HDF order. Most reliable selector — regions can be unnamed or have duplicate names.

None
all_regions bool

If True, apply spacing to every region.

False
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance.

None

Raises:

Type Description
ValueError

If no target is specified, or if the target is not found.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def set_refinement_region_spacing(
    geom_number: Union[str, Number, Path],
    spacing_dx: Optional[float] = None,
    spacing_dy: Optional[float] = None,
    region_name: Optional[str] = None,
    region_fid: Optional[int] = None,
    all_regions: bool = False,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> None:
    """
    Set refinement region cell spacing in the compiled HDF.

    Refinement regions override the base cell size within their
    polygon boundaries.  Target a single region by *region_name*
    or *region_fid* (0-based index in HDF order).  Set
    ``all_regions=True`` for bulk changes.

    HEC-RAS allows duplicate and empty refinement region names.
    When duplicates exist, *region_name* matches the **first**
    occurrence.  Use *region_fid* for reliable targeting — call
    ``get_refinement_region_names()`` to inspect the FID-to-name
    mapping and check for duplicates before editing by name.

    Args:
        geom_number: Geometry number or path to .g## text file.
        spacing_dx: Cell spacing in the X direction (project units).
            None keeps existing value.
        spacing_dy: Cell spacing in the Y direction (project units).
            None keeps existing value.  Defaults to spacing_dx if
            spacing_dx is provided and spacing_dy is None.
        region_name: Name of the refinement region to modify.
        region_fid: 0-based index of the region in HDF order.
            Most reliable selector — regions can be unnamed or
            have duplicate names.
        all_regions: If True, apply spacing to every region.
        hecras_dir: Override HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance.

    Raises:
        ValueError: If no target is specified, or if the target is
            not found.
    """
    import h5py

    if not all_regions and region_name is None and region_fid is None:
        raise ValueError(
            "Provide region_name or region_fid for single-region edits, "
            "or set all_regions=True for bulk changes."
        )
    if all_regions and (region_name is not None or region_fid is not None):
        raise ValueError(
            "all_regions=True cannot be combined with "
            "region_name or region_fid."
        )
    if region_name is not None and region_fid is not None:
        raise ValueError(
            "Provide region_name or region_fid, not both."
        )
    if spacing_dx is not None and spacing_dy is None:
        spacing_dy = spacing_dx

    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )

    rr_key = "Geometry/2D Flow Area Refinement Regions/Attributes"
    with h5py.File(str(hdf_path), "r+") as hf:
        if rr_key not in hf:
            raise ValueError("No refinement regions in geometry HDF.")
        data = hf[rr_key][:]
        has_dx = "Spacing dx" in data.dtype.names
        has_dy = "Spacing dy" in data.dtype.names
        if not has_dx or not has_dy:
            raise ValueError(
                "HDF refinement regions missing Spacing columns."
            )

        if region_name is not None:
            has_name_col = "Name" in data.dtype.names
            if not has_name_col:
                raise ValueError(
                    "HDF refinement regions missing Name column — "
                    "use region_fid instead."
                )
            matches = [
                i for i in range(len(data))
                if data["Name"][i].decode("utf-8", errors="replace").strip()
                == region_name
            ]
            if len(matches) > 1:
                raise ValueError(
                    f"Multiple refinement regions named '{region_name}' "
                    f"(count={len(matches)}). Use region_fid for "
                    f"disambiguation — call get_refinement_region_names() "
                    f"to inspect FID-to-name mapping."
                )

        found = False
        for i in range(len(data)):
            if all_regions:
                target_match = True
            elif region_fid is not None:
                target_match = i == region_fid
            else:
                name = data["Name"][i].decode("utf-8", errors="replace").strip()
                target_match = name == region_name
            if not target_match:
                continue
            found = True
            if spacing_dx is not None:
                data["Spacing dx"][i] = spacing_dx
            if spacing_dy is not None:
                data["Spacing dy"][i] = spacing_dy

        if not all_regions and not found:
            target_desc = (
                f"FID {region_fid}" if region_fid is not None
                else f"'{region_name}'"
            )
            raise ValueError(
                f"Refinement region {target_desc} not found in HDF."
            )
        hf[rr_key][:] = data

    target = (
        f"FID {region_fid}" if region_fid is not None
        else region_name or "ALL"
    )
    logger.info(
        f"Refinement region [{target}]: dx={spacing_dx}, dy={spacing_dy} "
        f"→ {hdf_path.name}"
    )

replace_refinement_regions staticmethod

Python
replace_refinement_regions(geom_number: Union[str, Number, Path], regions: Sequence[Mapping[str, Any]], *, expected_existing_names: Optional[Sequence[str]] = None, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, create_backup: bool = True) -> Optional[Path]

Atomically replace the complete HDF refinement-region collection.

Each region mapping requires polygon (or geometry) and spacing_dx; spacing_dy defaults to spacing_dx and name defaults to an empty string. The replacement is built and validated in a same-directory temporary HDF before it is promoted over the original.

Optional native properties are shift_dx, shift_dy, perimeter_spacing, near_repeats, far_spacing and protection_radius. Missing floating properties default to NaN; missing repeats and protection radius default to zero. Polygon holes are rejected rather than silently filled. Use clip_refinement_regions to prepare a delivered collection for a child perimeter.

expected_existing_names is an optimistic-concurrency guard. Names are compared in HDF/FID order and may contain duplicates or empty strings because HEC-RAS permits both. Passing an empty regions sequence removes the refinement-region group.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def replace_refinement_regions(
    geom_number: Union[str, Number, Path],
    regions: Sequence[Mapping[str, Any]],
    *,
    expected_existing_names: Optional[Sequence[str]] = None,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    create_backup: bool = True,
) -> Optional[Path]:
    """Atomically replace the complete HDF refinement-region collection.

    Each region mapping requires ``polygon`` (or ``geometry``) and
    ``spacing_dx``; ``spacing_dy`` defaults to ``spacing_dx`` and ``name``
    defaults to an empty string. The replacement is built and validated in
    a same-directory temporary HDF before it is promoted over the original.

    Optional native properties are ``shift_dx``, ``shift_dy``,
    ``perimeter_spacing``, ``near_repeats``, ``far_spacing`` and
    ``protection_radius``. Missing floating properties default to NaN;
    missing repeats and protection radius default to zero. Polygon holes
    are rejected rather than silently filled. Use ``clip_refinement_regions``
    to prepare a delivered collection for a child perimeter.

    ``expected_existing_names`` is an optimistic-concurrency guard. Names
    are compared in HDF/FID order and may contain duplicates or empty
    strings because HEC-RAS permits both. Passing an empty ``regions``
    sequence removes the refinement-region group.
    """
    import h5py
    import numpy as np

    from .GeomParser import GeomParser

    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
        # Refinement-region replacement does not consume computation
        # cells. A freshly imported, intentionally unmeshed HDF is valid
        # as long as perimeter and breakline identity are current.
        ignore_seed_count=True,
    )
    rr_group_key = "Geometry/2D Flow Area Refinement Regions"
    attr_key = f"{rr_group_key}/Attributes"
    info_key = f"{rr_group_key}/Polygon Info"
    parts_key = f"{rr_group_key}/Polygon Parts"
    points_key = f"{rr_group_key}/Polygon Points"

    with h5py.File(str(hdf_path), "r") as hf:
        if attr_key in hf:
            existing_names = [
                row.decode("utf-8", errors="replace").strip()
                for row in hf[attr_key]["Name"]
            ]
        else:
            existing_names = []
    if expected_existing_names is not None:
        expected_existing = [str(name) for name in expected_existing_names]
        if existing_names != expected_existing:
            raise ValueError(
                "Existing refinement-region collection changed before replacement: "
                f"expected {expected_existing!r}, found {existing_names!r}"
            )

    normalized: List[dict] = []
    for index, raw in enumerate(regions):
        if not isinstance(raw, Mapping):
            raise TypeError(f"regions[{index}] must be a mapping")
        polygon = raw.get("polygon", raw.get("geometry"))
        if polygon is None:
            raise ValueError(f"regions[{index}] is missing polygon or geometry")
        if hasattr(polygon, "interiors") and polygon.interiors:
            raise ValueError(f"regions[{index}] polygon has unsupported interior rings")
        coords = _normalise_polygon_coords(polygon)
        if len(coords) < 3:
            raise ValueError(
                f"regions[{index}] polygon must have at least 3 vertices"
            )
        if not np.isfinite(coords).all():
            raise ValueError(f"regions[{index}] polygon has non-finite coordinates")
        if not np.allclose(coords[0], coords[-1]):
            coords = np.vstack([coords, coords[:1]])

        spacing_dx = float(raw.get("spacing_dx"))
        spacing_dy = float(raw.get("spacing_dy", spacing_dx))
        if (
            not np.isfinite(spacing_dx)
            or not np.isfinite(spacing_dy)
            or spacing_dx <= 0
            or spacing_dy <= 0
        ):
            raise ValueError(
                f"regions[{index}] spacing must be finite and positive"
            )
        normalized.append(
            {
                "name": _truncate_ras_name(str(raw.get("name", ""))),
                "coords": np.asarray(coords, dtype=np.float64),
                "spacing_dx": spacing_dx,
                "spacing_dy": spacing_dy,
            }
        )
        native = normalized[-1]
        for key in ("shift_dx", "shift_dy", "perimeter_spacing", "far_spacing"):
            value = float(raw.get(key, np.nan))
            if not np.isnan(value) and (
                not np.isfinite(value) or abs(value) > np.finfo(np.float32).max
                or (key in ("perimeter_spacing", "far_spacing") and value <= 0)
            ):
                raise ValueError(f"regions[{index}] {key} must be valid native spacing/shift or NaN")
            native[key] = value
        for key, upper in (("near_repeats", np.iinfo(np.int32).max), ("protection_radius", 1)):
            value = raw.get(key, 0)
            if not isinstance(value, (int, np.integer)) or not 0 <= value <= upper:
                raise ValueError(f"regions[{index}] {key} must be an integer in [0, {upper}]")
            native[key] = int(value)

    attributes = _refinement_region_attribute_rows(normalized)
    info_rows = []
    part_rows = []
    point_arrays = []
    point_offset = 0
    for region_index, region in enumerate(normalized):
        coords = region["coords"]
        info_rows.append([point_offset, len(coords), region_index, 1])
        part_rows.append([0, len(coords)])
        point_arrays.append(coords)
        point_offset += len(coords)
    polygon_info = np.asarray(info_rows, dtype=np.int32).reshape((-1, 4))
    polygon_parts = np.asarray(part_rows, dtype=np.int32).reshape((-1, 2))
    polygon_points = (
        np.vstack(point_arrays)
        if point_arrays
        else np.empty((0, 2), dtype=np.float64)
    )

    temp_path = hdf_path.with_name(f".{hdf_path.name}.{uuid4().hex}.tmp")
    backup_path = None
    try:
        shutil.copy2(hdf_path, temp_path)
        with h5py.File(str(temp_path), "r+") as hf:
            if rr_group_key in hf:
                del hf[rr_group_key]
            if normalized:
                hf.require_group(rr_group_key)
                _create_hdf_dataset(hf, attr_key, attributes)
                _create_hdf_dataset(hf, info_key, polygon_info)
                _create_hdf_dataset(hf, parts_key, polygon_parts)
                _create_hdf_dataset(hf, points_key, polygon_points)
                _set_refinement_region_dataset_metadata(hf, rr_group_key)

        with h5py.File(str(temp_path), "r") as hf:
            if normalized:
                stored_names = [
                    value.decode("utf-8", errors="replace").strip()
                    for value in hf[attr_key]["Name"]
                ]
                expected_names = [region["name"] for region in normalized]
                if stored_names != expected_names:
                    raise RuntimeError(
                        "Refinement-region name validation failed: "
                        f"{stored_names!r}"
                    )
                if len(hf[info_key]) != len(normalized):
                    raise RuntimeError("Refinement-region count validation failed")
                if len(hf[points_key]) != len(polygon_points):
                    raise RuntimeError("Refinement-region point validation failed")
            elif rr_group_key in hf:
                raise RuntimeError("Empty replacement left a refinement-region group")

        if create_backup:
            backup_path = GeomParser.create_backup(hdf_path)
        release_native_sessions(temp_path, hdf_path)
        os.replace(temp_path, hdf_path)
    finally:
        if temp_path.exists():
            temp_path.unlink()

    logger.info(
        "Replaced %d refinement regions with %d in %s",
        len(existing_names),
        len(normalized),
        hdf_path.name,
    )
    return backup_path

clip_refinement_regions staticmethod

Python
clip_refinement_regions(geom_number: str | Number | Path, perimeter, *, min_area: float = 0.0, invalid_regions: str = 'raise', hecras_dir: str | Path | None = None, ras_object=None) -> tuple[list[dict[str, Any]], pandas.DataFrame]

Prepare delivered refinement regions for a smaller 2D perimeter.

Read the source HDF without modifying it. Intersect each region with perimeter, retain its native spacing properties, and return mappings for replace_refinement_regions() plus a per-source-region DataFrame. Disconnected intersections become separate output regions in source order, with the same name and properties. Duplicate names are permitted.

Parameters:

Name Type Description Default
geom_number str | Number | Path

Source geometry number or .g## text path.

required
perimeter Polygon | MultiPolygon | Sequence[Sequence[float]]

Clipping mask or (N, 2) XY coordinates in the source geometry's CRS and project length units. Holes are not supported by the replacement writer. A disconnected inward buffer may be a MultiPolygon; every positive-area intersection fragment is retained by default. This mask does not author the computational-domain perimeter.

required
min_area float

Optional fragment area cutoff in squared project units. Default zero retains every positive-area fragment, including regions smaller than one spacing_dx * spacing_dy cell. Such regions do not necessarily produce an interior grid point.

0.0
invalid_regions str

"raise" (default) rejects invalid polygons or unsupported holes; "drop" records them as dropped and continues. "repair" uses GEOS make_valid and partitions holes without filling them. Zero-area remnants are recorded. Repair hashes and areas are returned in report.attrs["repairs"].

'raise'
hecras_dir str | Path | None

Optional HEC-RAS installation for source HDF validation.

None
ras_object RasPrj | None

Optional source RasPrj context.

None

Returns:

Type Description
list[dict[str, Any]]

(regions, report). Regions preserve X/Y spacing, shifts, perimeter

DataFrame

spacing, near repeats, far spacing and protection radius. Report

tuple[list[dict[str, Any]], DataFrame]

columns are source_fid, name, status (kept/clipped/dropped), reason,

tuple[list[dict[str, Any]], DataFrame]

source_area, retained_area, output_fids, touches_perimeter and

tuple[list[dict[str, Any]], DataFrame]

below_one_cell_area. Areas use squared project units.

Raises:

Type Description
ValueError

Invalid perimeter, area cutoff, source polygon or unsupported interior rings. No files are written.

Notes

Clipping changes the region extent used as the grid origin and creates new perimeter transitions. Retaining spacing and shifts does not reproduce the full region's original points or transitions.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def clip_refinement_regions(
    geom_number: str | Number | Path,
    perimeter,
    *,
    min_area: float = 0.0,
    invalid_regions: str = "raise",
    hecras_dir: str | Path | None = None,
    ras_object=None,
) -> tuple[list[dict[str, Any]], pandas.DataFrame]:
    """Prepare delivered refinement regions for a smaller 2D perimeter.

    Read the source HDF without modifying it. Intersect each region with
    *perimeter*, retain its native spacing properties, and return mappings
    for ``replace_refinement_regions()`` plus a per-source-region DataFrame.
    Disconnected intersections become separate output regions in source
    order, with the same name and properties. Duplicate names are permitted.

    Args:
        geom_number: Source geometry number or .g## text path.
        perimeter (shapely.geometry.Polygon | MultiPolygon | Sequence[Sequence[float]]):
            Clipping mask or (N, 2) XY coordinates in the
            source geometry's CRS and project length units. Holes are not
            supported by the replacement writer. A disconnected inward
            buffer may be a MultiPolygon; every positive-area intersection
            fragment is retained by default. This mask does not author the
            computational-domain perimeter.
        min_area: Optional fragment area cutoff in squared project units.
            Default zero retains every positive-area fragment, including
            regions smaller than one spacing_dx * spacing_dy cell. Such
            regions do not necessarily produce an interior grid point.
        invalid_regions: "raise" (default) rejects invalid polygons or
            unsupported holes; "drop" records them as dropped and continues.
            "repair" uses GEOS make_valid and partitions holes without
            filling them. Zero-area remnants are recorded. Repair hashes
            and areas are returned in report.attrs["repairs"].
        hecras_dir: Optional HEC-RAS installation for source HDF validation.
        ras_object (RasPrj | None): Optional source RasPrj context.

    Returns:
        (regions, report). Regions preserve X/Y spacing, shifts, perimeter
        spacing, near repeats, far spacing and protection radius. Report
        columns are source_fid, name, status (kept/clipped/dropped), reason,
        source_area, retained_area, output_fids, touches_perimeter and
        below_one_cell_area. Areas use squared project units.

    Raises:
        ValueError: Invalid perimeter, area cutoff, source polygon or
            unsupported interior rings. No files are written.

    Notes:
        Clipping changes the region extent used as the grid origin and
        creates new perimeter transitions. Retaining spacing and shifts
        does not reproduce the full region's original points or transitions.
    """
    import h5py
    import numpy as np
    import pandas as pd
    from shapely.geometry import MultiPolygon, Polygon

    from ..hdf.HdfBndry import HdfBndry

    child = perimeter if isinstance(perimeter, (Polygon, MultiPolygon)) else Polygon(
        _normalise_polygon_coords(perimeter)
    )
    parts = list(_iter_polygon_geometries(child))
    if child.is_empty or not child.is_valid or child.area <= 0 or not parts or any(p.interiors for p in parts):
        raise ValueError("perimeter must be a valid positive-area Polygon or MultiPolygon without holes")
    min_area = float(min_area)
    if not math.isfinite(min_area) or min_area < 0:
        raise ValueError("min_area must be finite and non-negative")
    if invalid_regions not in ("raise", "drop", "repair"):
        raise ValueError("invalid_regions must be 'raise', 'drop' or 'repair'")
    source_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        source_path, hecras_dir=hecras_dir, ras_object=ras_object,
        ignore_seed_count=True,
    )
    source = HdfBndry.get_refinement_regions(hdf_path)
    properties = {
        "Spacing dx": "spacing_dx", "Spacing dy": "spacing_dy",
        "Shift dx": "shift_dx", "Shift dy": "shift_dy",
        "Perimeter Spacing": "perimeter_spacing",
        "Near Spacing Repeats": "near_repeats", "Far Spacing": "far_spacing",
        "Protection Radius": "protection_radius",
    }
    with h5py.File(hdf_path, "r") as hdf:
        key = "Geometry/2D Flow Area Refinement Regions/Attributes"
        attributes = _coerce_refinement_region_attributes(read_typed(hdf[key])) if key in hdf else []
    output: list[dict[str, Any]] = []
    rows = []
    repairs = []
    for fid, row in source.iterrows():
        region = row.geometry
        parts = list(_iter_polygon_geometries(region))
        repaired = False
        if invalid_regions == "repair" and (
            region.is_empty or not region.is_valid or not parts or any(p.interiors for p in parts)
        ):
            region, evidence = _repair_refinement_polygon(region)
            repairs.append({"source_fid": int(fid), "name": row["Name"], **evidence})
            parts = list(_iter_polygon_geometries(region))
            repaired = True
            if not parts:
                rows.append({
                    "source_fid": int(fid), "name": row["Name"], "status": "dropped",
                    "reason": "degenerate_source_no_positive_area", "source_area": float(row.geometry.area),
                    "retained_area": 0.0, "output_fids": [], "touches_perimeter": False,
                    "below_one_cell_area": False,
                })
                continue
        if region.is_empty or not region.is_valid or not parts or (
            invalid_regions != "repair" and any(p.interiors for p in parts)
        ):
            if invalid_regions == "raise":
                raise ValueError(f"Source region FID {fid} is invalid or has unsupported interior rings")
            reason = "unsupported_interior_rings" if any(p.interiors for p in parts) else "invalid_source_geometry"
            rows.append({
                "source_fid": int(fid), "name": row["Name"], "status": "dropped",
                "reason": reason, "source_area": float(region.area),
                "retained_area": 0.0, "output_fids": [], "touches_perimeter": False,
                "below_one_cell_area": False,
            })
            continue
        native = {target: attributes[fid][field].item() for field, target in properties.items()}
        dx, dy = float(native["spacing_dx"]), float(native["spacing_dy"])
        if not np.isfinite([dx, dy]).all() or min(dx, dy) <= 0:
            raise ValueError(f"Source region FID {fid} has invalid X/Y spacing")
        intersection = region.intersection(child)
        fragments = [p for p in _iter_polygon_geometries(intersection) if p.area > 0]
        kept = [p for p in fragments if p.area >= min_area]
        if any(p.interiors for p in kept):
            if invalid_regions != "repair":
                raise ValueError(f"Clipped region FID {fid} has unsupported interior rings")
            kept = _hole_free_refinement_parts(kept)
        output_fids = []
        for part in kept:
            output_fids.append(len(output))
            output.append({"name": row["Name"], "polygon": part, **native})
        retained = sum(p.area for p in kept)
        if not fragments:
            status, reason = "dropped", "no_polygon_overlap"
        elif not kept:
            status, reason = "dropped", "below_min_area"
        elif region.equals(intersection) and len(kept) == len(fragments):
            status, reason = "kept", "inside_child_perimeter"
        else:
            status, reason = "clipped", "child_perimeter_intersection"
            if len(kept) != len(fragments):
                reason = "intersection_fragments_below_min_area"
        rows.append({
            "source_fid": int(fid), "name": row["Name"], "status": status,
            "reason": ("repaired_source_geometry:" + reason) if repaired else reason, "source_area": float(region.area),
            "retained_area": float(retained), "output_fids": output_fids,
            "touches_perimeter": any(p.intersects(child.boundary) for p in kept),
            "below_one_cell_area": any(p.area < dx * dy for p in kept),
        })
    columns = ["source_fid", "name", "status", "reason", "source_area",
               "retained_area", "output_fids", "touches_perimeter", "below_one_cell_area"]
    report = pd.DataFrame(rows, columns=columns).astype({
        "source_fid": "int64", "source_area": "float64",
        "retained_area": "float64", "touches_perimeter": "bool",
        "below_one_cell_area": "bool",
    })
    report.attrs["repairs"] = repairs
    return output, report

add_refinement_region staticmethod

Python
add_refinement_region(geom_number: Union[str, Number, Path], polygon, spacing_dx: float, spacing_dy: Optional[float] = None, name: str = '', hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, use_rasmapper: Optional[bool] = None) -> int

Create a new refinement region in the compiled geometry HDF.

Refinement regions override the base cell size within their polygon boundaries during mesh generation. They are stored exclusively in HDF — there is no .g## text representation.

On Windows/Wine, real product geometry is authored through RAS Mapper's MeshRegions feature layer and verified with a fresh product reload. Synthetic or cross-platform fixtures use the complete nine-field native HDF schema and polygon-table metadata.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number or path to .g## text file.

required
polygon list[tuple[float, float]] | Polygon

Region boundary as a list of (x, y) tuples, a Shapely Polygon, or any object whose exterior.coords yields (x, y) pairs. The ring is closed automatically if needed.

required
spacing_dx float

Cell spacing in the X direction (project units, e.g. feet or metres).

required
spacing_dy Optional[float]

Stored Y-direction spacing. Defaults to spacing_dx when None. HEC-RAS 6.x stores this value, but its Mapper manual says independent Y spacing is not implemented; use equal X/Y spacing unless qualifying a newer product behavior.

None
name str

Region name stored in the HDF Name field (max 32 bytes UTF-8). Empty string is valid.

''
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance.

None
use_rasmapper Optional[bool]

Force product-backed authoring (True) or the low-level native-schema writer (False). None selects the product path for real geometry on Windows/Wine and retains the low-level path for synthetic fixtures and non-Windows hosts.

None

Returns:

Type Description
int

The 0-based FID of the newly created region.

Raises:

Type Description
ValueError

If polygon has fewer than 3 vertices or spacing_dx is not positive.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def add_refinement_region(
    geom_number: Union[str, Number, Path],
    polygon,
    spacing_dx: float,
    spacing_dy: Optional[float] = None,
    name: str = "",
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    use_rasmapper: Optional[bool] = None,
) -> int:
    """
    Create a new refinement region in the compiled geometry HDF.

    Refinement regions override the base cell size within their
    polygon boundaries during mesh generation.  They are stored
    exclusively in HDF — there is no .g## text representation.

    On Windows/Wine, real product geometry is authored through RAS
    Mapper's ``MeshRegions`` feature layer and verified with a fresh
    product reload. Synthetic or cross-platform fixtures use the complete
    nine-field native HDF schema and polygon-table metadata.

    Args:
        geom_number: Geometry number or path to .g## text file.
        polygon (list[tuple[float, float]] | Polygon): Region boundary as a list of (x, y) tuples,
            a Shapely Polygon, or any object whose
            ``exterior.coords`` yields (x, y) pairs.
            The ring is closed automatically if needed.
        spacing_dx: Cell spacing in the X direction (project
            units, e.g. feet or metres).
        spacing_dy: Stored Y-direction spacing. Defaults to *spacing_dx*
            when ``None``. HEC-RAS 6.x stores this value, but its Mapper
            manual says independent Y spacing is not implemented; use
            equal X/Y spacing unless qualifying a newer product behavior.
        name: Region name stored in the HDF ``Name`` field
            (max 32 bytes UTF-8).  Empty string is valid.
        hecras_dir: Override HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance.
        use_rasmapper: Force product-backed authoring (True) or the
            low-level native-schema writer (False). ``None`` selects the
            product path for real geometry on Windows/Wine and retains the
            low-level path for synthetic fixtures and non-Windows hosts.

    Returns:
        The 0-based FID of the newly created region.

    Raises:
        ValueError: If *polygon* has fewer than 3 vertices or
            *spacing_dx* is not positive.
    """
    import h5py
    import numpy as np

    if spacing_dy is None:
        spacing_dy = spacing_dx
    if spacing_dx <= 0 or spacing_dy <= 0:
        raise ValueError(
            f"Spacing must be positive (got dx={spacing_dx}, dy={spacing_dy})."
        )

    # ── Normalise polygon to (N, 2) float64 array ──────────────
    coords = _normalise_polygon_coords(polygon)
    if len(coords) < 3:
        raise ValueError(
            f"Polygon must have at least 3 vertices (got {len(coords)})."
        )
    # Close the ring if caller didn't
    if not np.allclose(coords[0], coords[-1]):
        coords = np.vstack([coords, coords[:1]])

    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )

    if use_rasmapper is None:
        with h5py.File(str(hdf_path), "r") as hf:
            has_product_polygon_table = (
                "Geometry/2D Flow Areas/Polygon Points" in hf
            )
        use_rasmapper = platform.system() == "Windows" and (
            hecras_dir is not None or has_product_polygon_table
        )
    if use_rasmapper:
        new_fid = _add_refinement_region_via_mapper(
            hdf_path,
            coords,
            float(spacing_dx),
            float(spacing_dy),
            str(name),
            hecras_dir,
        )
        logger.info(
            f"Added RAS Mapper refinement region FID {new_fid} "
            f"(name='{name}', dx={spacing_dx}, dy={spacing_dy}, "
            f"vertices={len(coords)}) → {hdf_path.name}"
        )
        return new_fid

    rr_group_key = "Geometry/2D Flow Area Refinement Regions"
    attr_key = f"{rr_group_key}/Attributes"
    info_key = f"{rr_group_key}/Polygon Info"
    parts_key = f"{rr_group_key}/Polygon Parts"
    points_key = f"{rr_group_key}/Polygon Points"

    # ── Encode name ─────────────────────────────────────────────
    name_bytes = name.encode("utf-8")[:32]
    # Ensure valid UTF-8 after byte truncation
    name_bytes = name_bytes.decode("utf-8", errors="ignore").encode("utf-8")

    attr_dtype = _refinement_region_attribute_dtype()

    n_pts = len(coords)
    new_attr_row = _refinement_region_attribute_rows(
        [
            {
                "name": name_bytes.decode("utf-8"),
                "spacing_dx": spacing_dx,
                "spacing_dy": spacing_dy,
            }
        ]
    )
    coords_xy = np.asarray(coords[:, :2], dtype=np.float64)

    with h5py.File(str(hdf_path), "a") as hf:
        # ── Read existing data (if any) ─────────────────────────
        if attr_key in hf:
            old_attrs = hf[attr_key][:]
            old_info = hf[info_key][:]
            old_parts = hf[parts_key][:] if parts_key in hf else np.empty((0, 2), dtype=np.int32)
            old_points = hf[points_key][:]

            old_attrs = _coerce_refinement_region_attributes(old_attrs)

            if old_points.ndim != 2 or old_points.shape[1] not in (2, 3):
                raise ValueError(
                    "Refinement-region Polygon Points must have two or "
                    f"three columns, got shape {old_points.shape}."
                )
            if old_points.shape[1] == 3:
                old_points = old_points[:, :2]

            existing_n = len(old_attrs)
            total_old_pts = len(old_points)
            total_old_parts = len(old_parts)
        else:
            old_attrs = np.empty(0, dtype=attr_dtype)
            old_info = np.empty((0, 4), dtype=np.int32)
            old_parts = np.empty((0, 2), dtype=np.int32)
            old_points = np.empty((0, 2), dtype=np.float64)
            existing_n = 0
            total_old_pts = 0
            total_old_parts = 0

        new_fid = existing_n

        # ── Build expanded arrays ───────────────────────────────
        merged_attrs = np.concatenate([old_attrs, new_attr_row])

        new_info_row = np.array(
            [[total_old_pts, n_pts, total_old_parts, 1]],
            dtype=np.int32,
        )
        merged_info = np.vstack([old_info, new_info_row]) if existing_n > 0 else new_info_row

        new_parts_row = np.array([[0, n_pts]], dtype=np.int32)
        merged_parts = np.vstack([old_parts, new_parts_row]) if total_old_parts > 0 else new_parts_row

        merged_points = (
            np.vstack([old_points, coords_xy])
            if total_old_pts > 0
            else coords_xy
        )

        # ── Delete-and-recreate (matches RASDecomp pattern) ─────
        for key in (attr_key, info_key, parts_key, points_key):
            if key in hf:
                del hf[key]

        _create_hdf_dataset(hf, attr_key, merged_attrs)
        _create_hdf_dataset(hf, info_key, merged_info)
        _create_hdf_dataset(hf, parts_key, merged_parts)
        _create_hdf_dataset(hf, points_key, merged_points)
        _set_refinement_region_dataset_metadata(hf, rr_group_key)

    logger.info(
        f"Added refinement region FID {new_fid} "
        f"(name='{name}', dx={spacing_dx}, dy={spacing_dy}, "
        f"vertices={n_pts}) → {hdf_path.name}"
    )
    return new_fid

add_flowline_refinement_regions staticmethod

Python
add_flowline_refinement_regions(geom_number: Union[str, Number, Path], flowlines, buffer_width: float, spacing_dx: Optional[float] = None, spacing_dy: Optional[float] = None, name_prefix: str = 'FlowlineRR', name_column: Optional[str] = None, simplify_tolerance: Optional[float] = None, preserve_topology: bool = True, trim_geometries=None, trim_distance: float = 0.0, trim_hook: Optional[Callable] = None, trim_overlaps: bool = False, cap_style: Union[str, int] = 'flat', join_style: Union[str, int] = 'round', mitre_limit: float = 5.0, min_area: float = 0.0, project_crs: Optional[object] = None, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> list[dict]

Buffer channel flowlines into HEC-RAS refinement regions.

This is the high-level API equivalent of the HEC-RAS Mapper workflow that filters flowlines, buffers them to refinement-region polygons, and sets the region X/Y cell spacing to the selected buffer width. The final write still goes through add_refinement_region() so the generated HDF datasets use the same schema as the lower-level helper.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number, .g## text path, or resolvable geometry selector. A current compiled .g##.hdf workspace must exist.

required
flowlines GeoDataFrame | GeoSeries | LineString | MultiLineString | Iterable

GeoDataFrame, GeoSeries, LineString, MultiLineString, or iterable of shapely line geometries. GeoDataFrame inputs are reprojected to the project CRS when both CRS values are known; inputs without a CRS are assumed to already be in project CRS.

required
buffer_width float

Distance used to buffer each flowline, in project units. Defaults spacing_dx and spacing_dy to this value.

required
spacing_dx Optional[float]

Refinement-region X spacing. Defaults to buffer_width.

None
spacing_dy Optional[float]

Refinement-region Y spacing. Defaults to spacing_dx.

None
name_prefix str

Prefix used when name_column is not supplied.

'FlowlineRR'
name_column Optional[str]

Optional GeoDataFrame column for region names.

None
simplify_tolerance Optional[float]

Optional line simplification tolerance applied before buffering.

None
preserve_topology bool

Passed to shapely simplify().

True
trim_geometries GeoDataFrame | BaseGeometry | Iterable

Optional GeoDataFrame, geometry, or iterable of geometries to subtract from generated buffers. Use this for bridge, confluence, levee, or other overlap avoidance zones.

None
trim_distance float

Optional buffer distance applied to trim_geometries before subtraction.

0.0
trim_hook Optional[Callable]

Optional callable f(polygon, line, source) that can return a custom trimmed polygon, MultiPolygon, or None to skip a flowline. source contains index and properties from the input record.

None
trim_overlaps bool

If True, subtract previously-created flowline regions from later regions. This is order-dependent but useful for quickly removing confluence overlaps.

False
cap_style Union[str, int]

Shapely buffer cap style: "round", "flat", or "square"; integer shapely style values are also accepted.

'flat'
join_style Union[str, int]

Shapely buffer join style: "round", "mitre" / "miter", or "bevel".

'round'
mitre_limit float

Shapely buffer mitre limit.

5.0
min_area float

Skip trimmed polygon parts smaller than this area.

0.0
project_crs Optional[object]

Optional CRS override for GeoDataFrame reprojection. If omitted, the method attempts to read the project CRS from the compiled geometry HDF/RASMapper files when needed.

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory for HDF resolution consistency with other GeomMesh methods.

None
ras_object RasPrj

Optional RasPrj instance.

None

Returns:

Type Description
list[dict]

List of dictionaries mapping each written region to its HDF FID,

list[dict]

stored name, source feature index, spacing, buffer width, and area.

Raises:

Type Description
ValueError

If spacing/buffer inputs are non-positive, if flowlines contains non-line geometries, or if name_column is requested but absent.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def add_flowline_refinement_regions(
    geom_number: Union[str, Number, Path],
    flowlines,
    buffer_width: float,
    spacing_dx: Optional[float] = None,
    spacing_dy: Optional[float] = None,
    name_prefix: str = "FlowlineRR",
    name_column: Optional[str] = None,
    simplify_tolerance: Optional[float] = None,
    preserve_topology: bool = True,
    trim_geometries=None,
    trim_distance: float = 0.0,
    trim_hook: Optional[Callable] = None,
    trim_overlaps: bool = False,
    cap_style: Union[str, int] = "flat",
    join_style: Union[str, int] = "round",
    mitre_limit: float = 5.0,
    min_area: float = 0.0,
    project_crs: Optional[object] = None,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> list[dict]:
    """
    Buffer channel flowlines into HEC-RAS refinement regions.

    This is the high-level API equivalent of the HEC-RAS Mapper workflow
    that filters flowlines, buffers them to refinement-region polygons,
    and sets the region X/Y cell spacing to the selected buffer width.
    The final write still goes through ``add_refinement_region()`` so the
    generated HDF datasets use the same schema as the lower-level helper.

    Args:
        geom_number: Geometry number, .g## text path, or resolvable geometry
            selector.  A current compiled .g##.hdf workspace must exist.
        flowlines (GeoDataFrame | GeoSeries | LineString | MultiLineString | Iterable): GeoDataFrame, GeoSeries, LineString, MultiLineString,
            or iterable of shapely line geometries. GeoDataFrame inputs are
            reprojected to the project CRS when both CRS values are known;
            inputs without a CRS are assumed to already be in project CRS.
        buffer_width: Distance used to buffer each flowline, in project
            units. Defaults ``spacing_dx`` and ``spacing_dy`` to this value.
        spacing_dx: Refinement-region X spacing. Defaults to
            ``buffer_width``.
        spacing_dy: Refinement-region Y spacing. Defaults to
            ``spacing_dx``.
        name_prefix: Prefix used when ``name_column`` is not supplied.
        name_column: Optional GeoDataFrame column for region names.
        simplify_tolerance: Optional line simplification tolerance applied
            before buffering.
        preserve_topology: Passed to shapely ``simplify()``.
        trim_geometries (GeoDataFrame | BaseGeometry | Iterable, optional): Optional GeoDataFrame, geometry, or iterable of
            geometries to subtract from generated buffers. Use this for
            bridge, confluence, levee, or other overlap avoidance zones.
        trim_distance: Optional buffer distance applied to
            ``trim_geometries`` before subtraction.
        trim_hook: Optional callable ``f(polygon, line, source)`` that can
            return a custom trimmed polygon, MultiPolygon, or ``None`` to
            skip a flowline. ``source`` contains ``index`` and
            ``properties`` from the input record.
        trim_overlaps: If True, subtract previously-created flowline
            regions from later regions. This is order-dependent but useful
            for quickly removing confluence overlaps.
        cap_style: Shapely buffer cap style: ``"round"``, ``"flat"``, or
            ``"square"``; integer shapely style values are also accepted.
        join_style: Shapely buffer join style: ``"round"``, ``"mitre"`` /
            ``"miter"``, or ``"bevel"``.
        mitre_limit: Shapely buffer mitre limit.
        min_area: Skip trimmed polygon parts smaller than this area.
        project_crs: Optional CRS override for GeoDataFrame reprojection.
            If omitted, the method attempts to read the project CRS from
            the compiled geometry HDF/RASMapper files when needed.
        hecras_dir: Override HEC-RAS installation directory for HDF
            resolution consistency with other ``GeomMesh`` methods.
        ras_object (RasPrj, optional): Optional RasPrj instance.

    Returns:
        List of dictionaries mapping each written region to its HDF FID,
        stored name, source feature index, spacing, buffer width, and area.

    Raises:
        ValueError: If spacing/buffer inputs are non-positive, if
            ``flowlines`` contains non-line geometries, or if
            ``name_column`` is requested but absent.
    """
    if buffer_width <= 0:
        raise ValueError(f"buffer_width must be positive (got {buffer_width}).")
    if spacing_dx is None:
        spacing_dx = buffer_width
    if spacing_dy is None:
        spacing_dy = spacing_dx
    if spacing_dx <= 0 or spacing_dy <= 0:
        raise ValueError(
            f"Spacing must be positive (got dx={spacing_dx}, dy={spacing_dy})."
        )
    if simplify_tolerance is not None and simplify_tolerance < 0:
        raise ValueError("simplify_tolerance must be non-negative.")
    if min_area < 0:
        raise ValueError("min_area must be non-negative.")

    target_crs = project_crs
    if target_crs is None and (
        _spatial_input_crs(flowlines) is not None
        or _spatial_input_crs(trim_geometries) is not None
    ):
        try:
            hdf_path = _resolve_geom_hdf_path(
                geom_number,
                hecras_dir=hecras_dir,
                ras_object=ras_object,
            )
            from ..hdf.HdfBase import HdfBase

            target_crs = HdfBase.get_projection(hdf_path)
        except Exception as exc:
            reraise_required(exc)
            logger.debug(f"Could not read project CRS for flowline regions: {exc}")
        if target_crs is None:
            logger.warning(
                "Flowline or trim geometries have a CRS, but the project CRS "
                "could not be determined. Coordinates will be used as-is."
            )

    records = _coerce_geospatial_records(flowlines, target_crs=target_crs)
    if not records:
        raise ValueError("flowlines is empty.")

    cap_value = _buffer_style_value(cap_style, _BUFFER_CAP_STYLES, "cap_style")
    join_value = _buffer_style_value(join_style, _BUFFER_JOIN_STYLES, "join_style")
    trim_union = _prepare_trim_union(
        trim_geometries,
        target_crs=target_crs,
        trim_distance=trim_distance,
    )

    if trim_overlaps:
        from shapely.ops import unary_union
    else:
        unary_union = None

    created_polygons = []
    mappings: list[dict] = []
    source_ordinal = 0

    for record in records:
        source_index = record["index"]
        properties = record["properties"]
        line = _ensure_line_geometry(record["geometry"], source_index)
        if line.is_empty:
            continue

        source_ordinal += 1
        if simplify_tolerance is not None and simplify_tolerance > 0:
            line = line.simplify(
                simplify_tolerance,
                preserve_topology=preserve_topology,
            )
            if line.is_empty:
                continue

        region_geom = line.buffer(
            buffer_width,
            cap_style=cap_value,
            join_style=join_value,
            mitre_limit=mitre_limit,
        )
        if trim_union is not None and not region_geom.is_empty:
            region_geom = region_geom.difference(trim_union)

        if trim_hook is not None and not region_geom.is_empty:
            source = {"index": source_index, "properties": properties}
            region_geom = trim_hook(region_geom, line, source)
            if region_geom is None:
                continue

        if trim_overlaps and created_polygons and not region_geom.is_empty:
            region_geom = region_geom.difference(unary_union(created_polygons))

        polygons = [
            polygon for polygon in _iter_polygon_geometries(region_geom)
            if polygon.area >= min_area
        ]
        if not polygons:
            continue

        if name_column is not None:
            if name_column not in properties:
                raise ValueError(f"name_column {name_column!r} not found.")
            raw_name = properties.get(name_column)
            base_name = str(raw_name).strip() if raw_name is not None else ""
            if not base_name:
                base_name = f"{name_prefix}_{source_ordinal:03d}"
        else:
            base_name = f"{name_prefix}_{source_ordinal:03d}"

        part_count = len(polygons)
        for part_index, polygon in enumerate(polygons):
            if getattr(polygon, "interiors", None) and len(polygon.interiors):
                logger.warning(
                    "Flowline refinement region trim produced an interior "
                    "hole for source %r; add_refinement_region() writes the "
                    "exterior ring only. Use a trim_hook that returns split "
                    "hole-free polygons if the hole must be preserved.",
                    source_index,
                )
            region_name = (
                base_name
                if part_count == 1
                else f"{base_name}_{part_index + 1}"
            )
            fid = GeomMesh.add_refinement_region(
                geom_number,
                polygon,
                spacing_dx=spacing_dx,
                spacing_dy=spacing_dy,
                name=region_name,
                hecras_dir=hecras_dir,
                ras_object=ras_object,
            )
            created_polygons.append(polygon)
            mappings.append({
                "fid": fid,
                "name": _truncate_ras_name(region_name),
                "source_index": source_index,
                "part_index": part_index,
                "spacing_dx": float(spacing_dx),
                "spacing_dy": float(spacing_dy),
                "buffer_width": float(buffer_width),
                "area": float(polygon.area),
            })

    logger.info("Added %s flowline refinement regions", len(mappings))
    return mappings

compile_geometry staticmethod

Python
compile_geometry(geom_number: Union[str, Number, Path], hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> Path

Disabled compatibility shim for .g## text -> .g##.hdf generation.

ras-commander cannot compile a plain-text geometry file into its compiled HDF representation without full HEC-RAS/Ras.exe behavior. RasMapperLib's CompleteGeometryCommand only completes existing HDF files; it is not a text geometry compiler.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01", 1) or path to .g## text file.

required
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None

Returns:

Type Description
Path

Never returns successfully.

Raises:

Type Description
FileNotFoundError

If geometry file cannot be resolved.

RuntimeError

Always, because this path is unavailable.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def compile_geometry(
    geom_number: Union[str, Number, Path],
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> Path:
    """
    Disabled compatibility shim for .g## text -> .g##.hdf generation.

    ras-commander cannot compile a plain-text geometry file into its
    compiled HDF representation without full HEC-RAS/Ras.exe behavior.
    RasMapperLib's CompleteGeometryCommand only completes existing HDF
    files; it is not a text geometry compiler.

    Args:
        geom_number: Geometry number ("01", 1) or path to .g## text file.
        hecras_dir: Override HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance for multi-project support.

    Returns:
        Never returns successfully.

    Raises:
        FileNotFoundError: If geometry file cannot be resolved.
        RuntimeError: Always, because this path is unavailable.
    """
    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = geom_text_path.with_suffix(geom_text_path.suffix + ".hdf")
    raise RuntimeError(
        _geometry_hdf_unavailable_message(
            geom_text_path,
            hdf_path,
            "not generated by ras-commander",
        )
    )

get_geometry_association staticmethod

Python
get_geometry_association(geom_number: Union[str, Number, Path], hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, resolve_paths: bool = True) -> dict

Read terrain and classification associations from a geometry HDF.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number, .g## text path, or .g##.hdf path. Text inputs require an existing current .g##.hdf.

required
hecras_dir Optional[Union[str, Path]]

Kept for API symmetry; no DLLs are loaded here.

None
ras_object RasPrj

Optional RasPrj instance for geometry-number lookup.

None
resolve_paths bool

If True, return absolute paths resolved relative to the geometry HDF. If False, return the raw HDF attribute text.

True

Returns:

Type Description
dict

Dict with keys terrain_hdf_path, landcover_hdf_path,

dict

infiltration_hdf_path, sediment_soils_hdf_path, matching

dict

*_layer_name keys, and si_units.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def get_geometry_association(
    geom_number: Union[str, Number, Path],
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    resolve_paths: bool = True,
) -> dict:
    """
    Read terrain and classification associations from a geometry HDF.

    Args:
        geom_number: Geometry number, .g## text path, or .g##.hdf path.
            Text inputs require an existing current .g##.hdf.
        hecras_dir: Kept for API symmetry; no DLLs are loaded here.
        ras_object (RasPrj, optional): Optional RasPrj instance for geometry-number lookup.
        resolve_paths: If True, return absolute paths resolved relative to
            the geometry HDF. If False, return the raw HDF attribute text.

    Returns:
        Dict with keys ``terrain_hdf_path``, ``landcover_hdf_path``,
        ``infiltration_hdf_path``, ``sediment_soils_hdf_path``, matching
        ``*_layer_name`` keys, and ``si_units``.
    """
    hdf_path = _resolve_geom_hdf_path(
        geom_number,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )
    hdf_path = _safe_resolve_path(hdf_path)
    return _read_geometry_association(hdf_path, resolve_paths=resolve_paths)

set_geometry_association staticmethod

Python
set_geometry_association(geom_number: Union[str, Number, Path], terrain_hdf_path: Optional[Union[str, Path]] = None, landcover_hdf_path: Optional[Union[str, Path]] = None, infiltration_hdf_path: Optional[Union[str, Path]] = None, sediment_soils_hdf_path: Optional[Union[str, Path]] = None, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, validate: bool = True) -> Path

Associate terrain / classification layers to an existing geometry HDF.

This wraps RasMapperLib's SetGeometryAssociationCommand and writes attributes under /Geometry in the compiled .g##.hdf. It does not create or refresh a missing geometry HDF.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number, .g## text path, or .g##.hdf path. Text inputs require an existing current .g##.hdf.

required
terrain_hdf_path Optional[Union[str, Path]]

Terrain HDF to associate.

None
landcover_hdf_path Optional[Union[str, Path]]

Land-cover / Manning's n HDF.

None
infiltration_hdf_path Optional[Union[str, Path]]

Infiltration HDF.

None
sediment_soils_hdf_path Optional[Union[str, Path]]

Sediment bed-material soils HDF. This is the HEC-RAS SedimentSoilsFilename slot, not the hydrologic soils layer used to build infiltration data.

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for geometry-number lookup.

None
validate bool

Re-read /Geometry attributes after execution and verify supplied paths were persisted.

True

Returns:

Type Description
Path

Path to the existing geometry HDF that was updated.

Raises:

Type Description
ValueError

If no association paths are supplied.

FileNotFoundError

If any supplied artifact is missing.

RuntimeError

If the HDF is missing /Geometry, execution fails, or validation does not find the expected attributes.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def set_geometry_association(
    geom_number: Union[str, Number, Path],
    terrain_hdf_path: Optional[Union[str, Path]] = None,
    landcover_hdf_path: Optional[Union[str, Path]] = None,
    infiltration_hdf_path: Optional[Union[str, Path]] = None,
    sediment_soils_hdf_path: Optional[Union[str, Path]] = None,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    validate: bool = True,
) -> Path:
    """
    Associate terrain / classification layers to an existing geometry HDF.

    This wraps RasMapperLib's ``SetGeometryAssociationCommand`` and writes
    attributes under ``/Geometry`` in the compiled ``.g##.hdf``. It does
    not create or refresh a missing geometry HDF.

    Args:
        geom_number: Geometry number, .g## text path, or .g##.hdf path.
            Text inputs require an existing current .g##.hdf.
        terrain_hdf_path: Terrain HDF to associate.
        landcover_hdf_path: Land-cover / Manning's n HDF.
        infiltration_hdf_path: Infiltration HDF.
        sediment_soils_hdf_path: Sediment bed-material soils HDF. This is
            the HEC-RAS ``SedimentSoilsFilename`` slot, not the hydrologic
            soils layer used to build infiltration data.
        hecras_dir: Override HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance for geometry-number lookup.
        validate: Re-read ``/Geometry`` attributes after execution and
            verify supplied paths were persisted.

    Returns:
        Path to the existing geometry HDF that was updated.

    Raises:
        ValueError: If no association paths are supplied.
        FileNotFoundError: If any supplied artifact is missing.
        RuntimeError: If the HDF is missing /Geometry, execution fails, or
            validation does not find the expected attributes.
    """
    supplied = {
        "terrain_hdf_path": terrain_hdf_path,
        "landcover_hdf_path": landcover_hdf_path,
        "infiltration_hdf_path": infiltration_hdf_path,
        "sediment_soils_hdf_path": sediment_soils_hdf_path,
    }
    if all(path is None for path in supplied.values()):
        raise ValueError("Provide at least one geometry association path.")

    hdf_path = _resolve_geom_hdf_path(
        geom_number,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )
    hdf_path = _safe_resolve_path(hdf_path)
    _validate_geometry_hdf_path(hdf_path)

    resolved_paths = {}
    for key, path_value in supplied.items():
        if path_value is None:
            continue
        resolved_path = _safe_resolve_path(Path(path_value))
        if not resolved_path.exists():
            raise FileNotFoundError(
                f"Association artifact not found for {key}: {resolved_path}"
            )
        resolved_paths[key] = resolved_path

    prior_association = _read_geometry_association(
        hdf_path,
        resolve_paths=False,
    )

    _load_dlls(hecras_dir)
    from RasMapperLib.Scripting import SetGeometryAssociationCommand  # type: ignore

    cmd = SetGeometryAssociationCommand()
    cmd.GeometryFilename = str(hdf_path)
    for key, resolved_path in resolved_paths.items():
        command_property = _GEOMETRY_ASSOCIATION_FIELDS[key]["command_property"]
        setattr(cmd, command_property, str(resolved_path))

    try:
        cmd.Execute(None)
    except Exception as exc:
        raise RuntimeError(
            f"SetGeometryAssociationCommand failed for {hdf_path.name}: {exc}"
        ) from exc

    if validate:
        _validate_geometry_association(hdf_path, resolved_paths)
        _validate_omitted_geometry_associations(
            hdf_path,
            prior_association,
            set(resolved_paths),
        )

    logger.info(
        "Updated geometry associations on %s: %s",
        hdf_path.name,
        ", ".join(sorted(resolved_paths)),
    )
    return hdf_path

compute_property_tables staticmethod

Python
compute_property_tables(geom_number: Union[str, Number, Path], mesh_name: Optional[str] = None, mesh_index: int = 0, force: bool = True, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None) -> bool

Compute 2D hydraulic property tables for a geometry.

Triggers RAS Mapper's property table computation: face profiles, Manning's n assignment, face hydraulic tables, and cell properties. Requires a terrain layer associated with the geometry.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01", 1) or path to .g## text file.

required
mesh_name Optional[str]

2D flow area name. Auto-detected if only one exists.

None
mesh_index int

Index of the 2D flow area (default 0).

0
force bool

Force recomputation even if tables are up-to-date.

True
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None

Returns:

Type Description
bool

True if property tables were computed successfully.

Raises:

Type Description
FileNotFoundError

If geometry file cannot be resolved.

RuntimeError

If terrain is missing or computation fails.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def compute_property_tables(
    geom_number: Union[str, Number, Path],
    mesh_name: Optional[str] = None,
    mesh_index: int = 0,
    force: bool = True,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
) -> bool:
    """
    Compute 2D hydraulic property tables for a geometry.

    Triggers RAS Mapper's property table computation: face profiles,
    Manning's n assignment, face hydraulic tables, and cell properties.
    Requires a terrain layer associated with the geometry.

    Args:
        geom_number: Geometry number ("01", 1) or path to .g## text file.
        mesh_name: 2D flow area name. Auto-detected if only one exists.
        mesh_index: Index of the 2D flow area (default 0).
        force: Force recomputation even if tables are up-to-date.
        hecras_dir: Override HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance for multi-project support.

    Returns:
        True if property tables were computed successfully.

    Raises:
        FileNotFoundError: If geometry file cannot be resolved.
        RuntimeError: If terrain is missing or computation fails.
    """
    geom_text_path = _resolve_geom_text_path(geom_number, ras_object)

    _load_dlls(hecras_dir)

    hdf_path = _ensure_hdf(
        geom_text_path,
        hecras_dir=hecras_dir,
        ras_object=ras_object,
    )

    association_diagnostic = landcover_association_diagnostic(hdf_path)
    if association_diagnostic:
        logger.warning(association_diagnostic)

    ns = _imports()
    geom = ns["RASGeometry"](str(hdf_path))
    d2fa = geom.D2FlowArea

    if d2fa.FeatureCount() == 0:
        raise RuntimeError(f"No 2D flow areas in {geom_text_path.name}")

    if mesh_name is not None:
        fid = d2fa.GetFeatureByName(mesh_name)
        if fid == -1:
            raise RuntimeError(
                f"2D flow area '{mesh_name}' not found in "
                f"{geom_text_path.name}"
            )
    else:
        fid = mesh_index
        mesh_name = d2fa.GetFeatureName(fid)

    terrain = geom.Terrain
    if terrain is None:
        raise RuntimeError(
            f"No terrain associated with {geom_text_path.name}. "
            f"Associate a terrain in RAS Mapper before computing "
            f"property tables."
        )

    if force:
        try:
            result = d2fa.CreatePropertyTables(fid, None, False, None)
        except TypeError:
            # HEC-RAS 6.0-6.2: no perTaskReporters parameter.
            result = d2fa.CreatePropertyTables(fid, None, False)
    else:
        result = d2fa.EnsurePropertyTables(False, True, False, None)

    if result:
        logger.info(
            f"Property tables computed for '{mesh_name}' "
            f"in {geom_text_path.name}"
        )
    else:
        logger.warning(
            f"Property table computation returned False for "
            f"'{mesh_name}' in {geom_text_path.name}"
        )

    return bool(result)

generate_computation_points staticmethod

Python
generate_computation_points(geom_number: Union[str, Number, Path], mesh_name: Optional[str] = None, mesh_index: int = 0, cell_size: Optional[float] = None, hecras_dir: Optional[Union[str, Path]] = None, ras_object=None, repair_generated_points: bool = False, min_face_length_ratio: float = 0.05, evidence_callback: Optional[Callable[[str, Any], None]] = None) -> 'MeshResult'

Generate initial 2D computation points for a 2D flow area directly from the authored .g## perimeter text — no pre-existing compiled .g##.hdf required.

This is the greenfield bootstrap for a brand-new 2D flow area. It builds a RasMapperLib perimeter Polygon from the Storage Area Surface Line= block and runs PointGenerator.GeneratePoints (RASMapper's "Generate Computation Points on Regular Interval"), then writes the resulting cell centers into the Storage Area 2D Points= block of the .g## text. HEC-RAS builds the full Voronoi mesh from those points during geometry preprocessing (e.g. RasCmdr.compute_plan(force_geompre=True)).

Unlike :meth:generate, this does NOT load a compiled HDF and is therefore the path to use before any mesh exists. It is breakline-unaware (regular-interval grid clipped to the perimeter); use :meth:generate for breakline-aware regeneration once a compiled HDF exists.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01", 1) or path to .g## text file.

required
mesh_name Optional[str]

Name of the 2D flow area (None -> use mesh_index).

None
mesh_index int

0-based 2D-area index when mesh_name is None.

0
cell_size Optional[float]

Regular-interval spacing in project units. When None, it is read from Storage Area Point Generation Data in the text.

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory (for RasMapperLib).

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None
repair_generated_points bool

Inspect native bootstrap topology and remove only recorded, index-matched seeds implicated by perimeter or fewer-than-three-face errors, with at most five repairs. The authored perimeter is never changed. Default preserves legacy point generation. Final Ras.exe compile and QA remain required.

False
min_face_length_ratio float

Dimensionless native preview setting; supply the persisted geometry setting when enabling repairs.

0.05
evidence_callback Optional[Callable[[str, Any], None]]

Observer receiving each bootstrap_seed_repair plan before any text mutation. Observer errors abort generation and are reported in the returned MeshResult error message.

None

Returns:

Type Description
'MeshResult'

MeshResult with status, mesh_name, cell_count (= number of generated

'MeshResult'

computation points), and geom_text_path. Points are written to the

'MeshResult'

.g## text; the full mesh is produced by the subsequent HEC-RAS

'MeshResult'

geometry preprocess. Successful bootstrap returns status="complete"

'MeshResult'

and operation="computation_points" and is truthy. This means points

'MeshResult'

were generated, not that a compiled mesh or hydraulically accepted

'MeshResult'

model exists.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def generate_computation_points(
    geom_number: Union[str, Number, Path],
    mesh_name: Optional[str] = None,
    mesh_index: int = 0,
    cell_size: Optional[float] = None,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object=None,
    repair_generated_points: bool = False,
    min_face_length_ratio: float = 0.05,
    evidence_callback: Optional[Callable[[str, Any], None]] = None,
) -> "MeshResult":
    """
    Generate initial 2D computation points for a 2D flow area directly from
    the authored .g## perimeter text — **no pre-existing compiled .g##.hdf
    required**.

    This is the greenfield bootstrap for a brand-new 2D flow area. It builds
    a RasMapperLib perimeter ``Polygon`` from the ``Storage Area Surface
    Line=`` block and runs ``PointGenerator.GeneratePoints`` (RASMapper's
    "Generate Computation Points on Regular Interval"), then writes the
    resulting cell centers into the ``Storage Area 2D Points=`` block of the
    .g## text. HEC-RAS builds the full Voronoi mesh from those points during
    geometry preprocessing (e.g. ``RasCmdr.compute_plan(force_geompre=True)``).

    Unlike :meth:`generate`, this does NOT load a compiled HDF and is
    therefore the path to use *before* any mesh exists. It is
    breakline-unaware (regular-interval grid clipped to the perimeter); use
    :meth:`generate` for breakline-aware regeneration once a compiled HDF
    exists.

    Args:
        geom_number: Geometry number ("01", 1) or path to .g## text file.
        mesh_name: Name of the 2D flow area (None -> use mesh_index).
        mesh_index: 0-based 2D-area index when mesh_name is None.
        cell_size: Regular-interval spacing in project units. When None, it
            is read from ``Storage Area Point Generation Data`` in the text.
        hecras_dir: Override HEC-RAS installation directory (for RasMapperLib).
        ras_object (RasPrj, optional): Optional RasPrj instance for multi-project support.
        repair_generated_points: Inspect native bootstrap topology and remove
            only recorded, index-matched seeds implicated by perimeter or
            fewer-than-three-face errors, with at most five repairs. The
            authored perimeter is never changed. Default preserves legacy
            point generation. Final Ras.exe compile and QA remain required.
        min_face_length_ratio: Dimensionless native preview setting; supply
            the persisted geometry setting when enabling repairs.
        evidence_callback: Observer receiving each bootstrap_seed_repair
            plan before any text mutation. Observer errors abort generation
            and are reported in the returned MeshResult error message.

    Returns:
        MeshResult with status, mesh_name, cell_count (= number of generated
        computation points), and geom_text_path. Points are written to the
        .g## text; the full mesh is produced by the subsequent HEC-RAS
        geometry preprocess. Successful bootstrap returns status="complete"
        and operation="computation_points" and is truthy. This means points
        were generated, not that a compiled mesh or hydraulically accepted
        model exists.
    """
    import numpy as np
    from .GeomStorage import GeomStorage

    _load_dlls(hecras_dir)
    ns = _imports()
    geom_path = _resolve_geom_text_path(geom_number, ras_object)

    result = MeshResult(
        mesh_name=mesh_name or f"<index {mesh_index}>",
        status="error",
        geom_text_path=str(geom_path),
        operation="computation_points",
    )

    try:
        # ── Read the 2D-area perimeter ring from the .g## text ──────────
        gdf = GeomStorage.get_storage_area_polygons(geom_path, exclude_2d=False)
        twod = gdf[gdf["is_2d"]] if "is_2d" in gdf.columns else gdf
        if mesh_name is not None:
            twod = twod[twod["Name"] == mesh_name]
        elif 0 <= mesh_index < len(twod):
            twod = twod.iloc[mesh_index:mesh_index + 1]
        if len(twod) == 0:
            result.error_message = (
                f"No matching 2D flow area in {geom_path.name} "
                f"(mesh_name={mesh_name!r}, mesh_index={mesh_index})"
            )
            return result
        row = twod.iloc[0]
        area = mesh_name or str(row["Name"])
        result.mesh_name = area
        poly = row.geometry
        if poly is None or not hasattr(poly, "exterior"):
            result.error_message = f"2D area '{area}' has no perimeter polygon"
            return result
        coords = list(poly.exterior.coords)

        # ── Resolve cell size (arg > text point-generation data) ───────
        if cell_size is None:
            cell_size = _read_cell_size_from_text(geom_path, mesh_name=area)
        if cell_size is None or float(cell_size) <= 0:
            result.error_message = (
                "cell_size not provided and not found in 'Storage Area "
                "Point Generation Data' of the geometry text"
            )
            return result
        cell_size = float(cell_size)

        # ── Build a RasMapperLib perimeter Polygon from the coords ─────
        from RasMapperLib import PointMs as _PointMs, Polygon as _Polygon  # type: ignore
        from RasMapperLib import PointM as _PointM  # type: ignore
        pts = _PointMs()
        for x, y in coords:
            pts.Add(_PointM(float(x), float(y)))
        perim = _Polygon(pts)

        # ── Generate computation points (float32-safe GeneratePoints) ──
        seeds = _generate_seeds_safe(perim, cell_size, ns)
        if repair_generated_points:
            from .GeomMeshRepair import GeomMeshRepair
            for repair_attempt in range(5):
                preview = _compute_mesh(perim, seeds, None, min_face_length_ratio, ns)
                repair = GeomMeshRepair.plan_native_seed_removal(preview, seeds)
                indexes = {p["generated_point_index"] for p in repair["removed_points"]}
                if not indexes:
                    break
                repair["attempt"] = repair_attempt
                if evidence_callback is not None:
                    evidence_callback("bootstrap_seed_repair", repair)
                seeds, removed = _remove_seed_indexes(seeds, indexes, ns)
                result.fixes_applied.append(f"Bootstrap:native-generated-seed-removal(-{removed}pts)")
        n_pts = int(seeds.Count)
        if n_pts <= 0:
            result.status = "exception"
            result.error_message = "PointGenerator returned no computation points"
            return result
        centers = np.empty((n_pts, 2), dtype=float)
        for i in range(n_pts):
            p = seeds.PointM(i)
            centers[i, 0] = float(p.X)
            centers[i, 1] = float(p.Y)

        # ── Write points into the .g## text (sole persistent output) ───
        _patch_text_seeds(geom_path, centers, mesh_name=area)

        result.status = "complete"
        result.cell_count = n_pts
        logger.info(
            f"Generated {n_pts} computation points for 2D area '{area}' "
            f"(cell_size={cell_size:g}) in {geom_path.name}; run HEC-RAS "
            f"geometry preprocessing to build the mesh."
        )
        return result
    except Exception as exc:  # noqa: BLE001
        result.status = "exception"
        result.error_message = f"{type(exc).__name__}: {exc}"
        logger.error(
            f"[{result.mesh_name}] generate_computation_points failed: {exc}"
        )
        return result

get_grid_anchor staticmethod

Python
get_grid_anchor(geometry: Union[str, Number, Path], mesh_name: Optional[str] = None, mesh_index: int = 0, ras_object: Optional[RasPrj] = None) -> GridAnchor

Return the regular-grid lattice point of a compiled 2D flow area.

RAS Mapper starts a 2D area's regular computation-point grid half a cell inside the area's bounding box: at (min x + dx/2, max y - dy/2) of the stored perimeter, then one point every Spacing dx / Spacing dy. This reads that point and the spacing from the compiled geometry HDF. Pass the result to GeomMesh.generate(grid_anchor=...) so a child or ensemble member cut from this area re-meshes on the same lattice.

Read-only; nothing is loaded through .NET, so it runs on any platform with h5py.

Parameters:

Name Type Description Default
geometry Union[str, Number, Path]

Compiled geometry HDF path (.g##.hdf), geometry text path (.hdf is appended), or geometry number.

required
mesh_name Optional[str]

2D flow area name (None = use mesh_index).

None
mesh_index int

0-based 2D-area index when mesh_name is None.

0
ras_object RasPrj

RasPrj instance for geometry-number lookup; None uses the global project.

None

Returns:

Type Description
GridAnchor

GridAnchor in the geometry's CRS and horizontal units, with

GridAnchor

source naming the HDF file and area.

Raises:

Type Description
FileNotFoundError

The geometry or its compiled HDF is missing.

ValueError

The area is missing or has no positive spacing.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def get_grid_anchor(
    geometry: Union[str, Number, Path],
    mesh_name: Optional[str] = None,
    mesh_index: int = 0,
    ras_object: Optional[RasPrj] = None,
) -> GridAnchor:
    """Return the regular-grid lattice point of a compiled 2D flow area.

    RAS Mapper starts a 2D area's regular computation-point grid half a
    cell inside the area's bounding box: at ``(min x + dx/2, max y - dy/2)``
    of the stored perimeter, then one point every ``Spacing dx`` /
    ``Spacing dy``. This reads that point and the spacing from the
    compiled geometry HDF. Pass the result to
    ``GeomMesh.generate(grid_anchor=...)`` so a child or ensemble member
    cut from this area re-meshes on the same lattice.

    Read-only; nothing is loaded through .NET, so it runs on any
    platform with h5py.

    Args:
        geometry: Compiled geometry HDF path (``.g##.hdf``), geometry
            text path (``.hdf`` is appended), or geometry number.
        mesh_name: 2D flow area name (None = use ``mesh_index``).
        mesh_index: 0-based 2D-area index when ``mesh_name`` is None.
        ras_object (RasPrj, optional): RasPrj instance for
            geometry-number lookup; None uses the global project.

    Returns:
        GridAnchor in the geometry's CRS and horizontal units, with
        ``source`` naming the HDF file and area.

    Raises:
        FileNotFoundError: The geometry or its compiled HDF is missing.
        ValueError: The area is missing or has no positive spacing.
    """
    path = Path(geometry) if isinstance(geometry, (str, Path)) else None
    if path is None or path.suffix.lower() != ".hdf":
        path = Path(str(_resolve_geom_text_path(geometry, ras_object)) + ".hdf")
    if not path.is_file():
        raise FileNotFoundError(f"Compiled geometry HDF not found: {path}")
    return _grid_anchor_from_hdf(path, mesh_name=mesh_name, mesh_index=mesh_index)

generate staticmethod

Python
generate(geom_number: Union[str, Number, Path], mesh_name: Optional[str] = None, mesh_index: int = 0, cell_size: Optional[float] = None, bl_spacing: Optional[float] = None, near_repeats: Optional[int] = None, protection_radius: Optional[int] = None, min_face_length_ratio: float = 0.05, max_iterations: int = 8, hecras_dir: Optional[Union[str, Path]] = None, bl_spacing_near: Optional[float] = None, bl_spacing_far: Optional[float] = None, ras_object=None, recompile_via_rasexe: bool = False, _require_current_hdf: bool = True, refinement_region_constraints: bool = False, strict_refinement_containment: bool = False, robustness_screening: bool = False, require_complete_products: bool = False, grid_anchor: Optional[Union[GridAnchor, Tuple[float, float]]] = None) -> MeshResult

Generate or regenerate a 2D mesh headlessly via text-first workflow.

The .g01 text file is the sole persistent output. The HDF is used only as an existing temporary workspace for .NET geometry loading and cell center extraction. ras-commander does not generate .g##.hdf from text.

Workflow
  1. Validate an existing content-current compiled .g##.hdf workspace, optionally refreshing it through HEC-RAS/Ras.exe. If the selected area has no computation points and refresh is enabled, bootstrap regular-interval points from the authored perimeter first. Native recompilation still checks full products.
  2. Read per-breakline spacing from .g01 text (preserve existing)
  3. Sync text spacing -> HDF (RegenerateMeshPoints reads HDF)
  4. Load .NET geometry -> perimeter, breaklines
  5. Generate seeds: RegenerateMeshPoints (primary) or GeneratePoints
  6. Fix loop (matches TryAutoFix tier ordering):
  7. Tier 0: Diagnose short perimeter segments while preserving the exact authored perimeter
  8. Tier 1: DuplicatePoints -> remove duplicate seed points
  9. Tier 2: MaxFaces -> add midpoint seeds (before ratio escalation)
  10. Tier 3: Perimeter errors -> remove bad vertices
  11. Tier 4: Escalate MinFaceLengthRatio [0.05 -> 0.25]
  12. Tier 5: Douglas-Peucker perimeter simplification (last resort)
  13. Extract cell centers via geom.Save() + h5py read
  14. Write cell centers to .g01 text - sole persistent output

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number ("01", 1) or path to .g## text file.

required
mesh_name Optional[str]

Name of 2D flow area (None = use mesh_index).

None
mesh_index int

0-based index if mesh_name not provided.

0
cell_size Optional[float]

Base grid spacing in project units. When None (default), the value is read from geometry text Storage Area Point Generation Data first, then from the compiled HDF (Spacing dx) only as a fallback. This avoids trusting byte-copied stale HDF metadata after geometry clones.

None
bl_spacing Optional[float]

Legacy alias that applies the same positive value to both near and far breakline spacing when explicit values are omitted.

None
near_repeats Optional[int]

Number of offset seed rows on each side of breaklines. None preserves existing values from the .g01 text.

None
protection_radius Optional[int]

Enable 1-cell protection radius (0 or 1). None preserves existing values from the .g01 text.

None
min_face_length_ratio float

Positive, finite initial face-length ratio. The first attempt uses this value exactly; ratio escalation uses larger values from 0.05, 0.10, 0.15 and 0.25. Before HEC-RAS 6.6, the mesh constructor does not accept a ratio. On success the used ratio is written to geometry text and the Mapper workspace. Native geometry preprocessing remains the validation step.

0.05
max_iterations int

Maximum fix-and-retry attempts.

8
hecras_dir Optional[Union[str, Path]]

HEC-RAS installation whose RasMapperLib to load (6.0 or later). Defaults to the newest installed release found, regardless of the project's version.

None
bl_spacing_near Optional[float]

Optional override for near spacing in project units. If omitted, existing per-breakline values in the .g01 text are preserved (read from geometry, not defaulted).

None
bl_spacing_far Optional[float]

Optional override for far spacing in project units. If omitted, existing per-breakline values are preserved.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None
recompile_via_rasexe bool

If True, refresh a missing or content-stale compiled geometry HDF through GeomPreprocessor/Ras.exe. The geometry must be referenced by a plan in ras_object. An empty selected area is backed up and given initial regular computation points before native compilation and regeneration.

False
require_complete_products bool

Forward strict completion to native recompilation and perimeter-repair preprocessing. Defaults False.

False
refinement_region_constraints bool

If False (default), evaluate and repair the saved-point mesh with breakline/structure constraints. Regions still shape point generation. True retains the earlier RAS Mapper mesh with region-edge constraints. A cached Mapper mesh may differ from a fresh text-point compile.

False
strict_refinement_containment bool

If True, retain the earlier one-cell inward margin for regions. False permits valid region extents across or outside the perimeter, as RAS Mapper does.

False
robustness_screening bool

Opt-in ras-commander optimization (default False). Screen requested/accepted ratios, 0.05 and 0.1 with saved-point, region-edge and unconstrained variants. Retain region seeds and structure constraints in production. Requires one 2D area and a ratio-aware native constructor (HEC-RAS 6.6+). Adds up to max_iterations repair rounds and 50% more seeds; failure prevents saving the screened mesh. Native preprocessing is still required. Diagnostics are returned in MeshResult.robustness_screening.

False
grid_anchor Optional[Union[GridAnchor, Tuple[float, float]]]

Optional lattice point for the regular (base) grid, as a :class:GridAnchor or an (x, y) pair in the geometry's CRS and units. RAS Mapper otherwise starts the grid half a cell inside the area's own bounding box, so a child cut from a parent gets an offset grid. With an anchor, the grid passes through the anchor's lattice (use :meth:get_grid_anchor on the parent geometry), and RAS Mapper still generates the refinement-region and breakline points on it. The anchor spacing must equal cell_size. Requires RegenerateMeshPoints; there is no unanchored fallback. Evidence is returned in MeshResult.grid_anchor.

None

Returns:

Type Description
MeshResult

MeshResult with status, cell_count, face_count, fixes_applied, and

MeshResult

the compiled geometry HDF path on success. perimeter_repairs

MeshResult

records each persisted automatic repair's reason, ordered-ring

MeshResult

SHA-256 hashes, maximum vertex-to-opposite-boundary displacement

MeshResult

(both directions, project length units), signed area change

MeshResult

(squared project units), and backup path. Coordinates retain the

MeshResult

project's CRS. Repair mutates text and HDF, with a text backup;

MeshResult

supply an initialized project with a referencing plan.

Raises:

Type Description
ValueError

The face-length ratio is not positive and finite.

TypeError

grid_anchor is not a GridAnchor or (x, y) pair. (A grid anchor whose spacing differs from the cell size returns status="exception" with the reason.)

RuntimeError

A perimeter repair handoff or subsequent mesh retry fails, chained to the original mesh repair reason. Retries share the existing max_iterations bound.

Source code in ras_commander/geom/GeomMesh.py
Python
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
@staticmethod
@log_call
def generate(
    geom_number: Union[str, Number, Path],
    mesh_name: Optional[str] = None,
    mesh_index: int = 0,
    cell_size: Optional[float] = None,
    bl_spacing: Optional[float] = None,
    near_repeats: Optional[int] = None,
    protection_radius: Optional[int] = None,
    min_face_length_ratio: float = 0.05,
    max_iterations: int = 8,
    hecras_dir: Optional[Union[str, Path]] = None,
    bl_spacing_near: Optional[float] = None,
    bl_spacing_far: Optional[float] = None,
    ras_object=None,
    recompile_via_rasexe: bool = False,
    _require_current_hdf: bool = True,
    refinement_region_constraints: bool = False,
    strict_refinement_containment: bool = False,
    robustness_screening: bool = False,
    require_complete_products: bool = False,
    grid_anchor: Optional[Union[GridAnchor, Tuple[float, float]]] = None,
) -> MeshResult:
    """
    Generate or regenerate a 2D mesh headlessly via text-first workflow.

    The .g01 text file is the sole persistent output. The HDF is used only
    as an existing temporary workspace for .NET geometry loading and cell
    center extraction. ras-commander does not generate .g##.hdf from text.

    Workflow:
        1. Validate an existing content-current compiled .g##.hdf
           workspace, optionally refreshing it through HEC-RAS/Ras.exe.
           If the selected area has no computation points and refresh is
           enabled, bootstrap regular-interval points from the authored
           perimeter first. Native recompilation still checks full products.
        2. Read per-breakline spacing from .g01 text (preserve existing)
        3. Sync text spacing -> HDF (RegenerateMeshPoints reads HDF)
        4. Load .NET geometry -> perimeter, breaklines
        5. Generate seeds: RegenerateMeshPoints (primary) or GeneratePoints
        6. Fix loop (matches TryAutoFix tier ordering):
           - Tier 0: Diagnose short perimeter segments while preserving
             the exact authored perimeter
           - Tier 1: DuplicatePoints -> remove duplicate seed points
           - Tier 2: MaxFaces -> add midpoint seeds (before ratio escalation)
           - Tier 3: Perimeter errors -> remove bad vertices
           - Tier 4: Escalate MinFaceLengthRatio [0.05 -> 0.25]
           - Tier 5: Douglas-Peucker perimeter simplification (last resort)
        7. Extract cell centers via geom.Save() + h5py read
        8. Write cell centers to .g01 text - sole persistent output

    Args:
        geom_number: Geometry number ("01", 1) or path to .g## text file.
        mesh_name: Name of 2D flow area (None = use mesh_index).
        mesh_index: 0-based index if mesh_name not provided.
        cell_size: Base grid spacing in project units.  When ``None``
            (default), the value is read from geometry text
            ``Storage Area Point Generation Data`` first, then from the
            compiled HDF (``Spacing dx``) only as a fallback.  This avoids
            trusting byte-copied stale HDF metadata after geometry clones.
        bl_spacing: Legacy alias that applies the same positive value to both
            near and far breakline spacing when explicit values are omitted.
        near_repeats: Number of offset seed rows on each side of breaklines.
            None preserves existing values from the .g01 text.
        protection_radius: Enable 1-cell protection radius (0 or 1).
            None preserves existing values from the .g01 text.
        min_face_length_ratio: Positive, finite initial face-length ratio.
            The first attempt uses this value exactly; ratio escalation uses
            larger values from 0.05, 0.10, 0.15 and 0.25. Before HEC-RAS
            6.6, the mesh constructor does not accept a ratio. On success the used
            ratio is written to geometry text and the Mapper workspace.
            Native geometry preprocessing remains the validation step.
        max_iterations: Maximum fix-and-retry attempts.
        hecras_dir: HEC-RAS installation whose RasMapperLib to load
            (6.0 or later). Defaults to the newest installed release
            found, regardless of the project's version.
        bl_spacing_near: Optional override for near spacing in project units.
            If omitted, existing per-breakline values in the .g01 text
            are preserved (read from geometry, not defaulted).
        bl_spacing_far: Optional override for far spacing in project units.
            If omitted, existing per-breakline values are preserved.
        ras_object (RasPrj, optional): Optional RasPrj instance for multi-project support.
        recompile_via_rasexe: If True, refresh a missing or content-stale
            compiled geometry HDF through ``GeomPreprocessor``/Ras.exe.
            The geometry must be referenced by a plan in *ras_object*.
            An empty selected area is backed up and given initial regular
            computation points before native compilation and regeneration.
        require_complete_products: Forward strict completion to native
            recompilation and perimeter-repair preprocessing. Defaults False.
        refinement_region_constraints: If False (default), evaluate and
            repair the saved-point mesh with breakline/structure constraints.
            Regions still shape point generation. True retains the earlier
            RAS Mapper mesh with region-edge constraints. A cached Mapper
            mesh may differ from a fresh text-point compile.
        strict_refinement_containment: If True, retain the earlier one-cell
            inward margin for regions. False permits valid region extents
            across or outside the perimeter, as RAS Mapper does.
        robustness_screening: Opt-in ras-commander optimization (default False).
            Screen requested/accepted ratios, 0.05 and 0.1 with saved-point,
            region-edge and unconstrained variants. Retain region seeds and
            structure constraints in production. Requires one 2D area and a
            ratio-aware native constructor (HEC-RAS 6.6+). Adds up to
            max_iterations repair rounds and 50% more seeds; failure prevents
            saving the screened mesh. Native preprocessing is still required.
            Diagnostics are returned in MeshResult.robustness_screening.
        grid_anchor: Optional lattice point for the regular (base) grid,
            as a :class:`GridAnchor` or an ``(x, y)`` pair in the
            geometry's CRS and units. RAS Mapper otherwise starts the grid
            half a cell inside the area's own bounding box, so a child cut
            from a parent gets an offset grid. With an anchor, the grid
            passes through the anchor's lattice (use
            :meth:`get_grid_anchor` on the parent geometry), and RAS
            Mapper still generates the refinement-region and breakline
            points on it. The anchor spacing must equal ``cell_size``.
            Requires RegenerateMeshPoints; there is no unanchored
            fallback. Evidence is returned in ``MeshResult.grid_anchor``.

    Returns:
        MeshResult with status, cell_count, face_count, fixes_applied, and
        the compiled geometry HDF path on success. ``perimeter_repairs``
        records each persisted automatic repair's reason, ordered-ring
        SHA-256 hashes, maximum vertex-to-opposite-boundary displacement
        (both directions, project length units), signed area change
        (squared project units), and backup path. Coordinates retain the
        project's CRS. Repair mutates text and HDF, with a text backup;
        supply an initialized project with a referencing plan.

    Raises:
        ValueError: The face-length ratio is not positive and finite.
        TypeError: ``grid_anchor`` is not a GridAnchor or ``(x, y)`` pair.
            (A grid anchor whose spacing differs from the cell size
            returns ``status="exception"`` with the reason.)
        RuntimeError: A perimeter repair handoff or subsequent mesh retry
            fails, chained to the original mesh repair reason. Retries
            share the existing ``max_iterations`` bound.
    """
    geom_path = _resolve_geom_text_path(geom_number, ras_object)

    result = MeshResult(
        mesh_name=mesh_name or f"<index {mesh_index}>",
        status="error",
        geom_text_path=str(geom_path),
    )

    min_face_length_ratio = _normalize_positive_value(
        min_face_length_ratio, "min_face_length_ratio"
    )
    if not math.isfinite(min_face_length_ratio):
        raise ValueError("min_face_length_ratio must be finite")
    cell_size_provided = cell_size is not None
    if cell_size_provided:
        cell_size = _normalize_positive_value(cell_size, "cell_size")
    legacy_bl_spacing = _normalize_positive_value(
        bl_spacing, "bl_spacing", allow_none=True
    )
    bl_spacing_near = _normalize_positive_value(
        bl_spacing_near, "bl_spacing_near", allow_none=True
    )
    bl_spacing_far = _normalize_positive_value(
        bl_spacing_far, "bl_spacing_far", allow_none=True
    )


    if legacy_bl_spacing is not None:
        if bl_spacing_near is None:
            bl_spacing_near = legacy_bl_spacing
        if bl_spacing_far is None:
            bl_spacing_far = legacy_bl_spacing
    if grid_anchor is not None and not isinstance(grid_anchor, GridAnchor):
        # Type check now; spacing is checked once the cell size is known.
        _coerce_grid_anchor(grid_anchor, 1.0)

    repair_reason = None
    try:
        text_path = geom_path
        if recompile_via_rasexe and _bootstrap_empty_mesh_for_refresh(
            text_path, mesh_name=mesh_name, mesh_index=mesh_index,
            cell_size=cell_size, hecras_dir=hecras_dir, ras_object=ras_object,
        ):
            result.fixes_applied.append("Bootstrap:empty-area-computation-points")
            # Seed-count checks are normally relaxed during regeneration.
            # An empty-area bootstrap must still compile its new points.
            _recompile_geometry_hdf_via_rasexe(
                text_path, text_path.with_suffix(text_path.suffix + ".hdf"),
                ras_object=ras_object,
                require_complete_products=require_complete_products,
            )

        # ── Step 1: Validate existing compiled HDF workspace ─────
        # True .g## text -> .g##.hdf generation is a full HEC-RAS/Ras.exe
        # responsibility. This method only works against an existing
        # compiled geometry HDF.
        hdf_path = _ensure_hdf(
            text_path,
            hecras_dir=hecras_dir,
            require_current=_require_current_hdf,
            ras_object=ras_object,
            mesh_name=mesh_name,
            recompile_via_rasexe=recompile_via_rasexe,
            # Seed-count mismatch is expected here: this method replaces
            # computation points. Perimeter and breakline identity remain
            # mandatory content-current gates.
            ignore_seed_count=True,
            require_complete_products=require_complete_products,
        )

        # ── Step 1a: Auto-detect cell size from text if not provided ──
        if not cell_size_provided:
            cell_size = _read_cell_size_from_text(
                text_path,
                mesh_name=mesh_name,
                mesh_index=mesh_index,
            )
            if cell_size is not None:
                logger.debug(
                    f"Auto-detected cell size {cell_size} from geometry text"
                )
            else:
                cell_size = _read_cell_size_from_hdf(hdf_path, mesh_name)
                logger.debug(
                    f"Auto-detected cell size {cell_size} from HDF Spacing dx"
                )
        anchor = (
            _coerce_grid_anchor(grid_anchor, float(cell_size))
            if grid_anchor is not None
            else None
        )

        # ── Step 1b: Fail-closed mesh-feature containment gate ───
        # Breaklines and SA/2D structures retain the one-cell margin.
        # Refinement regions use native extent handling by default.
        # External boundary-condition lines are audited separately.
        domain_containment = _audit_domain_containment_hdf(
            hdf_path,
            mesh_name
            or list(_read_mesh_metadata_from_hdf(hdf_path))[mesh_index],
            float(cell_size),
            strict_refinement_containment=strict_refinement_containment,
        )
        result.domain_containment = domain_containment
        result.mesh_name = domain_containment.mesh_name
        mesh_name = domain_containment.mesh_name
        result.geom_hdf_path = str(hdf_path)
        if not domain_containment:
            preview = ", ".join(
                f"{item.feature_type}:{item.feature_name or item.feature_index}"
                for item in domain_containment.violations[:5]
            )
            suffix = "..." if len(domain_containment.violations) > 5 else ""
            result.error_message = (
                f"Pre-mesh domain containment failed for "
                f"{len(domain_containment.violations)} feature(s): "
                f"{preview}{suffix}"
            )
            return result

        # Native dependencies are loaded only after the read-only spatial
        # gate succeeds, so an invalid breakout cannot start meshing.
        _load_dlls(hecras_dir)
        ns = _imports()

        # Only modify .g01 text breakline properties if explicitly provided.
        # Otherwise the geometry's existing per-breakline values are
        # the source of truth — don't overwrite them with defaults.
        has_spacing = bl_spacing_near is not None or bl_spacing_far is not None
        has_bl_params = has_spacing or near_repeats is not None or protection_radius is not None
        if has_bl_params:
            _set_breakline_spacing_impl(
                text_path,
                bl_spacing_near if bl_spacing_near is not None else (cell_size if has_spacing else None),
                bl_spacing_far if bl_spacing_far is not None else (cell_size if has_spacing else None),
                near_repeats=near_repeats,
                protection_radius=protection_radius,
                all_breaklines=True,
                _log_summary=False,
            )

        # ── Step 1c: Sync text → HDF ────────────────────────────────
        # RegenerateMeshPoints reads spacing from the HDF, not from
        # .g01 text. Sync current cell size and per-breakline values from
        # text into the existing HDF workspace.
        _sync_cell_size_to_hdf(hdf_path, cell_size, mesh_name=mesh_name)
        _sync_breakline_spacing_text_to_hdf(text_path, hdf_path)

        # ── Step 2: Load geometry from .NET (same as RASDecomp) ──────
        geom = ns["RASGeometry"](str(hdf_path))
        d2fa = geom.D2FlowArea

        # Resolve mesh name / index
        fid = mesh_index
        if mesh_name is not None:
            resolved_fid = d2fa.GetFeatureByName(mesh_name)
            if resolved_fid >= 0:
                fid = resolved_fid
            else:
                logger.debug(
                    f"GetFeatureByName('{mesh_name}') returned -1; "
                    f"using index={mesh_index}"
                )
        else:
            try:
                mesh_name = d2fa.GetFeatureName(fid)
            except Exception:
                mesh_name = f"<index {fid}>"
        result.mesh_name = mesh_name

        # ── Step 3: Perimeter and breaklines from .NET ───────────────
        perim = d2fa.Geometry.MeshPerimeters.Polygon(fid)
        if perim is None or perim.Count == 0:
            result.error_message = "MeshPerimeters.Polygon returned None/empty"
            return result
        logger.debug(
            f"[{mesh_name}] {perim.Count}-point perimeter from .NET"
        )

        breaklines = _build_breaklines(
            d2fa, ns, refinement_region_constraints=refinement_region_constraints
        )

        # ── Step 4: Generate seeds via .NET ──────────────────────────
        # Always try RegenerateMeshPoints first — it uses the correct
        # grid origin from the HDF regardless of whether breaklines exist.
        net_seeds_ok = False
        anchor_evidence: dict = {}
        # Pass anchor keywords only when anchoring, so callers that wrap
        # the seed generator with the original signature keep working.
        seed_kwargs = (
            {"grid_anchor": anchor, "evidence": anchor_evidence}
            if anchor is not None
            else {}
        )
        try:
            seeds_pm = _generate_seeds_via_net(
                str(hdf_path), ns, fid=fid, **seed_kwargs
            )
            net_seeds_ok = True
            logger.debug(
                f"[{mesh_name}] {seeds_pm.Count} seeds via "
                f".NET RegenerateMeshPoints"
            )
        except _MeshRegenerationError as exc:
            # A known silent native failure must not become an unconstrained
            # lattice fallback that loses breakline/refinement enforcement.
            raise _MeshRegenerationError(
                f"[{mesh_name}] Native point regeneration failed: {exc}"
            ) from exc
        except Exception as exc:
            if anchor is not None:
                raise RuntimeError(
                    f"Anchored point generation failed: {exc}"
                ) from exc
            logger.warning(
                f"[{mesh_name}] RegenerateMeshPoints failed: {exc}"
            )
        if anchor is not None:
            result.grid_anchor = {**anchor_evidence, "repairs": []}
            result.fixes_applied.append("grid_anchor:lattice_phase_locked")

        if not net_seeds_ok:
            if robustness_screening:
                raise RuntimeError(
                    "Robustness screening requires RegenerateMeshPoints; "
                    "fallback points do not preserve refinement-region generation"
                )
            seeds_pm = _generate_seeds_safe(perim, cell_size, ns)
            logger.debug(
                f"[{mesh_name}] {seeds_pm.Count} seeds via "
                f"PointGenerator.GeneratePoints"
            )

        if net_seeds_ok:
            # Native region generation can retain points beyond a smaller
            # area when the source region extends far outside it. Such
            # points cannot be serialized for a valid text-point compile.
            outside = _seed_indexes_outside_perimeter(
                seeds_pm, perim, strictly_inside=True
            )
            if outside:
                seeds_pm, removed = _remove_seed_indexes(seeds_pm, outside, ns)
                result.fixes_applied.append(f"removed_{removed}_outside_or_boundary_seeds")
            if seeds_pm.Count == 0:
                result.error_message = "Point generation produced no points inside the 2D perimeter"
                return result

        # ── Fix loop setup (same tier structure as RASDecomp) ────────
        ratios = [min_face_length_ratio] + [
            r for r in _RATIO_LADDER if r > min_face_length_ratio
        ]
        if not _meshfv2d_takes_min_face_ratio(ns):
            # Before HEC-RAS 6.6 MeshFV2D has no minFaceLengthRatio, so
            # ratio escalation cannot change the mesh.
            ratios = ratios[:1]

        current_perim = perim
        current_seeds_pm = seeds_pm

        def apply_perimeter_repair(candidate, reason):
            nonlocal geom, d2fa, fid, breaklines, current_perim, current_seeds_pm
            nonlocal repair_reason
            if repair_reason is None:
                repair_reason = RuntimeError(reason)
            # The loop counts mesh attempts, including the post-repair retry.
            if result.iterations >= max_iterations:
                raise RuntimeError(
                    f"Max iterations ({max_iterations}) reached before repair retry"
                )
            evidence = _reseed_after_perimeter_fix(
                text_path,
                hdf_path,
                candidate,
                cell_size,
                mesh_name,
                hecras_dir,
                ras_object=ras_object,
                require_complete_products=require_complete_products,
            )
            evidence["reason"] = reason
            result.perimeter_repairs.append(evidence)
            containment = _audit_domain_containment_hdf(
                hdf_path, mesh_name, float(cell_size),
                strict_refinement_containment=strict_refinement_containment,
            )
            result.domain_containment = containment
            if not containment:
                raise RuntimeError("Repaired perimeter failed mesh-feature containment")
            # Every object loaded from the old HDF must be replaced before
            # computing or saving another mesh; candidate-only retries are stale.
            geom = ns["RASGeometry"](str(hdf_path))
            d2fa = geom.D2FlowArea
            fid = d2fa.GetFeatureByName(mesh_name)
            if fid < 0:
                raise RuntimeError(f"Recompiled HDF is missing 2D flow area '{mesh_name}'")
            current_perim = d2fa.Geometry.MeshPerimeters.Polygon(fid)
            if current_perim is None or current_perim.Count < 3:
                raise RuntimeError("Recompiled HDF has an empty repaired perimeter")
            breaklines = _build_breaklines(
                d2fa, ns, refinement_region_constraints=refinement_region_constraints
            )
            repair_evidence: dict = {}
            current_seeds_pm = _generate_seeds_via_net(
                str(hdf_path), ns, fid=fid,
                **(
                    {"grid_anchor": anchor, "evidence": repair_evidence}
                    if anchor is not None
                    else {}
                ),
            )
            if anchor is not None:
                result.grid_anchor["repairs"].append(repair_evidence)
            outside = _seed_indexes_outside_perimeter(
                current_seeds_pm, current_perim, strictly_inside=True
            )
            if outside:
                current_seeds_pm, removed = _remove_seed_indexes(
                    current_seeds_pm, outside, ns
                )
                result.fixes_applied.append(f"removed_{removed}_outside_or_boundary_seeds")
            if current_seeds_pm.Count == 0:
                raise RuntimeError("Repaired area has no computation points inside its perimeter")

        # Tier 0: Pre-simplify short perimeter segments
        pre_n = current_perim.Count
        repaired_perim = _remove_short_perimeter_segments(
            current_perim, cell_size * min_face_length_ratio, ns
        )
        post_n = repaired_perim.Count
        if post_n < pre_n:
            # A repaired in-memory perimeter would diverge from both the
            # authored text and the HDF collection. Try the exact authored
            # perimeter first; if HEC-RAS rejects it, report the need for a
            # separately compiled geometry edit instead of silently
            # changing the domain boundary.
            logger.warning(
                f"[{mesh_name}] Exact perimeter contains {pre_n - post_n} "
                "short segment(s); preserving the authored perimeter"
            )

        ratio_idx = 0
        tier4_count = 0
        midpoint_attempts = 0
        MAX_MIDPOINT_ATTEMPTS = 5
        duplicate_tolerances = [
            max(cell_size * 1e-8, 1e-6),
            max(cell_size * 1e-6, 1e-4),
            max(cell_size * 1e-5, 1e-3),
            max(cell_size * 1e-4, 1e-2),
        ]
        duplicate_tolerance_idx = 0
        MeshStatus = ns["MeshStatus"]
        complete_val = int(MeshStatus.Complete)
        max_faces_val = int(MeshStatus.MaxFacesPerCellExceeded)
        face_perim_val = int(MeshStatus.FacePerimeterConnectionError)
        perim_poly_val = int(MeshStatus.PerimeterPolygonError)
        try:
            duplicate_points_val = int(MeshStatus.DuplicatePoints)
        except AttributeError:
            duplicate_points_val = None
        try:
            points_outside_val = int(MeshStatus.PointsOutsidePerimeter)
        except AttributeError:
            points_outside_val = None

        for iteration in range(max_iterations):
            ratio = ratios[min(ratio_idx, len(ratios) - 1)]
            logger.debug(
                f"[{mesh_name}] Iteration {iteration + 1}: "
                f"{current_seeds_pm.Count} seeds, ratio={ratio:g}"
            )

            mesh = _compute_mesh(
                current_perim, current_seeds_pm, breaklines, ratio, ns
            )
            state_val = int(mesh.MeshCompletionState)
            state_name = str(mesh.MeshCompletionState)
            result.iterations = iteration + 1

            logger.debug(
                f"[{mesh_name}] Iteration {iteration + 1} result: "
                f"{state_name} "
                f"({_safe_non_virtual_cell_count(mesh) or 'unknown'} cells)"
            )

            if state_val == complete_val:
                if robustness_screening:
                    mesh = _screen_mesh_robustness(
                        current_perim, current_seeds_pm, d2fa, ratio,
                        min_face_length_ratio, ns, max_iterations,
                        refinement_region_constraints, _screening_inset(hdf_path),
                        result.robustness_screening,
                    )
                # ── Success: extract cell centers → patch .g01 text ──
                # The .g01 text is the sole deliverable. HEC-RAS
                # preprocessing reads "Storage Area 2D Points= N"
                # and regenerates the mesh from those XY seeds,
                # overriding any HDF content.
                #
                # geom.Save() is used only to bulk-write cell centers
                # to HDF so we can read them back via h5py (fast).
                # The HDF is a temporary workspace created by
                # HEC-RAS/Ras.exe, not a deliverable generated here.

                import numpy as _np
                _nv = _safe_non_virtual_cell_count(mesh)
                if _nv is None:
                    result.status = "error"
                    result.mesh_state = state_name
                    result.error_message = (
                        "Mesh reported Complete but RasMapper did not expose "
                        "NonVirtualCellCount."
                    )
                    if repair_reason is not None:
                        raise RuntimeError(result.error_message)
                    return result

                # Fast path: geom.Save() → h5py bulk read
                # Use the same face-collapse tolerance in the saved geometry
                # as in the mesh that the repair loop just evaluated.
                from .GeomStorage import GeomStorage

                settings = GeomStorage.get_2d_flow_area_settings(text_path)
                selected = settings.loc[settings["name"] == mesh_name, "min_face_length_ratio"]
                text_ratio = selected.iloc[0] if len(selected) else None
                if text_ratio is None or not math.isfinite(float(text_ratio)):
                    text_ratio = 0.05
                if not math.isclose(float(text_ratio), ratio, rel_tol=0, abs_tol=1e-8):
                    GeomStorage.set_2d_flow_area_settings(
                        text_path, mesh_name, min_face_length_ratio=ratio
                    )
                if hasattr(d2fa, "SetMinFaceLengthRatio"):
                    d2fa.SetMinFaceLengthRatio(fid, float(ratio))
                _new_seeds = None
                try:
                    _save_mesh(geom, d2fa, fid, mesh, ns)
                    import h5py as _h5
                    with _h5.File(str(hdf_path), "r") as _hf:
                        _cc_path = (
                            f"Geometry/2D Flow Areas/{mesh_name}/"
                            f"Cells Center Coordinate"
                        )
                        _new_seeds = _hf[_cc_path][:_nv].astype(
                            _np.float64
                        )
                    logger.debug(
                        f"[{mesh_name}] Read {_nv} cell centers from HDF"
                    )
                except Exception as _se:
                    logger.warning(
                        f"[{mesh_name}] geom.Save/h5py read failed: "
                        f"{_se}; falling back to .NET cell iteration"
                    )

                # Slow path: iterate .NET mesh cells directly
                if _new_seeds is None:
                    _new_seeds = _np.empty((_nv, 2), dtype=_np.float64)
                    for ci in range(_nv):
                        cell = mesh.Cell(ci)
                        _new_seeds[ci, 0] = float(cell.Point.X)
                        _new_seeds[ci, 1] = float(cell.Point.Y)
                    logger.debug(
                        f"[{mesh_name}] Extracted {_nv} cell centers "
                        f"via .NET iteration"
                    )

                # Write to .g01 text — the only persistent output
                _set_point_generation_data(text_path, float(cell_size), mesh_name=mesh_name)
                _patch_text_seeds(text_path, _new_seeds, mesh_name=mesh_name)

                result.status = "complete"
                result.mesh_state = state_name
                result.cell_count = _nv
                result.face_count = _safe_face_count(mesh) or 0
                result.geom_hdf_path = str(hdf_path)
                fixes_str = (
                    f", fixes: {result.fixes_applied}"
                    if result.fixes_applied else ""
                )
                logger.info(
                    f"[{mesh_name}] Mesh complete: "
                    f"{_nv} cells, {result.face_count} faces "
                    f"in {iteration + 1} iteration(s){fixes_str}"
                )
                return result

            # ── Try specific error fixes FIRST (matches TryAutoFix) ──

            # DuplicatePoints → remove duplicate seed coordinates at current ratio.
            if duplicate_points_val is not None and state_val == duplicate_points_val:
                bad_indexes = _bad_seed_indexes(mesh, current_seeds_pm.Count)
                if bad_indexes:
                    current_seeds_pm, n_removed = _remove_seed_indexes(
                        current_seeds_pm,
                        bad_indexes,
                        ns,
                    )
                    if n_removed > 0:
                        fix_msg = (
                            "DuplicatePoints:bad-index-removal"
                            f"(-{n_removed}pts)"
                        )
                        result.fixes_applied.append(fix_msg)
                        logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
                        continue

                n_removed = 0
                while duplicate_tolerance_idx < len(duplicate_tolerances):
                    tolerance = duplicate_tolerances[duplicate_tolerance_idx]
                    duplicate_tolerance_idx += 1
                    current_seeds_pm, n_removed = _dedupe_seed_points(
                        current_seeds_pm,
                        ns,
                        tolerance=tolerance,
                    )
                    if n_removed > 0:
                        fix_msg = (
                            "DuplicatePoints:dedupe"
                            f"(-{n_removed}pts,tol={tolerance:g})"
                        )
                        result.fixes_applied.append(fix_msg)
                        logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
                        break
                if n_removed > 0:
                    continue
                result.error_message = (
                    "Mesh reported DuplicatePoints, but no duplicate seed "
                    "coordinates were found within the configured tolerances."
                )
                break

            # Remove only generated seed points that HEC-RAS identifies as
            # outside. Never respond by mutating the authored perimeter.
            if points_outside_val is not None and state_val == points_outside_val:
                bad_indexes = _bad_seed_indexes(mesh, current_seeds_pm.Count)
                if not bad_indexes:
                    bad_indexes = _seed_indexes_outside_perimeter(
                        current_seeds_pm,
                        current_perim,
                    )
                if bad_indexes:
                    current_seeds_pm, n_removed = _remove_seed_indexes(
                        current_seeds_pm,
                        bad_indexes,
                        ns,
                    )
                    if n_removed > 0:
                        fix_msg = (
                            "PointsOutsidePerimeter:seed-removal"
                            f"(-{n_removed}pts)"
                        )
                        result.fixes_applied.append(fix_msg)
                        logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
                        continue
                result.error_message = (
                    "Mesh reported PointsOutsidePerimeter, but no outside "
                    "generated seed points could be identified."
                )
                break

            # MaxFaces → add midpoint seeds at current ratio
            if (
                state_val == max_faces_val
                and midpoint_attempts < MAX_MIDPOINT_ATTEMPTS
            ):
                seeds_list = [
                    current_seeds_pm[i]
                    for i in range(current_seeds_pm.Count)
                ]
                midpoint_stats: dict = {}
                new_list, n_added, _ = _autofix_max_faces(
                    mesh, seeds_list, ns, perimeter=current_perim,
                    stats=midpoint_stats,
                )
                if n_added > 0:
                    current_seeds_pm = _seeds_from_pointms_list(
                        new_list, ns
                    )
                    midpoint_attempts += 1
                    fix_msg = f"MaxFaces:midpoints(+{n_added}pts)"
                    result.fixes_applied.append(fix_msg)
                    logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
                    if midpoint_stats.get("inset"):
                        # Departure from RASMapper's placement, kept visible.
                        inset_msg = (
                            f"MaxFaces:perimeter-inset({midpoint_stats['inset']})"
                        )
                        result.fixes_applied.append(inset_msg)
                        logger.debug(f"[{mesh_name}] Fix applied: {inset_msg}")
                    continue

            # Perimeter errors → remove bad vertices
            if state_val in (face_perim_val, perim_poly_val):
                bad_indices = _autofix_perimeter(current_perim, ns)
                if bad_indices:
                    if repair_reason is None:
                        repair_reason = RuntimeError(f"{state_name}: Perim:remove")
                    candidate = _remove_perimeter_points(
                        current_perim, bad_indices, ns
                    )
                    fix_msg = f"Perim:remove(-{len(bad_indices)}pts)"
                    result.fixes_applied.append(fix_msg)
                    logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
                    apply_perimeter_repair(candidate, f"{state_name}: {fix_msg}")
                    continue

            # ── Ratio escalation (when specific fix didn't apply) ────
            if ratio_idx < len(ratios) - 1:
                old_r = ratios[ratio_idx]
                ratio_idx += 1
                fix_msg = f"Ratio:{old_r:g}->{ratios[ratio_idx]:g}"
                result.fixes_applied.append(fix_msg)
                logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
                continue

            # ── Douglas-Peucker (last resort) ────────────────────────
            cs = cell_size or 200.0
            tol = cs * min(0.10 * (tier4_count + 1), 0.50)
            buf_mult = 3.0 + float(tier4_count)
            tier4_count += 1
            if repair_reason is None:
                repair_reason = RuntimeError(f"{state_name}: DP(tol={tol:.1f})")
            error_pts = _find_error_locations(mesh, cs, ratio)
            if error_pts:
                candidate = _localized_douglas_peucker(
                    current_perim, error_pts, cs, tol, ns, buf_mult
                )
                fix_msg = f"DP:local({len(error_pts)}zones)"
                result.fixes_applied.append(fix_msg)
                logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
            else:
                candidate = _douglas_peucker_polygon(
                    current_perim, tol, ns
                )
                fix_msg = f"DP:global(tol={tol:.1f})"
                result.fixes_applied.append(fix_msg)
                logger.debug(f"[{mesh_name}] Fix applied: {fix_msg}")
            # No-op simplifications still consume the existing bound,
            # but do not invoke Ras.exe or overwrite the perimeter.
            candidate_coords = [
                (float(candidate.PointM(i).X), float(candidate.PointM(i).Y))
                for i in range(candidate.Count)
            ]
            current_coords = [
                (float(current_perim.PointM(i).X), float(current_perim.PointM(i).Y))
                for i in range(current_perim.Count)
            ]
            if candidate_coords != current_coords:
                apply_perimeter_repair(candidate, f"{state_name}: {fix_msg}")
        else:
            result.error_message = (
                f"Max iterations ({max_iterations}) reached"
            )

        result.status = "error"
        result.mesh_state = state_name
        if repair_reason is not None:
            raise RuntimeError(
                result.error_message or f"Mesh retry failed: {state_name}"
            )
        return result

    except Exception as exc:
        if repair_reason is not None:
            raise RuntimeError(
                f"Mesh repair/retry failed after {repair_reason}: {exc}"
            ) from repair_reason
        result.status = "exception"
        result.error_message = str(exc)
        logger.error(f"[{result.mesh_name}] Exception: {exc}")
        return result

generate_all staticmethod

Python
generate_all(geom_number: Union[str, Number, Path], cell_size: Optional[float] = None, bl_spacing: Optional[float] = None, bl_spacing_near: Optional[float] = None, bl_spacing_far: Optional[float] = None, near_repeats: Optional[int] = None, protection_radius: Optional[int] = None, min_face_length_ratio: float = 0.05, max_iterations: int = 8, hecras_dir: Optional[Union[str, Path]] = None, ras_object: Optional['RasPrj'] = None, recompile_via_rasexe: bool = False, refinement_region_constraints: bool = False, strict_refinement_containment: bool = False, robustness_screening: bool = False, require_complete_products: bool = False) -> List[MeshResult]

Generate/repair all 2D mesh areas in a geometry file.

Discovers every 2D flow area in the geometry and calls generate() for each one.

Parameters:

Name Type Description Default
geom_number Union[str, Number, Path]

Geometry number (e.g. "01" or 1), or a direct path to a .g## text file.

required
cell_size Optional[float]

Default mesh cell size. When None (default), each mesh area reads its spacing from geometry text first, then from the compiled HDF as a fallback.

None
bl_spacing Optional[float]

Shorthand — sets both near and far breakline spacing.

None
bl_spacing_near Optional[float]

Breakline near-spacing override.

None
bl_spacing_far Optional[float]

Breakline far-spacing override.

None
near_repeats Optional[int]

Number of offset seed rows along breaklines.

None
protection_radius Optional[int]

Enable 1-cell protection radius (0 or 1).

None
min_face_length_ratio float

Minimum face-length ratio for mesh quality.

0.05
max_iterations int

Maximum fix-loop iterations per mesh area.

8
hecras_dir Optional[Union[str, Path]]

Override path to the HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None
recompile_via_rasexe bool

If True, refresh a missing or content-stale compiled geometry HDF through GeomPreprocessor/Ras.exe.

False
require_complete_products bool

Forward strict completion to all native recompilation and mesh-repair calls. Defaults False.

False
refinement_region_constraints bool

Include region edges in mesh constraints (RAS Mapper compatibility); defaults to False.

False
strict_refinement_containment bool

Apply the old inward region margin; defaults to False.

False
robustness_screening bool

Forward the opt-in screening described by generate(). Currently requires a single 2D flow area.

False

Returns:

Type Description
List[MeshResult]

List of MeshResult, one per 2D flow area.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def generate_all(
    geom_number: Union[str, Number, Path],
    cell_size: Optional[float] = None,
    bl_spacing: Optional[float] = None,
    bl_spacing_near: Optional[float] = None,
    bl_spacing_far: Optional[float] = None,
    near_repeats: Optional[int] = None,
    protection_radius: Optional[int] = None,
    min_face_length_ratio: float = 0.05,
    max_iterations: int = 8,
    hecras_dir: Optional[Union[str, Path]] = None,
    ras_object: Optional['RasPrj'] = None,
    recompile_via_rasexe: bool = False,
    refinement_region_constraints: bool = False,
    strict_refinement_containment: bool = False,
    robustness_screening: bool = False,
    require_complete_products: bool = False,
) -> List[MeshResult]:
    """Generate/repair all 2D mesh areas in a geometry file.

    Discovers every 2D flow area in the geometry and calls
    ``generate()`` for each one.

    Args:
        geom_number: Geometry number (e.g. ``"01"`` or ``1``),
            or a direct path to a ``.g##`` text file.
        cell_size: Default mesh cell size.  When ``None`` (default),
            each mesh area reads its spacing from geometry text first,
            then from the compiled HDF as a fallback.
        bl_spacing: Shorthand — sets both near and far breakline spacing.
        bl_spacing_near: Breakline near-spacing override.
        bl_spacing_far: Breakline far-spacing override.
        near_repeats: Number of offset seed rows along breaklines.
        protection_radius: Enable 1-cell protection radius (0 or 1).
        min_face_length_ratio: Minimum face-length ratio for mesh quality.
        max_iterations: Maximum fix-loop iterations per mesh area.
        hecras_dir: Override path to the HEC-RAS installation directory.
        ras_object (RasPrj, optional): Optional RasPrj instance for multi-project support.
        recompile_via_rasexe: If True, refresh a missing or content-stale
            compiled geometry HDF through ``GeomPreprocessor``/Ras.exe.
        require_complete_products: Forward strict completion to all native
            recompilation and mesh-repair calls. Defaults False.
        refinement_region_constraints: Include region edges in mesh
            constraints (RAS Mapper compatibility); defaults to False.
        strict_refinement_containment: Apply the old inward region margin;
            defaults to False.
        robustness_screening: Forward the opt-in screening described by
            generate(). Currently requires a single 2D flow area.

    Returns:
        List of MeshResult, one per 2D flow area.
    """
    text_path = _resolve_geom_text_path(geom_number, ras_object=ras_object)
    _load_dlls(hecras_dir)
    ns = _imports()
    hdf_path = _ensure_hdf(
        text_path,
        hecras_dir=hecras_dir,
        require_current=True,
        ras_object=ras_object,
        recompile_via_rasexe=recompile_via_rasexe,
        require_complete_products=require_complete_products,
    )
    geom = ns["RASGeometry"](str(hdf_path))
    d2fa = geom.D2FlowArea
    count = d2fa.FeatureCount()
    results = []
    for i in range(count):
        name = d2fa.GetFeatureName(i)
        r = GeomMesh.generate(
            geom_number=text_path,
            mesh_name=name,
            cell_size=cell_size,
            bl_spacing=bl_spacing,
            bl_spacing_near=bl_spacing_near,
            bl_spacing_far=bl_spacing_far,
            near_repeats=near_repeats,
            protection_radius=protection_radius,
            min_face_length_ratio=min_face_length_ratio,
            max_iterations=max_iterations,
            hecras_dir=hecras_dir,
            ras_object=ras_object,
            recompile_via_rasexe=recompile_via_rasexe,
            refinement_region_constraints=refinement_region_constraints,
            strict_refinement_containment=strict_refinement_containment,
            robustness_screening=robustness_screening,
            _require_current_hdf=False,
            require_complete_products=require_complete_products,
        )
        results.append(r)
    return results

detect_bc_conflicts staticmethod

Python
detect_bc_conflicts(geom_hdf_path: Union[str, Path], cell_size: float) -> List[BCConflict]

Detect perimeter faces covered by 2+ BC lines.

Reads the boundary condition lines HEC-RAS stores in Geometry/Boundary Condition Lines (Attributes Name, SA-2D and Type with Polyline Info/Parts/Points) and, for each 2D flow area named in SA-2D, its perimeter faces: faces whose Faces Cell Indexes include a ghost cell (an index at or above the area's Attributes Cell Count), drawn from Faces FacePoint Indexes, FacePoints Coordinate and Faces Perimeter Info/Values. A face is reported when two or more of the area's BC lines lie within 0.01 * cell_size of it.

Parameters:

Name Type Description Default
geom_hdf_path Union[str, Path]

Path to a compiled .g##.hdf file (a plan HDF, which carries the same geometry, also works).

required
cell_size float

Mesh cell size for intersection buffer scaling.

required

Returns:

Type Description
List[BCConflict]

List of BCConflict (one per conflicting face), in 2D-area and face

List[BCConflict]

order. bc_names lists the BC lines in Attributes order.

List[BCConflict]

bc_types holds each line's geometry Type as stored

``External`` or ``Internal``

the geometry HDF does not record

List[BCConflict]

the hydraulic boundary type (Normal Depth, Flow Hydrograph, ...),

List[BCConflict]

which belongs to the unsteady flow file. normal_depth_bc is

List[BCConflict]

therefore filled only from a plan HDF, whose

List[BCConflict]

Event Conditions/Unsteady/Boundary Conditions/Normal Depths

List[BCConflict]

entries name the 2D area and BC line; it is None for a

List[BCConflict]

geometry HDF. Areas without Cell Count or face tables (for

List[BCConflict]

example an uncompiled geometry) yield no conflicts.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def detect_bc_conflicts(
    geom_hdf_path: Union[str, Path],
    cell_size: float,
) -> List[BCConflict]:
    """
    Detect perimeter faces covered by 2+ BC lines.

    Reads the boundary condition lines HEC-RAS stores in
    ``Geometry/Boundary Condition Lines`` (``Attributes`` ``Name``,
    ``SA-2D`` and ``Type`` with ``Polyline Info``/``Parts``/``Points``)
    and, for each 2D flow area named in ``SA-2D``, its perimeter faces:
    faces whose ``Faces Cell Indexes`` include a ghost cell (an index at or
    above the area's ``Attributes`` ``Cell Count``), drawn from
    ``Faces FacePoint Indexes``, ``FacePoints Coordinate`` and
    ``Faces Perimeter Info``/``Values``. A face is reported when two or
    more of the area's BC lines lie within ``0.01 * cell_size`` of it.

    Args:
        geom_hdf_path: Path to a compiled .g##.hdf file (a plan HDF, which
            carries the same geometry, also works).
        cell_size: Mesh cell size for intersection buffer scaling.

    Returns:
        List of BCConflict (one per conflicting face), in 2D-area and face
        order. ``bc_names`` lists the BC lines in ``Attributes`` order.
        ``bc_types`` holds each line's geometry ``Type`` as stored
        (``External`` or ``Internal``): the geometry HDF does not record
        the hydraulic boundary type (Normal Depth, Flow Hydrograph, ...),
        which belongs to the unsteady flow file. ``normal_depth_bc`` is
        therefore filled only from a plan HDF, whose
        ``Event Conditions/Unsteady/Boundary Conditions/Normal Depths``
        entries name the 2D area and BC line; it is ``None`` for a
        geometry HDF. Areas without ``Cell Count`` or face tables (for
        example an uncompiled geometry) yield no conflicts.
    """
    import h5py
    from shapely.geometry import LineString as ShapelyLine

    conflicts = []
    buf = 0.01 * cell_size

    with h5py.File(str(geom_hdf_path), "r") as hf:
        if _BC_LINES_GROUP not in hf:
            return conflicts
        bcs_by_area = _read_bc_lines_by_area(hf)
        if not bcs_by_area:
            return conflicts
        normal_depth = _read_normal_depth_bc_lines(hf)
        for flow_area_name, area_group, cell_count in _iter_perimeter_face_areas(hf):
            bcs = [
                bc for bc in bcs_by_area.get(flow_area_name, [])
                if bc["geom"] is not None
            ]
            if len(bcs) < 2:
                continue

            for face_id, face_line in _read_perimeter_face_lines(
                area_group, cell_count, ShapelyLine
            ):
                hitting = [bc for bc in bcs if face_line.distance(bc["geom"]) < buf]
                if len(hitting) >= 2:
                    nd_bc = next(
                        (bc["name"] for bc in hitting
                         if (flow_area_name, bc["name"]) in normal_depth),
                        None,
                    )
                    conflicts.append(BCConflict(
                        face_id=face_id,
                        flow_area_name=flow_area_name,
                        bc_names=[bc["name"] for bc in hitting],
                        bc_types=[bc["type"] for bc in hitting],
                        normal_depth_bc=nd_bc,
                    ))

    return conflicts

fix_bc_conflicts staticmethod

Python
fix_bc_conflicts(geom_hdf_path: Union[str, Path], cell_size: float, dry_run: bool = False) -> BCFixResult

Detect and fix BC conflicts by trimming overlapping BC endpoints.

.. warning:: This method reads and writes the old per-area Geometry/2D Flow Areas/<area>/BC Lines layout. HEC-RAS 6.x and 7.x geometry HDFs store 2D boundary condition lines in Geometry/Boundary Condition Lines instead, so on those files it finds no conflicts and changes nothing (an empty BCFixResult). Use :meth:detect_bc_conflicts to detect conflicts in HEC-RAS 6.x/7.x geometry.

Prefers trimming Normal Depth BCs (least sensitive to endpoint placement). Falls back to trimming the longer BC when no Normal Depth BC is involved.

Trim is vertex-by-vertex from the endpoint nearest the conflicting face, stopping once the BC no longer intersects that face. If vertex-walking exhausts all vertices, interpolates a new endpoint.

Parameters:

Name Type Description Default
geom_hdf_path Union[str, Path]

Path to compiled .g##.hdf file.

required
cell_size float

Mesh cell size for buffer scaling.

required
dry_run bool

If True, detect only — do not modify HDF.

False

Returns:

Type Description
BCFixResult

BCFixResult with conflicts_found, conflicts_fixed, unresolvable.

Source code in ras_commander/geom/GeomMesh.py
Python
@staticmethod
@log_call
def fix_bc_conflicts(
    geom_hdf_path: Union[str, Path],
    cell_size: float,
    dry_run: bool = False,
) -> BCFixResult:
    """
    Detect and fix BC conflicts by trimming overlapping BC endpoints.

    .. warning::
        This method reads and writes the old per-area
        ``Geometry/2D Flow Areas/<area>/BC Lines`` layout. HEC-RAS 6.x and
        7.x geometry HDFs store 2D boundary condition lines in
        ``Geometry/Boundary Condition Lines`` instead, so on those files it
        finds no conflicts and changes nothing (an empty ``BCFixResult``).
        Use :meth:`detect_bc_conflicts` to detect conflicts in HEC-RAS
        6.x/7.x geometry.

    Prefers trimming Normal Depth BCs (least sensitive to endpoint placement).
    Falls back to trimming the longer BC when no Normal Depth BC is involved.

    Trim is vertex-by-vertex from the endpoint nearest the conflicting face,
    stopping once the BC no longer intersects that face. If vertex-walking
    exhausts all vertices, interpolates a new endpoint.

    Args:
        geom_hdf_path: Path to compiled .g##.hdf file.
        cell_size: Mesh cell size for buffer scaling.
        dry_run: If True, detect only — do not modify HDF.

    Returns:
        BCFixResult with conflicts_found, conflicts_fixed, unresolvable.
    """
    import h5py
    from math import hypot
    from shapely.geometry import LineString as ShapelyLine, Point as ShapelyPoint

    import numpy as np

    cell_size = _normalize_positive_value(cell_size, "cell_size")
    geom_hdf_path = str(geom_hdf_path)
    area_results = []
    with h5py.File(geom_hdf_path, "r") as hf:
        for area_group in _iter_bc_flow_area_groups(hf):
            bcs = _read_bc_features(area_group, ShapelyLine)
            if not bcs:
                continue
            face_segments = _read_bc_face_segments(area_group, ShapelyLine)
            if not face_segments:
                continue
            area_results.append(
                {
                    "flow_area_name": area_group.name.rsplit("/", 1)[-1],
                    "area_group_path": area_group.name,
                    "bcs": bcs,
                    "face_segments": face_segments,
                }
            )

    if not area_results:
        return BCFixResult()

    buf = max(0.1, cell_size * 0.01)
    result = BCFixResult()
    for area_result in area_results:
        conflicts = []
        for fid, face_geom in area_result["face_segments"]:
            face_buf = face_geom.buffer(buf)
            hitting = [
                (b["name"], b["type"])
                for b in area_result["bcs"]
                if b["geom"] is not None and face_buf.intersects(b["geom"])
            ]
            if len(hitting) >= 2:
                nd_bc = next((n for n, t in hitting if "normal" in t.lower()), None)
                conflicts.append(BCConflict(
                    face_id=fid,
                    flow_area_name=area_result["flow_area_name"],
                    bc_names=[n for n, _ in hitting],
                    bc_types=[t for _, t in hitting],
                    normal_depth_bc=nd_bc,
                ))
        area_result["conflicts"] = conflicts
        result.conflicts_found += len(conflicts)

    if result.conflicts_found == 0 or dry_run:
        if dry_run:
            for area_result in area_results:
                result.unresolvable.extend(area_result["conflicts"])
        return result

    for area_result in area_results:
        conflicts = area_result["conflicts"]
        if not conflicts:
            continue

        bc_coords = {
            b["name"]: list(b["geom"].coords) if b["geom"] else []
            for b in area_result["bcs"]
        }
        face_mids = {
            fid: ((g.coords[0][0] + g.coords[1][0]) / 2,
                  (g.coords[0][1] + g.coords[1][1]) / 2)
            for fid, g in area_result["face_segments"]
        }
        face_geoms = {fid: g for fid, g in area_result["face_segments"]}

        for conflict in conflicts:
            if conflict.normal_depth_bc is not None:
                trim_name = conflict.normal_depth_bc
            else:
                lengths = {}
                for name in conflict.bc_names:
                    c = bc_coords.get(name, [])
                    if len(c) >= 2:
                        lengths[name] = ShapelyLine(c).length
                if not lengths:
                    result.unresolvable.append(conflict)
                    continue
                trim_name = max(lengths, key=lengths.get)

            coords = bc_coords.get(trim_name, [])
            if len(coords) < 2:
                result.unresolvable.append(conflict)
                continue

            face_geom = face_geoms[conflict.face_id]
            face_mid = face_mids[conflict.face_id]

            start_dist = hypot(coords[0][0] - face_mid[0], coords[0][1] - face_mid[1])
            end_dist = hypot(coords[-1][0] - face_mid[0], coords[-1][1] - face_mid[1])
            trim_from_start = start_dist <= end_dist

            trimmed = list(coords)
            trimmed_count = 0
            while len(trimmed) >= 2:
                if face_geom.buffer(buf).intersects(ShapelyLine(trimmed)):
                    trimmed = trimmed[1:] if trim_from_start else trimmed[:-1]
                    trimmed_count += 1
                    continue
                ep = trimmed[0] if trim_from_start else trimmed[-1]
                ep_to_conflict = hypot(ep[0] - face_mid[0], ep[1] - face_mid[1])
                nearest_other = min(
                    (hypot(ep[0] - mid[0], ep[1] - mid[1])
                     for fid, mid in face_mids.items() if fid != conflict.face_id),
                    default=float("inf"),
                )
                if ep_to_conflict <= nearest_other:
                    trimmed = trimmed[1:] if trim_from_start else trimmed[:-1]
                    trimmed_count += 1
                    continue
                break

            if len(trimmed) < 2:
                line_geom = ShapelyLine(coords)
                face_mid_pt = ShapelyPoint(*face_mid)
                proj = line_geom.project(face_mid_pt)
                pullback = face_geom.length + buf * 2
                if trim_from_start:
                    new_dist = proj + pullback
                    if new_dist >= line_geom.length:
                        result.unresolvable.append(conflict)
                        continue
                    new_pt = line_geom.interpolate(new_dist)
                    remaining = [c for c in coords
                                 if line_geom.project(ShapelyPoint(*c)) >= new_dist]
                    trimmed = [(new_pt.x, new_pt.y)] + remaining
                else:
                    new_dist = proj - pullback
                    if new_dist <= 0:
                        result.unresolvable.append(conflict)
                        continue
                    new_pt = line_geom.interpolate(new_dist)
                    remaining = [c for c in coords
                                 if line_geom.project(ShapelyPoint(*c)) <= new_dist]
                    trimmed = remaining + [(new_pt.x, new_pt.y)]
                if len(trimmed) < 2 or face_geom.buffer(buf).intersects(ShapelyLine(trimmed)):
                    result.unresolvable.append(conflict)
                    continue

            trimmed_line = ShapelyLine(trimmed)
            covers_other = any(
                fid != conflict.face_id and g.buffer(buf).intersects(trimmed_line)
                for fid, g in face_geoms.items()
            )
            if not covers_other:
                result.unresolvable.append(conflict)
                continue

            bc_coords[trim_name] = trimmed
            direction = "start" if trim_from_start else "end"
            result.trims.append(
                (
                    f"{area_result['flow_area_name']}/{trim_name}",
                    f"trimmed {trimmed_count} pts from {direction}",
                )
            )
            result.conflicts_fixed += 1

        area_result["bc_coords"] = bc_coords

    if result.conflicts_fixed == 0:
        return result

    with h5py.File(geom_hdf_path, "r+") as hf:
        for area_result in area_results:
            if "bc_coords" not in area_result:
                continue
            for b in area_result["bcs"]:
                bc_feature_path = f"{area_result['area_group_path']}/BC Lines/{b['name']}"
                if bc_feature_path not in hf:
                    continue
                bc_feature = hf[bc_feature_path]
                if "Coordinates" in bc_feature:
                    del bc_feature["Coordinates"]
                bc_feature.create_dataset(
                    "Coordinates",
                    data=np.array(area_result["bc_coords"].get(b["name"], []), dtype=np.float64),
                )

    result.modified_hdf = True
    logger.info(
        f"BC conflicts fixed: {result.conflicts_fixed}/{result.conflicts_found} "
        f"(trims: {result.trims})"
    )
    return result

Result and audit records

For generate() and generate_all(), inspect MeshResult.ok/status, error information and repair evidence rather than cell count alone.

MeshResult.status == "complete", MeshResult.ok and bool(result) report that the requested operation succeeded. Error, exception, and unknown statuses are false. operation identifies "computation_points" for bootstrap and "mesh_generation" for mesh generation, including failed operations.

For generate_computation_points(), cell_count counts generated points; geom_hdf_path is empty and the operation does not produce a compiled mesh. Callers requiring a compiled mesh must perform and verify native geometry preprocessing. Truthiness is not hydraulic acceptance.

Migration: Bootstrap previously returned status == "success" while ok and truthiness were false. Bootstrap now returns status == "complete", matching mesh generation. Replace checks for the old "success" string with result.ok; inspect result.operation when the operation type matters.

DomainContainmentResult.ok means no recorded containment violations. BCFixResult.ok means no unresolved conflicts in that result; these are operation-specific states, not hydraulic acceptance criteria.

MeshResult dataclass

Result of a mesh operation, including computation-point bootstrap.

status="complete", ok and truthiness mean the requested operation succeeded. operation identifies computation-point generation versus mesh generation. Completion does not establish hydraulic acceptance.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass
class MeshResult:
    """Result of a mesh operation, including computation-point bootstrap.

    ``status="complete"``, ``ok`` and truthiness mean the requested operation
    succeeded. ``operation`` identifies computation-point generation versus
    mesh generation. Completion does not establish hydraulic acceptance.
    """

    mesh_name: str
    status: str  # "complete", "error", "exception"
    mesh_state: str = ""
    cell_count: int = 0
    face_count: int = 0
    iterations: int = 0
    fixes_applied: List[str] = field(default_factory=list)
    error_message: str = ""
    geom_text_path: str = ""
    geom_hdf_path: str = ""
    domain_containment: Optional[DomainContainmentResult] = None
    perimeter_repairs: list[dict[str, Any]] = field(default_factory=list)

    # Empty when disabled; otherwise records rounds, convergence, timing and errors.
    robustness_screening: Dict[str, Any] = field(default_factory=dict)

    # Empty unless generate(grid_anchor=...) was used; then the anchor and
    # lattice/seed counts of each anchored point generation.
    grid_anchor: Dict[str, Any] = field(default_factory=dict)

    # Appended to preserve the positional constructor contract. For point
    # generation, cell_count counts points and no compiled HDF is produced.
    operation: str = "mesh_generation"  # or "computation_points", "cell_subset"

    # Empty unless exact physical parent cells were copied into an owned child.
    cell_subset: Dict[str, Any] = field(default_factory=dict)

    @property
    def ok(self) -> bool:
        return self.status == "complete"

    def __bool__(self) -> bool:
        return self.ok

GridAnchor dataclass

One point of a 2D area's regular computation-point lattice.

RAS Mapper lays the regular (base) grid of a 2D flow area from the area's own bounding box: the first point is half a cell inside the minimum x and the maximum y, then one point every spacing_dx / spacing_dy. A child area cut from a parent therefore gets a grid that is offset from the parent's by a sub-cell vector. A GridAnchor names a lattice point (and the spacing) that the regenerated grid must pass through instead, so a child or ensemble member re-meshes on the parent's lattice.

Coordinates and spacing are in the geometry's projected CRS and horizontal units. Only the phase (x mod spacing_dx, y mod spacing_dy) matters; any lattice point of the parent gives the same grid.

Attributes:

Name Type Description
x float

X coordinate of a lattice point.

y float

Y coordinate of a lattice point.

spacing_dx float

Lattice spacing in x (the base cell size).

spacing_dy float

Lattice spacing in y.

source str

Free-text provenance, such as the parent HDF and area name.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class GridAnchor:
    """One point of a 2D area's regular computation-point lattice.

    RAS Mapper lays the regular (base) grid of a 2D flow area from the
    area's own bounding box: the first point is half a cell inside the
    minimum x and the maximum y, then one point every ``spacing_dx`` /
    ``spacing_dy``. A child area cut from a parent therefore gets a grid
    that is offset from the parent's by a sub-cell vector. A ``GridAnchor``
    names a lattice point (and the spacing) that the regenerated grid must
    pass through instead, so a child or ensemble member re-meshes on the
    parent's lattice.

    Coordinates and spacing are in the geometry's projected CRS and
    horizontal units. Only the phase ``(x mod spacing_dx, y mod spacing_dy)``
    matters; any lattice point of the parent gives the same grid.

    Attributes:
        x: X coordinate of a lattice point.
        y: Y coordinate of a lattice point.
        spacing_dx: Lattice spacing in x (the base cell size).
        spacing_dy: Lattice spacing in y.
        source: Free-text provenance, such as the parent HDF and area name.
    """

    x: float
    y: float
    spacing_dx: float
    spacing_dy: float
    source: str = ""

    def __post_init__(self) -> None:
        for name in ("x", "y", "spacing_dx", "spacing_dy"):
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                raise TypeError(f"GridAnchor.{name} must be a number")
            if not math.isfinite(float(value)):
                raise ValueError(f"GridAnchor.{name} must be finite")
        if self.spacing_dx <= 0 or self.spacing_dy <= 0:
            raise ValueError("GridAnchor spacing must be positive")

    @property
    def phase(self) -> Tuple[float, float]:
        """Lattice phase ``(x mod spacing_dx, y mod spacing_dy)``."""
        return (
            float(self.x) % float(self.spacing_dx),
            float(self.y) % float(self.spacing_dy),
        )

    def to_dict(self) -> Dict[str, Any]:
        """Return machine-readable anchor evidence."""
        return {
            "x": float(self.x),
            "y": float(self.y),
            "spacing_dx": float(self.spacing_dx),
            "spacing_dy": float(self.spacing_dy),
            "phase": list(self.phase),
            "source": self.source,
        }

phase property

Python
phase: Tuple[float, float]

Lattice phase (x mod spacing_dx, y mod spacing_dy).

to_dict

Python
to_dict() -> Dict[str, Any]

Return machine-readable anchor evidence.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return machine-readable anchor evidence."""
    return {
        "x": float(self.x),
        "y": float(self.y),
        "spacing_dx": float(self.spacing_dx),
        "spacing_dy": float(self.spacing_dy),
        "phase": list(self.phase),
        "source": self.source,
    }

DomainContainmentResult dataclass

Pre-mesh containment evidence for one 2D flow area.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class DomainContainmentResult:
    """Pre-mesh containment evidence for one 2D flow area."""

    mesh_name: str
    geom_hdf_path: str
    base_cell_spacing: float
    inward_buffer_distance: float
    admissible_geometry_type: str
    checked_counts: Dict[str, int]
    violations: List[DomainContainmentViolation]

    @property
    def ok(self) -> bool:
        return not self.violations

    def __bool__(self) -> bool:
        return self.ok

    def to_dict(self) -> Dict[str, Any]:
        """Return machine-readable audit evidence without geometry payloads."""
        return {
            "mesh_name": self.mesh_name,
            "geom_hdf_path": self.geom_hdf_path,
            "base_cell_spacing": self.base_cell_spacing,
            "inward_buffer_distance": self.inward_buffer_distance,
            "admissible_geometry_type": self.admissible_geometry_type,
            "checked_counts": dict(self.checked_counts),
            "violation_count": len(self.violations),
            "ok": self.ok,
            "violations": [item.to_dict() for item in self.violations],
        }

to_dict

Python
to_dict() -> Dict[str, Any]

Return machine-readable audit evidence without geometry payloads.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return machine-readable audit evidence without geometry payloads."""
    return {
        "mesh_name": self.mesh_name,
        "geom_hdf_path": self.geom_hdf_path,
        "base_cell_spacing": self.base_cell_spacing,
        "inward_buffer_distance": self.inward_buffer_distance,
        "admissible_geometry_type": self.admissible_geometry_type,
        "checked_counts": dict(self.checked_counts),
        "violation_count": len(self.violations),
        "ok": self.ok,
        "violations": [item.to_dict() for item in self.violations],
    }

DomainContainmentViolation dataclass

One mesh-owned feature that is not inside the eroded 2D domain.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class DomainContainmentViolation:
    """One mesh-owned feature that is not inside the eroded 2D domain."""

    feature_type: str
    feature_name: str
    feature_index: int
    geometry_type: str
    reason: str
    outside_length: float = 0.0
    outside_area: float = 0.0
    structure_type: str = ""

    def to_dict(self) -> Dict[str, Any]:
        """Return machine-readable violation evidence."""
        return {
            "feature_type": self.feature_type,
            "feature_name": self.feature_name,
            "feature_index": self.feature_index,
            "geometry_type": self.geometry_type,
            "reason": self.reason,
            "outside_length": self.outside_length,
            "outside_area": self.outside_area,
            "structure_type": self.structure_type,
        }

to_dict

Python
to_dict() -> Dict[str, Any]

Return machine-readable violation evidence.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return machine-readable violation evidence."""
    return {
        "feature_type": self.feature_type,
        "feature_name": self.feature_name,
        "feature_index": self.feature_index,
        "geometry_type": self.geometry_type,
        "reason": self.reason,
        "outside_length": self.outside_length,
        "outside_area": self.outside_area,
        "structure_type": self.structure_type,
    }

BCConflict dataclass

A perimeter face covered by 2+ BC lines.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass
class BCConflict:
    """A perimeter face covered by 2+ BC lines."""

    face_id: int
    bc_names: List[str]
    flow_area_name: str = ""
    bc_types: List[str] = field(default_factory=list)
    normal_depth_bc: Optional[str] = None

BCFixResult dataclass

Result of BC conflict detection and repair.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass
class BCFixResult:
    """Result of BC conflict detection and repair."""

    conflicts_found: int = 0
    conflicts_fixed: int = 0
    trims: List[tuple] = field(default_factory=list)
    unresolvable: List[BCConflict] = field(default_factory=list)
    modified_hdf: bool = False

    @property
    def ok(self) -> bool:
        return len(self.unresolvable) == 0

    def __bool__(self) -> bool:
        return self.ok

Mesh engine selection and qualification (experimental fast-mesh)

HEC-RAS is the default mesh engine. GeomMeshEngine.build_mesh writes a meshed project copy with engine="native" (default), "fast-mesh" (explicit experimental opt-in; not HEC software) or "auto". "auto" uses fast-mesh only with a valid approval from RasEngineQualification. Run RasEngineQualification.validate_mesh on your project before relying on fast-mesh, and report any gap with write_gap_report. See the Mesh Engine guide and the validation how-to.

GeomMeshEngine

Engine-selectable 2D mesh generation (native HEC-RAS default; fast-mesh experimental).

All methods are static; do not instantiate this class.

Source code in ras_commander/geom/GeomMeshEngine.py
Python
class GeomMeshEngine:
    """Engine-selectable 2D mesh generation (native HEC-RAS default; fast-mesh experimental).

    All methods are static; do not instantiate this class.
    """

    ENGINES = ENGINES
    PROFILES = _engine.PROFILES
    SEED_SOURCES = _engine.SEED_SOURCES

    @staticmethod
    @log_call
    def is_fast_mesh_available(engine_path: Optional[Union[str, Path]] = None) -> bool:
        """Return True when the fast-mesh executable can be located (it is not run).

        Args:
            engine_path: Explicit executable path. Otherwise
                ``RAS_COMMANDER_FAST_MESH_EXE``, the installed
                ``ras-commander-fast-mesh`` wheel, then ``PATH`` are searched.

        Returns:
            bool: Whether the executable resolves.
        """
        return _engine.is_available(engine_path)

    @staticmethod
    @log_call
    def get_engine_info(engine_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
        """Describe the installed experimental fast-mesh engine.

        Args:
            engine_path: Explicit executable path (see :meth:`is_fast_mesh_available`).

        Returns:
            dict: ``engine``, ``version``, ``git_commit``, ``hdf5_feature``,
            ``executable``, ``executable_sha256`` and the engine's
            ``capabilities`` JSON (schema ``fast-mesh-capabilities/v1``).

        Raises:
            FastMeshNotFoundError: The executable is not installed.
            FastMeshEngineError: The engine is incompatible with this adapter.
        """
        info = _engine.engine_info(engine_path)
        logger.debug("fast-mesh executable: %s", info["executable"])
        return info

    @staticmethod
    @log_call
    def resolve_mesh_engine(
        geometry: Union[str, int, Path],
        engine: str = "auto",
        profile: str = "hec701-exact",
        repair: bool = False,
        seeds: str = "stored",
        project: Optional[Union[str, Path, Any]] = None,
        engine_path: Optional[Union[str, Path]] = None,
        ras_object: Optional[Any] = None,
    ) -> Dict[str, Any]:
        """Decide which mesh engine ``build_mesh`` would run, without running it.

        ``native`` and ``fast-mesh`` resolve to themselves. ``auto`` resolves to
        fast-mesh only when :meth:`RasEngineQualification.status` reports a valid
        approval for this project, geometry, profile, repair and seeds settings;
        otherwise to native.

        Args:
            geometry: Geometry number, ``"gNN"``, or ``.g##`` path.
            engine: ``"native"``, ``"fast-mesh"`` or ``"auto"``.
            profile: fast-mesh profile (``"hec701-exact"`` or ``"ras2025-exact"``).
            repair: Seed and perimeter repair flag.
            seeds: ``"stored"`` or ``"generated"``.
            project: ``RasPrj``, project folder or ``.prj`` path (default: ``ras_object``).
            engine_path: Explicit fast-mesh executable.
            ras_object: Optional ``RasPrj``.

        Returns:
            dict: ``engine`` (``"native"`` or ``"fast-mesh"``) and ``reason``.
        """
        if engine not in ENGINES:
            raise ValueError(f"engine must be one of {ENGINES}, got {engine!r}")
        if engine == "native":
            return {"engine": "native", "reason": "requested"}
        if engine == "fast-mesh":
            return {"engine": "fast-mesh", "reason": "requested (explicit experimental opt-in)"}
        if profile not in _engine.QUALIFIABLE_PROFILES:
            return {"engine": "native",
                    "reason": f"auto never selects profile {profile!r}; it has no qualification path"}
        from ..RasEngineQualification import RasEngineQualification

        files = resolve_project_files(project, geometry, ras_object)
        decision = RasEngineQualification.resolve_engine(
            files["project_file"], family="mesh", scope=_geometry_suffix(files["geometry_file"]),
            config={"profile": profile, "repair": bool(repair), "seeds": seeds},
            engine_path=engine_path,
        )
        if decision["engine"] not in ("native", "fast-mesh"):
            return {"engine": "native",
                    "reason": f"approved engine {decision['engine']!r} has no GeomMeshEngine build path"}
        return decision

    @staticmethod
    @log_call
    def build_mesh(
        geometry: Union[str, int, Path],
        dest_folder: Union[str, Path],
        engine: str = "native",
        profile: str = "hec701-exact",
        repair: bool = False,
        seeds: str = "stored",
        plan: Optional[Union[str, int]] = None,
        hecras_version: Optional[str] = None,
        engine_path: Optional[Union[str, Path]] = None,
        areas: Optional[Sequence[str]] = None,
        timeout: float = 3600,
        project: Optional[Union[str, Path, Any]] = None,
        ras_object: Optional[Any] = None,
    ) -> MeshBuildResult:
        """Write a meshed copy of a project with the selected engine.

        The native HEC-RAS engine is the default. ``engine="fast-mesh"`` is an
        explicit opt-in to the experimental Rust engine (not HEC software).
        ``engine="auto"`` uses fast-mesh only when the project holds a valid
        approval from :meth:`RasEngineQualification.approve`; any change to the
        approved inputs or engine version reverts it to native. Run
        :meth:`RasEngineQualification.validate_mesh` on your project before
        relying on fast-mesh, and file an issue or PR for any gap it finds.

        The source project is never modified: both engines write into
        ``dest_folder``, which must be new and outside the source.

        Args:
            geometry: Geometry number (``"02"``, ``2``), ``"g02"``, or ``.g##`` path.
            dest_folder: New folder for the meshed project copy.
            engine: ``"native"`` (default), ``"fast-mesh"`` or ``"auto"``.
            profile: fast-mesh profile: ``"hec701-exact"`` (HEC-RAS 7.0.1 mesher)
                or ``"ras2025-exact"`` (RAS2025 mesher; explicit fast-mesh only).
            repair: fast-mesh ``--repair``; for native with generated seeds, the
                ``GeomMesh.generate_all`` repair loop (``max_iterations=8``), else one attempt.
            seeds: ``"stored"`` (the seeds in the geometry text) or ``"generated"``
                (RAS Mapper 7.0.1 seed rules). Native generated seeds run
                ``GeomMesh.generate_all(recompile_via_rasexe=True)`` on the copy, which
                first refreshes a missing or stale compiled geometry HDF through HEC-RAS,
                and loads RasMapperLib from the same HEC-RAS install as preprocessing
                (a different RasMapperLib already loaded in the process is refused).
            plan: Native only: plan used for geometry preprocessing. Default: the
                first plan in ``plan_df`` that uses the geometry.
            hecras_version: Native only: HEC-RAS version or ``Ras.exe`` path.
                Default: the initialized project's executable, else ``"7.0.1"``.
            engine_path: Explicit fast-mesh executable.
            areas: 2D area names to mesh, only with ``engine="fast-mesh"`` (an
                explicit, unqualified run). Native and ``auto`` builds mesh every area,
                and approvals cover the whole geometry, so ``areas`` raises there.
            timeout: Seconds allowed for the engine run.
            project: ``RasPrj``, project folder or ``.prj`` (default: ``ras_object``).
            ras_object: Optional ``RasPrj`` for the source project.

        Returns:
            MeshBuildResult: Engine used, reason, version and output paths.

        Raises:
            FastMeshNotFoundError: fast-mesh requested but not installed.
            FastMeshEngineError: fast-mesh failed or refused the input.
            RuntimeError: Native preprocessing failed.
        """
        if engine not in ENGINES:
            raise ValueError(f"engine must be one of {ENGINES}, got {engine!r}")
        if seeds not in _engine.SEED_SOURCES:
            raise ValueError(f"seeds must be one of {_engine.SEED_SOURCES}, got {seeds!r}")
        if areas is not None and engine != "fast-mesh":
            # Native preprocessing meshes every area, and approvals cover the whole
            # geometry; a subset is neither comparable nor qualified, so it is only
            # available as an explicit, unqualified fast-mesh run.
            raise ValueError("areas is supported only with engine='fast-mesh'; native and auto "
                             "builds mesh every 2D area of the geometry")
        files = resolve_project_files(project, geometry, ras_object)
        decision = GeomMeshEngine.resolve_mesh_engine(
            files["geometry_file"], engine=engine, profile=profile, repair=repair, seeds=seeds,
            project=files["project_file"], engine_path=engine_path)
        dest = _new_destination(dest_folder, files["project_folder"])
        logger.info("Mesh engine for %s: %s (%s)", files["geometry_file"].name,
                    decision["engine"], decision["reason"])
        info = None
        if decision["engine"] == "fast-mesh" and decision.get("approved_identity"):
            # auto: run only the exact build the approval names. An install update
            # between the approval check and launch falls back to native.
            approved = decision["approved_identity"]
            try:
                info = _engine.engine_info(engine_path)
                changed = [k for k in approved if info.get(k) != approved[k]]
            except FastMeshEngineError as exc:
                changed = [f"engine unavailable ({exc.code})"]
            if changed:
                decision = {"engine": "native",
                            "reason": f"approved fast-mesh build changed before launch: {', '.join(changed)}"}
                logger.warning("Mesh engine for %s: native (%s)", files["geometry_file"].name,
                               decision["reason"])
        if decision["engine"] == "fast-mesh":
            return _build_fast_mesh(files, dest, profile=profile, repair=repair, seeds=seeds,
                                    engine_path=engine_path, areas=areas, timeout=timeout,
                                    requested=engine, reason=decision["reason"], info=info)
        if hecras_version is None:
            hecras_version = _inherited_ras_exe(project, ras_object)
        return _build_native(files, dest, seeds=seeds, repair=repair, plan=plan,
                             hecras_version=hecras_version or DEFAULT_REFERENCE_VERSION,
                             timeout=timeout, requested=engine, reason=decision["reason"])

is_fast_mesh_available staticmethod

Python
is_fast_mesh_available(engine_path: Optional[Union[str, Path]] = None) -> bool

Return True when the fast-mesh executable can be located (it is not run).

Parameters:

Name Type Description Default
engine_path Optional[Union[str, Path]]

Explicit executable path. Otherwise RAS_COMMANDER_FAST_MESH_EXE, the installed ras-commander-fast-mesh wheel, then PATH are searched.

None

Returns:

Type Description
bool

Whether the executable resolves.

Source code in ras_commander/geom/GeomMeshEngine.py
Python
@staticmethod
@log_call
def is_fast_mesh_available(engine_path: Optional[Union[str, Path]] = None) -> bool:
    """Return True when the fast-mesh executable can be located (it is not run).

    Args:
        engine_path: Explicit executable path. Otherwise
            ``RAS_COMMANDER_FAST_MESH_EXE``, the installed
            ``ras-commander-fast-mesh`` wheel, then ``PATH`` are searched.

    Returns:
        bool: Whether the executable resolves.
    """
    return _engine.is_available(engine_path)

get_engine_info staticmethod

Python
get_engine_info(engine_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]

Describe the installed experimental fast-mesh engine.

Parameters:

Name Type Description Default
engine_path Optional[Union[str, Path]]

Explicit executable path (see :meth:is_fast_mesh_available).

None

Returns:

Type Description
dict

engine, version, git_commit, hdf5_feature,

Dict[str, Any]

executable, executable_sha256 and the engine's

Dict[str, Any]

capabilities JSON (schema fast-mesh-capabilities/v1).

Raises:

Type Description
FastMeshNotFoundError

The executable is not installed.

FastMeshEngineError

The engine is incompatible with this adapter.

Source code in ras_commander/geom/GeomMeshEngine.py
Python
@staticmethod
@log_call
def get_engine_info(engine_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
    """Describe the installed experimental fast-mesh engine.

    Args:
        engine_path: Explicit executable path (see :meth:`is_fast_mesh_available`).

    Returns:
        dict: ``engine``, ``version``, ``git_commit``, ``hdf5_feature``,
        ``executable``, ``executable_sha256`` and the engine's
        ``capabilities`` JSON (schema ``fast-mesh-capabilities/v1``).

    Raises:
        FastMeshNotFoundError: The executable is not installed.
        FastMeshEngineError: The engine is incompatible with this adapter.
    """
    info = _engine.engine_info(engine_path)
    logger.debug("fast-mesh executable: %s", info["executable"])
    return info

resolve_mesh_engine staticmethod

Python
resolve_mesh_engine(geometry: Union[str, int, Path], engine: str = 'auto', profile: str = 'hec701-exact', repair: bool = False, seeds: str = 'stored', project: Optional[Union[str, Path, Any]] = None, engine_path: Optional[Union[str, Path]] = None, ras_object: Optional[Any] = None) -> Dict[str, Any]

Decide which mesh engine build_mesh would run, without running it.

native and fast-mesh resolve to themselves. auto resolves to fast-mesh only when :meth:RasEngineQualification.status reports a valid approval for this project, geometry, profile, repair and seeds settings; otherwise to native.

Parameters:

Name Type Description Default
geometry Union[str, int, Path]

Geometry number, "gNN", or .g## path.

required
engine str

"native", "fast-mesh" or "auto".

'auto'
profile str

fast-mesh profile ("hec701-exact" or "ras2025-exact").

'hec701-exact'
repair bool

Seed and perimeter repair flag.

False
seeds str

"stored" or "generated".

'stored'
project Optional[Union[str, Path, Any]]

RasPrj, project folder or .prj path (default: ras_object).

None
engine_path Optional[Union[str, Path]]

Explicit fast-mesh executable.

None
ras_object Optional[Any]

Optional RasPrj.

None

Returns:

Type Description
dict

engine ("native" or "fast-mesh") and reason.

Source code in ras_commander/geom/GeomMeshEngine.py
Python
@staticmethod
@log_call
def resolve_mesh_engine(
    geometry: Union[str, int, Path],
    engine: str = "auto",
    profile: str = "hec701-exact",
    repair: bool = False,
    seeds: str = "stored",
    project: Optional[Union[str, Path, Any]] = None,
    engine_path: Optional[Union[str, Path]] = None,
    ras_object: Optional[Any] = None,
) -> Dict[str, Any]:
    """Decide which mesh engine ``build_mesh`` would run, without running it.

    ``native`` and ``fast-mesh`` resolve to themselves. ``auto`` resolves to
    fast-mesh only when :meth:`RasEngineQualification.status` reports a valid
    approval for this project, geometry, profile, repair and seeds settings;
    otherwise to native.

    Args:
        geometry: Geometry number, ``"gNN"``, or ``.g##`` path.
        engine: ``"native"``, ``"fast-mesh"`` or ``"auto"``.
        profile: fast-mesh profile (``"hec701-exact"`` or ``"ras2025-exact"``).
        repair: Seed and perimeter repair flag.
        seeds: ``"stored"`` or ``"generated"``.
        project: ``RasPrj``, project folder or ``.prj`` path (default: ``ras_object``).
        engine_path: Explicit fast-mesh executable.
        ras_object: Optional ``RasPrj``.

    Returns:
        dict: ``engine`` (``"native"`` or ``"fast-mesh"``) and ``reason``.
    """
    if engine not in ENGINES:
        raise ValueError(f"engine must be one of {ENGINES}, got {engine!r}")
    if engine == "native":
        return {"engine": "native", "reason": "requested"}
    if engine == "fast-mesh":
        return {"engine": "fast-mesh", "reason": "requested (explicit experimental opt-in)"}
    if profile not in _engine.QUALIFIABLE_PROFILES:
        return {"engine": "native",
                "reason": f"auto never selects profile {profile!r}; it has no qualification path"}
    from ..RasEngineQualification import RasEngineQualification

    files = resolve_project_files(project, geometry, ras_object)
    decision = RasEngineQualification.resolve_engine(
        files["project_file"], family="mesh", scope=_geometry_suffix(files["geometry_file"]),
        config={"profile": profile, "repair": bool(repair), "seeds": seeds},
        engine_path=engine_path,
    )
    if decision["engine"] not in ("native", "fast-mesh"):
        return {"engine": "native",
                "reason": f"approved engine {decision['engine']!r} has no GeomMeshEngine build path"}
    return decision

build_mesh staticmethod

Python
build_mesh(geometry: Union[str, int, Path], dest_folder: Union[str, Path], engine: str = 'native', profile: str = 'hec701-exact', repair: bool = False, seeds: str = 'stored', plan: Optional[Union[str, int]] = None, hecras_version: Optional[str] = None, engine_path: Optional[Union[str, Path]] = None, areas: Optional[Sequence[str]] = None, timeout: float = 3600, project: Optional[Union[str, Path, Any]] = None, ras_object: Optional[Any] = None) -> MeshBuildResult

Write a meshed copy of a project with the selected engine.

The native HEC-RAS engine is the default. engine="fast-mesh" is an explicit opt-in to the experimental Rust engine (not HEC software). engine="auto" uses fast-mesh only when the project holds a valid approval from :meth:RasEngineQualification.approve; any change to the approved inputs or engine version reverts it to native. Run :meth:RasEngineQualification.validate_mesh on your project before relying on fast-mesh, and file an issue or PR for any gap it finds.

The source project is never modified: both engines write into dest_folder, which must be new and outside the source.

Parameters:

Name Type Description Default
geometry Union[str, int, Path]

Geometry number ("02", 2), "g02", or .g## path.

required
dest_folder Union[str, Path]

New folder for the meshed project copy.

required
engine str

"native" (default), "fast-mesh" or "auto".

'native'
profile str

fast-mesh profile: "hec701-exact" (HEC-RAS 7.0.1 mesher) or "ras2025-exact" (RAS2025 mesher; explicit fast-mesh only).

'hec701-exact'
repair bool

fast-mesh --repair; for native with generated seeds, the GeomMesh.generate_all repair loop (max_iterations=8), else one attempt.

False
seeds str

"stored" (the seeds in the geometry text) or "generated" (RAS Mapper 7.0.1 seed rules). Native generated seeds run GeomMesh.generate_all(recompile_via_rasexe=True) on the copy, which first refreshes a missing or stale compiled geometry HDF through HEC-RAS, and loads RasMapperLib from the same HEC-RAS install as preprocessing (a different RasMapperLib already loaded in the process is refused).

'stored'
plan Optional[Union[str, int]]

Native only: plan used for geometry preprocessing. Default: the first plan in plan_df that uses the geometry.

None
hecras_version Optional[str]

Native only: HEC-RAS version or Ras.exe path. Default: the initialized project's executable, else "7.0.1".

None
engine_path Optional[Union[str, Path]]

Explicit fast-mesh executable.

None
areas Optional[Sequence[str]]

2D area names to mesh, only with engine="fast-mesh" (an explicit, unqualified run). Native and auto builds mesh every area, and approvals cover the whole geometry, so areas raises there.

None
timeout float

Seconds allowed for the engine run.

3600
project Optional[Union[str, Path, Any]]

RasPrj, project folder or .prj (default: ras_object).

None
ras_object Optional[Any]

Optional RasPrj for the source project.

None

Returns:

Type Description
MeshBuildResult

Engine used, reason, version and output paths.

Raises:

Type Description
FastMeshNotFoundError

fast-mesh requested but not installed.

FastMeshEngineError

fast-mesh failed or refused the input.

RuntimeError

Native preprocessing failed.

Source code in ras_commander/geom/GeomMeshEngine.py
Python
@staticmethod
@log_call
def build_mesh(
    geometry: Union[str, int, Path],
    dest_folder: Union[str, Path],
    engine: str = "native",
    profile: str = "hec701-exact",
    repair: bool = False,
    seeds: str = "stored",
    plan: Optional[Union[str, int]] = None,
    hecras_version: Optional[str] = None,
    engine_path: Optional[Union[str, Path]] = None,
    areas: Optional[Sequence[str]] = None,
    timeout: float = 3600,
    project: Optional[Union[str, Path, Any]] = None,
    ras_object: Optional[Any] = None,
) -> MeshBuildResult:
    """Write a meshed copy of a project with the selected engine.

    The native HEC-RAS engine is the default. ``engine="fast-mesh"`` is an
    explicit opt-in to the experimental Rust engine (not HEC software).
    ``engine="auto"`` uses fast-mesh only when the project holds a valid
    approval from :meth:`RasEngineQualification.approve`; any change to the
    approved inputs or engine version reverts it to native. Run
    :meth:`RasEngineQualification.validate_mesh` on your project before
    relying on fast-mesh, and file an issue or PR for any gap it finds.

    The source project is never modified: both engines write into
    ``dest_folder``, which must be new and outside the source.

    Args:
        geometry: Geometry number (``"02"``, ``2``), ``"g02"``, or ``.g##`` path.
        dest_folder: New folder for the meshed project copy.
        engine: ``"native"`` (default), ``"fast-mesh"`` or ``"auto"``.
        profile: fast-mesh profile: ``"hec701-exact"`` (HEC-RAS 7.0.1 mesher)
            or ``"ras2025-exact"`` (RAS2025 mesher; explicit fast-mesh only).
        repair: fast-mesh ``--repair``; for native with generated seeds, the
            ``GeomMesh.generate_all`` repair loop (``max_iterations=8``), else one attempt.
        seeds: ``"stored"`` (the seeds in the geometry text) or ``"generated"``
            (RAS Mapper 7.0.1 seed rules). Native generated seeds run
            ``GeomMesh.generate_all(recompile_via_rasexe=True)`` on the copy, which
            first refreshes a missing or stale compiled geometry HDF through HEC-RAS,
            and loads RasMapperLib from the same HEC-RAS install as preprocessing
            (a different RasMapperLib already loaded in the process is refused).
        plan: Native only: plan used for geometry preprocessing. Default: the
            first plan in ``plan_df`` that uses the geometry.
        hecras_version: Native only: HEC-RAS version or ``Ras.exe`` path.
            Default: the initialized project's executable, else ``"7.0.1"``.
        engine_path: Explicit fast-mesh executable.
        areas: 2D area names to mesh, only with ``engine="fast-mesh"`` (an
            explicit, unqualified run). Native and ``auto`` builds mesh every area,
            and approvals cover the whole geometry, so ``areas`` raises there.
        timeout: Seconds allowed for the engine run.
        project: ``RasPrj``, project folder or ``.prj`` (default: ``ras_object``).
        ras_object: Optional ``RasPrj`` for the source project.

    Returns:
        MeshBuildResult: Engine used, reason, version and output paths.

    Raises:
        FastMeshNotFoundError: fast-mesh requested but not installed.
        FastMeshEngineError: fast-mesh failed or refused the input.
        RuntimeError: Native preprocessing failed.
    """
    if engine not in ENGINES:
        raise ValueError(f"engine must be one of {ENGINES}, got {engine!r}")
    if seeds not in _engine.SEED_SOURCES:
        raise ValueError(f"seeds must be one of {_engine.SEED_SOURCES}, got {seeds!r}")
    if areas is not None and engine != "fast-mesh":
        # Native preprocessing meshes every area, and approvals cover the whole
        # geometry; a subset is neither comparable nor qualified, so it is only
        # available as an explicit, unqualified fast-mesh run.
        raise ValueError("areas is supported only with engine='fast-mesh'; native and auto "
                         "builds mesh every 2D area of the geometry")
    files = resolve_project_files(project, geometry, ras_object)
    decision = GeomMeshEngine.resolve_mesh_engine(
        files["geometry_file"], engine=engine, profile=profile, repair=repair, seeds=seeds,
        project=files["project_file"], engine_path=engine_path)
    dest = _new_destination(dest_folder, files["project_folder"])
    logger.info("Mesh engine for %s: %s (%s)", files["geometry_file"].name,
                decision["engine"], decision["reason"])
    info = None
    if decision["engine"] == "fast-mesh" and decision.get("approved_identity"):
        # auto: run only the exact build the approval names. An install update
        # between the approval check and launch falls back to native.
        approved = decision["approved_identity"]
        try:
            info = _engine.engine_info(engine_path)
            changed = [k for k in approved if info.get(k) != approved[k]]
        except FastMeshEngineError as exc:
            changed = [f"engine unavailable ({exc.code})"]
        if changed:
            decision = {"engine": "native",
                        "reason": f"approved fast-mesh build changed before launch: {', '.join(changed)}"}
            logger.warning("Mesh engine for %s: native (%s)", files["geometry_file"].name,
                           decision["reason"])
    if decision["engine"] == "fast-mesh":
        return _build_fast_mesh(files, dest, profile=profile, repair=repair, seeds=seeds,
                                engine_path=engine_path, areas=areas, timeout=timeout,
                                requested=engine, reason=decision["reason"], info=info)
    if hecras_version is None:
        hecras_version = _inherited_ras_exe(project, ras_object)
    return _build_native(files, dest, seeds=seeds, repair=repair, plan=plan,
                         hecras_version=hecras_version or DEFAULT_REFERENCE_VERSION,
                         timeout=timeout, requested=engine, reason=decision["reason"])

MeshBuildResult dataclass

Outcome of :meth:GeomMeshEngine.build_mesh.

Attributes:

Name Type Description
engine str

Engine that ran: "native" or "fast-mesh".

requested_engine str

The engine argument as given.

resolution_reason str

Why that engine ran (for auto, the approval status).

engine_version Optional[str]

fast-mesh version, or the HEC-RAS version label for native.

project_folder Path

The written project copy.

geometry_file Path

The meshed .g## text in the copy.

geometry_hdf Path

The meshed .g##.hdf in the copy.

profile Optional[str]

fast-mesh profile (None for native).

seeds str

"stored" or "generated".

repair bool

Whether seed and perimeter repair was requested.

manifest Optional[Dict[str, Any]]

fast-mesh run manifest (fast-mesh-run-manifest/v1), unchanged; None for native.

preprocess Any

Native GeometryPreprocessResult (None for fast-mesh).

engine_details Dict[str, Any]

Engine identity (version, commit, executable digest) without paths.

Source code in ras_commander/geom/GeomMeshEngine.py
Python
@dataclass
class MeshBuildResult:
    """Outcome of :meth:`GeomMeshEngine.build_mesh`.

    Attributes:
        engine: Engine that ran: ``"native"`` or ``"fast-mesh"``.
        requested_engine: The ``engine`` argument as given.
        resolution_reason: Why that engine ran (for ``auto``, the approval status).
        engine_version: fast-mesh version, or the HEC-RAS version label for native.
        project_folder: The written project copy.
        geometry_file: The meshed ``.g##`` text in the copy.
        geometry_hdf: The meshed ``.g##.hdf`` in the copy.
        profile: fast-mesh profile (``None`` for native).
        seeds: ``"stored"`` or ``"generated"``.
        repair: Whether seed and perimeter repair was requested.
        manifest: fast-mesh run manifest (``fast-mesh-run-manifest/v1``), unchanged; ``None`` for native.
        preprocess: Native ``GeometryPreprocessResult`` (``None`` for fast-mesh).
        engine_details: Engine identity (version, commit, executable digest) without paths.
    """

    engine: str
    requested_engine: str
    resolution_reason: str
    engine_version: Optional[str]
    project_folder: Path
    geometry_file: Path
    geometry_hdf: Path
    profile: Optional[str]
    seeds: str
    repair: bool
    manifest: Optional[Dict[str, Any]] = None
    preprocess: Any = None
    engine_details: Dict[str, Any] = field(default_factory=dict)

RasEngineQualification

Qualify, approve and resolve experimental engines per project.

All methods are static; do not instantiate this class.

The native engine stays the default. An experimental engine runs by default for a project only with a saved approval whose input fingerprints and engine version still match. Run the validation API on your project before relying on a Rust engine; file an issue or PR for any gap it finds, and keep private project data out.

Source code in ras_commander/RasEngineQualification.py
Python
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
class RasEngineQualification:
    """Qualify, approve and resolve experimental engines per project.

    All methods are static; do not instantiate this class.

    The native engine stays the default. An experimental engine runs by
    default for a project only with a saved approval whose input fingerprints
    and engine version still match. Run the validation API on your project
    before relying on a Rust engine; file an issue or PR for any gap it finds,
    and keep private project data out.
    """

    MESH_TABLES = MESH_TABLES
    APPROVALS_DIR = APPROVALS_DIR
    APPROVALS_FILE = APPROVALS_FILE

    # -- registry ---------------------------------------------------------

    @staticmethod
    @log_call
    def register_engine(spec: EngineSpec, replace: bool = False) -> EngineSpec:
        """Register an engine and its equivalence check (extension point).

        Args:
            spec: Engine registration. ``validator`` and ``fingerprint`` make
                approvals possible; without them the engine can only be the
                platform default or run by explicit request.
            replace: Allow replacing an existing registration.

        Returns:
            EngineSpec: The registered spec.
        """
        if spec.family not in NATIVE_ENGINES:
            raise ValueError(f"family must be one of {sorted(NATIVE_ENGINES)}, got {spec.family!r}")
        if spec.name in _REGISTRY and not replace:
            raise ValueError(f"engine {spec.name!r} is already registered")
        _REGISTRY[spec.name] = spec
        return spec

    @staticmethod
    @log_call
    def unregister_engine(name: str) -> None:
        """Remove a registration added with :meth:`register_engine`. Built-ins are re-registered on reset."""
        _REGISTRY.pop(name, None)
        if name in ("fast-mesh", "fast-hdf", "fast-map", "fast-dss", "fast-preprocess", "fast-unsteady"):
            _register_builtin()

    @staticmethod
    @log_call
    def registered_engines() -> pd.DataFrame:
        """List registered engines (schema ``engine_registry``).

        Returns:
            pd.DataFrame: ``engine``, ``family``, ``platform_default``, ``status``,
            ``has_equivalence_check``, ``description``.
        """
        return pd.DataFrame([
            {"engine": s.name, "family": s.family, "platform_default": s.platform_default,
             "status": s.status, "has_equivalence_check": s.validator is not None,
             "description": s.description}
            for s in _REGISTRY.values()
        ], columns=["engine", "family", "platform_default", "status",
                    "has_equivalence_check", "description"])

    @staticmethod
    @log_call
    def validate(engine: str, project: Optional[Union[str, Path, Any]] = None, **kwargs) -> EngineQualificationReport:
        """Run the registered equivalence check for ``engine``.

        Raises:
            KeyError: Unknown engine.
            NotImplementedError: The engine has no equivalence check yet.
        """
        spec = _REGISTRY.get(engine)
        if spec is None:
            raise KeyError(f"unknown engine {engine!r}; registered: {sorted(_REGISTRY)}")
        if spec.validator is None:
            raise NotImplementedError(
                f"{engine} has no per-project equivalence check in RAS Commander yet "
                f"(status {spec.status}). Register one with RasEngineQualification.register_engine. "
                "Its existing behaviour is unchanged.")
        return spec.validator(project, **kwargs)

    # -- mesh validation --------------------------------------------------

    @staticmethod
    @log_call
    def compare_mesh_tables(reference_hdf: Union[str, Path],
                            candidate_hdf: Union[str, Path]) -> pd.DataFrame:
        """Compare the 15 mesh tables of every 2D area in two geometry HDF files.

        Comparison is exact: same shape, same dtype, same bytes (``-0.0`` and
        ``0.0`` differ). Only counts and indices are reported, never values.

        Args:
            reference_hdf: Native HEC-RAS geometry HDF (the reference).
            candidate_hdf: Candidate geometry HDF (for example fast-mesh's).

        Returns:
            pd.DataFrame: One row per area and table (schema ``engine_mesh_qualification``).
        """
        import h5py

        rows = []
        with h5py.File(reference_hdf, "r") as ref, h5py.File(candidate_hdf, "r") as cand:
            ref_areas, cand_areas = _area_names(ref), _area_names(cand)
            ordered = ref_areas + [a for a in cand_areas if a not in ref_areas]
            for area in ordered:
                for table in MESH_TABLES:
                    key = f"Geometry/2D Flow Areas/{area}/{table}"
                    row = {"area": area, "table": table}
                    in_ref, in_cand = key in ref, key in cand
                    if not in_ref or not in_cand:
                        row.update(status="missing_reference" if not in_ref else "missing_candidate")
                        for col in ("reference_shape", "candidate_shape", "reference_dtype",
                                    "candidate_dtype", "differing_elements", "differing_rows",
                                    "first_differing_row", "max_abs_difference"):
                            row[col] = None
                    else:
                        row.update(_compare_arrays(ref[key][()], cand[key][()]))
                    rows.append(row)
        columns = ["area", "table", "status", "reference_shape", "candidate_shape",
                   "reference_dtype", "candidate_dtype", "differing_elements",
                   "differing_rows", "first_differing_row", "max_abs_difference"]
        return pd.DataFrame(rows, columns=columns)

    @staticmethod
    @log_call
    def validate_mesh(
        project: Optional[Union[str, Path, Any]] = None,
        geometry: Union[str, int, Path] = None,
        profile: str = "hec701-exact",
        repair: bool = False,
        seeds: str = "stored",
        plan: Optional[Union[str, int]] = None,
        hecras_version: str = "7.0.1",
        workspace: Optional[Union[str, Path]] = None,
        keep_projects: bool = False,
        engine_path: Optional[Union[str, Path]] = None,
        timeout: float = 3600,
        write_gap_report: bool = True,
        ras_object: Optional[Any] = None,
    ) -> EngineQualificationReport:
        """Prove (or disprove) that fast-mesh reproduces HEC-RAS's mesh for one geometry.

        Run this on your own project before relying on the experimental
        fast-mesh engine. The source project is never modified:

        1. The native reference is built on a staged copy: HEC-RAS
           ``hecras_version`` geometry preprocessing through
           ``GeomPreprocessor.run_geometry_preprocessor`` (after
           ``GeomMesh.generate_all`` when ``seeds="generated"``).
        2. fast-mesh meshes another copy (``mesh --out-dir``) from the source
           geometry text and source geometry HDF.
        3. The 15 mesh tables of every 2D area are compared byte for byte, and
           the run manifest is checked (schema, validation, profile and label,
           ``official_equivalent``, output hashes, warnings).
        4. The source tree fingerprint is checked before and after.

        When the result is not equivalent and the native reference succeeded,
        a gap report (markdown and JSON, no project data) is written to the
        workspace. Nothing is posted. When it is equivalent, call
        ``report.approve()`` to let ``engine="auto"`` use fast-mesh for this
        geometry and these settings.

        Args:
            project: ``RasPrj``, project folder or ``.prj`` (default: ``ras_object``).
            geometry: Geometry number, ``"gNN"`` or ``.g##`` path.
            profile: Must be ``"hec701-exact"``; RAS2025 has no native reference here.
            repair: fast-mesh ``--repair`` (and native ``GeomMesh.generate_all`` repair).
            seeds: ``"stored"`` (default) or ``"generated"``.
            plan: Plan for native preprocessing (default: first plan using the geometry).
            hecras_version: Reference HEC-RAS version (default ``"7.0.1"``).
            workspace: Folder for staged copies and reports (default: a new temp folder).
                Keep it short; HEC-RAS needs short paths.
            keep_projects: Keep the two meshed project copies after comparison.
            engine_path: Explicit fast-mesh executable.
            timeout: Seconds allowed for each engine run.
            write_gap_report: Write the gap-report bundle on non-equivalence.
            ras_object: Optional ``RasPrj`` for the source project.

        Returns:
            EngineQualificationReport: ``status`` is ``equivalent``,
            ``not_equivalent``, ``fast_mesh_failed``, ``comparison_failed`` (an
            output could not be compared), ``native_reference_failed``, or
            ``reference_not_qualifying`` (the reference was not HEC-RAS 7.0.1, which
            ``hec701-exact`` requires), or ``engine_changed`` (the fast-mesh
            executable resolved at the start is not the build that produced the
            candidate). Only ``equivalent`` can be approved.
        """
        from .geom import _fast_mesh_engine as engine
        from .geom.GeomMeshEngine import GeomMeshEngine, _geometry_suffix, resolve_project_files
        from .RasQualification import RasQualification

        if profile not in engine.QUALIFIABLE_PROFILES:
            raise NotImplementedError(
                f"profile {profile!r} cannot be qualified through RAS Commander: there is no "
                "native reference for it. Only 'hec701-exact' (HEC-RAS 7.0.1) is qualifiable.")
        if seeds not in engine.SEED_SOURCES:
            raise ValueError(f"seeds must be one of {engine.SEED_SOURCES}, got {seeds!r}")
        files = resolve_project_files(project if project is not None else ras_object, geometry,
                                      ras_object)
        source = files["project_folder"]
        scope = _geometry_suffix(files["geometry_file"])
        config = {"profile": profile, "repair": bool(repair), "seeds": seeds}
        if workspace is not None:
            requested = Path(workspace).absolute().resolve()
            if requested == source or source in requested.parents:
                raise ValueError(f"workspace must be outside the source project: {requested}")
        # Resolve the engine once and pin that executable for the whole validation,
        # so the report can only credit the build that produced the candidate.
        resolved_engine = engine.engine_info(engine_path)
        pinned_executable = resolved_engine["executable"]
        identity = {k: resolved_engine[k] for k in _IDENTITY_KEYS}
        before = RasQualification.project_tree_fingerprint(source)
        fingerprints = _mesh_fingerprint(files["project_file"], scope)
        if workspace is None:
            work = Path(tempfile.mkdtemp(prefix="rasq-mesh-"))
        else:
            requested.mkdir(parents=True, exist_ok=True)
            work = Path(tempfile.mkdtemp(prefix=f"mesh-{scope}-", dir=requested))
        logger.info("Validating fast-mesh %s (%s, seeds %s, repair %s) against HEC-RAS %s for %s",
                    identity["version"], profile, seeds, repair, _version_label(hecras_version), scope)
        report = EngineQualificationReport(
            engine="fast-mesh", family="mesh", scope=scope, config=config,
            project_folder=str(source), project_file=files["project_file"].name,
            equivalent=False, status="running",
            engine_identity=identity,
            reference={"hecras_version": _version_label(hecras_version), "method":
                       "GeomPreprocessor.run_geometry_preprocessor", "plan": None},
            fingerprints=fingerprints, workspace=str(work), created_utc=_utc_now(),
            ras_commander_version=_ras_commander_version())

        native_dir = work / "native" / source.name
        fast_dir = work / "fast-mesh" / source.name
        native = fast = None
        try:
            try:
                native = GeomMeshEngine.build_mesh(
                    files["geometry_file"], native_dir, engine="native", seeds=seeds, repair=repair,
                    plan=plan, hecras_version=hecras_version, timeout=timeout,
                    project=files["project_file"])
                report.reference["plan"] = native.engine_details.get("plan")
                report.reference["hecras_version_resolved"] = native.engine_version
            except Exception as exc:  # native failure is not an engine gap
                report.status = "native_reference_failed"
                report.checks["native_reference"] = {"passed": False, "error": type(exc).__name__,
                                                     "detail": str(exc)[:2000]}
                logger.error("Native reference failed; fast-mesh not judged: %s", exc)
            if native is not None:
                report.checks["native_reference"] = {"passed": True}
                # hec701-exact claims HEC-RAS 7.0.1 equivalence, so only a 7.0.1
                # reference can qualify it (the resolved install's version folder).
                resolved = str(native.engine_version)
                report.checks["reference_version"] = {
                    "passed": resolved == REFERENCE_VERSIONS[profile],
                    "required": REFERENCE_VERSIONS[profile], "value": _version_label(resolved)}
                if not report.checks["reference_version"]["passed"]:
                    report.status = "reference_not_qualifying"
                try:
                    fast = GeomMeshEngine.build_mesh(
                        files["geometry_file"], fast_dir, engine="fast-mesh", profile=profile,
                        seeds=seeds, repair=repair, engine_path=pinned_executable, timeout=timeout,
                        project=files["project_file"])
                    report.checks["fast_mesh_run"] = {"passed": True}
                    built = {k: fast.engine_details.get(k) for k in _IDENTITY_KEYS}
                    changed = sorted(k for k in _IDENTITY_KEYS if built[k] != identity[k])
                    report.checks["engine_identity"] = {"passed": not changed, "changed": changed}
                    if changed:
                        if report.status == "running":
                            report.status = "engine_changed"
                        logger.error("The fast-mesh executable changed during validation (%s); "
                                     "the result is not credited to either build.", ", ".join(changed))
                except engine.FastMeshEngineError as exc:
                    if report.status == "running":
                        report.status = "fast_mesh_failed"
                    report.checks["fast_mesh_run"] = {"passed": False, "code": exc.code,
                                                      "area": exc.area, "detail": exc.message[:2000]}
                if fast is not None:
                    try:
                        report.tables = RasEngineQualification.compare_mesh_tables(
                            native.geometry_hdf, fast.geometry_hdf)
                        hashes = engine.verify_outputs(fast.manifest, fast.project_folder, expected={
                            "geometry_hdf": fast.geometry_hdf.name,
                            "geometry_text": fast.geometry_file.name})
                        report.checks.update(_manifest_checks(fast.manifest, hashes, profile))
                        import h5py
                        with h5py.File(native.geometry_hdf, "r") as ref:
                            report.areas = [{"name": a, "real_cells": _cell_count(ref, a)}
                                            for a in _area_names(ref)]
                        tables_ok = not report.tables.empty and bool(
                            (report.tables["status"] == "identical").all())
                        report.checks["mesh_tables"] = {
                            "passed": tables_ok,
                            "identical": int((report.tables["status"] == "identical").sum()),
                            "compared": int(len(report.tables))}
                    except Exception as exc:  # unreadable/unsupported HDF: not equivalent
                        if report.status == "running":
                            report.status = "comparison_failed"
                        report.checks["mesh_comparison"] = {
                            "passed": False, "error": type(exc).__name__, "detail": str(exc)[:2000]}
                        logger.error("Mesh comparison failed; reported as not equivalent: %s", exc)
            if report.tables.empty and "table" not in report.tables:
                report.tables = pd.DataFrame(columns=["area", "table", "status"])
        finally:
            # Always check the source and clean up, whatever failed above.
            after = RasQualification.project_tree_fingerprint(source)
            report.source_unchanged = before == after
            report.checks["source_unchanged"] = {"passed": report.source_unchanged}
            if not keep_projects:
                for folder in (work / "native", work / "fast-mesh"):
                    shutil.rmtree(folder, ignore_errors=True)
        if report.status == "running":
            report.equivalent = all(v.get("passed") for v in report.checks.values()
                                    if isinstance(v, dict) and "passed" in v)
            report.status = "equivalent" if report.equivalent else "not_equivalent"
        else:
            report.equivalent = False
        if (not report.equivalent and write_gap_report
                and report.status not in ("native_reference_failed", "reference_not_qualifying",
                                          "engine_changed")):
            report.gap_report = RasEngineQualification.write_gap_report(report, work / "gap-report")
        report_path = work / "qualification_report.json"
        report.report_path = str(report_path)
        report_path.write_text(json.dumps(report.to_dict(), indent=2, default=str) + "\n",
                               encoding="utf-8")
        summary = report.summary()
        logger.info("fast-mesh qualification for %s: %s (%d/%d tables identical)", scope,
                    report.status, summary["tables_identical"], summary["tables_compared"])
        if report.equivalent:
            logger.info("Equivalent. Call report.approve() to let engine='auto' use fast-mesh "
                        "for %s with these settings.", scope)
        elif report.gap_report:
            logger.warning("Not equivalent. Review the gap report at %s and file an issue or PR "
                           "(nothing was posted; keep private data out).",
                           report.gap_report.get("markdown"))
        return report

    # -- approvals --------------------------------------------------------

    @staticmethod
    @log_call
    def approve(report: EngineQualificationReport, user: Optional[str] = None,
                note: Optional[str] = None,
                engine_path: Optional[Union[str, Path]] = None) -> EngineApprovalStatus:
        """Save an approval from a fully equivalent qualification report.

        Writes ``<project>/.ras-commander/engine_approvals.json`` (the only
        write this module makes to a project). The inputs and the installed
        engine must still match the report.

        Args:
            report: Report from :meth:`validate_mesh` (or another registered check).
            user: Recorded approver (default: the signed-in user name).
            note: Optional free-text note.
            engine_path: Explicit engine executable for the version check.

        Returns:
            EngineApprovalStatus: The saved record, valid.

        Raises:
            ValueError: The report is not equivalent, or the inputs or engine changed.
        """
        if not report.equivalent:
            raise ValueError(f"cannot approve: report status is {report.status!r}, not equivalent")
        spec = _REGISTRY.get(report.engine)
        if spec is None or spec.fingerprint is None or spec.version_probe is None:
            raise ValueError(f"engine {report.engine!r} has no registered fingerprint and version probe")
        folder = Path(report.project_folder)
        current = spec.fingerprint(_project_ref(folder, report.project_file), report.scope)
        if current != report.fingerprints:
            changed = sorted(k for k in set(current) | set(report.fingerprints)
                             if current.get(k) != report.fingerprints.get(k))
            raise ValueError(f"cannot approve: inputs changed since validation: {changed}")
        identity = spec.version_probe(engine_path)
        for key in ("version", "git_commit", "executable_sha256"):
            if identity.get(key) != report.engine_identity.get(key):
                raise ValueError(f"cannot approve: engine {key} changed since validation "
                                 f"({report.engine_identity.get(key)} -> {identity.get(key)})")
        if not report.project_file:
            raise ValueError("cannot approve: the report does not name its project file")
        config = _normalize_config(report.config)
        record = {
            "id": _record_id(report.engine, report.scope, config, report.project_file),
            "engine": report.engine,
            "family": report.family,
            "scope": report.scope,
            "project_file": report.project_file,
            "config": config,
            "engine_version": identity.get("version"),
            "engine_git_commit": identity.get("git_commit"),
            "engine_executable_sha256": identity.get("executable_sha256"),
            "fingerprints": report.fingerprints,
            "reference": report.reference,
            "approved_utc": _utc_now(),
            "approved_by": user or getpass.getuser(),
            "ras_commander_version": _ras_commander_version(),
            "report_summary": report.summary(),
            "validated_utc": report.created_utc,
            "note": note,
        }
        with _store_lock(folder):
            data = _read_store(folder)
            data["approvals"] = [r for r in data["approvals"] if not (
                r.get("engine") == record["engine"] and r.get("scope") == record["scope"]
                and r.get("config") == record["config"]
                and _same_project_file(folder, r.get("project_file"), record["project_file"]))] + [record]
            _validate_store(data, _store_path(folder))
            path = _write_store(folder, data)
        logger.info("Saved %s approval for %s (%s) in %s", report.engine, report.scope,
                    record["id"], path.name)
        return EngineApprovalStatus(engine=report.engine, scope=report.scope, config=config,
                                    valid=True, reasons=[], record=record)

    @staticmethod
    @log_call
    def status(project: Optional[Union[str, Path, Any]] = None, engine: str = "fast-mesh",
               scope: Optional[Union[str, int, Path]] = None,
               config: Optional[Mapping[str, Any]] = None,
               engine_path: Optional[Union[str, Path]] = None) -> List[EngineApprovalStatus]:
        """Check saved approvals against the current inputs and installed engine.

        Approvals belong to one project file. A ``RasPrj``, a ``.prj`` path or a
        folder with a single ``.prj`` returns only that project's records; a
        folder holding several projects returns every project's records.

        Args:
            project: ``RasPrj``, project folder or ``.prj`` (default: global ``ras``).
            engine: Engine name.
            scope: Limit to one scope (for fast-mesh, the geometry: ``"02"``, ``"g02"``).
            config: Limit to records with exactly this configuration
                (for fast-mesh: ``profile``, ``repair``, ``seeds``).
            engine_path: Explicit engine executable for the version check.

        Returns:
            list[EngineApprovalStatus]: One entry per matching record, with
            ``valid`` and every reason it is not.
        """
        folder, prj_name = _project_identity(project)
        spec = _REGISTRY.get(engine)
        wanted_scope = _scope_of(engine, scope) if scope is not None else None
        wanted_config = _normalize_config(config) if config is not None else None
        records = [r for r in _read_store(folder)["approvals"] if r.get("engine") == engine
                   and (prj_name is None or _same_project_file(folder, r.get("project_file"), prj_name))
                   and (wanted_scope is None or r.get("scope") == wanted_scope)
                   and (wanted_config is None or r.get("config") == wanted_config)]
        identity: Optional[Dict[str, Any]] = None
        identity_error: Optional[str] = None
        if records and spec is not None and spec.version_probe is not None:
            try:
                identity = spec.version_probe(engine_path)
            except Exception as exc:
                identity_error = f"engine unavailable: {type(exc).__name__}"
        results = []
        for record in records:
            reasons: List[str] = []
            if spec is None or spec.fingerprint is None:
                reasons.append(f"engine {engine!r} is not registered with a fingerprint")
            else:
                saved_prints = record.get("fingerprints") or {}
                try:
                    current = spec.fingerprint(_project_ref(folder, record.get("project_file")),
                                               record["scope"])
                except (OSError, ValueError) as exc:
                    current = {}
                    reasons.append(f"inputs unavailable: {exc}")
                if not saved_prints:
                    reasons.append("no input fingerprints recorded")
                for key in sorted(set(current) - set(saved_prints)):
                    reasons.append(f"{key} not fingerprinted in the approval")
                for key, saved in sorted(saved_prints.items()):
                    now = current.get(key)
                    if now is None and current:
                        reasons.append(f"{key} no longer tracked")
                    elif now is not None and now.get("sha256") != saved.get("sha256"):
                        reasons.append(f"{key} changed" if now.get("sha256") else f"{key} missing")
            if spec is None or spec.version_probe is None:
                # Matching inputs alone never validate an approval: the engine's
                # identity must be checkable too.
                reasons.append(f"engine {engine!r} registration cannot check engine identity "
                               "(no version probe)")
            elif identity_error:
                reasons.append(identity_error)
            elif identity is not None:
                if identity.get("version") != record.get("engine_version"):
                    reasons.append(f"engine version changed ({record.get('engine_version')} -> "
                                   f"{identity.get('version')})")
                if identity.get("git_commit") != record.get("engine_git_commit"):
                    reasons.append("engine commit changed")
                if identity.get("executable_sha256") != record.get("engine_executable_sha256"):
                    reasons.append("engine executable changed")
            results.append(EngineApprovalStatus(engine=engine, scope=record["scope"],
                                                config=record.get("config") or {},
                                                valid=not reasons, reasons=reasons, record=record))
        return results

    @staticmethod
    @log_call
    def list_approvals(project: Optional[Union[str, Path, Any]] = None,
                       engine_path: Optional[Union[str, Path]] = None) -> pd.DataFrame:
        """List every saved approval with its current validity (schema ``engine_approvals``).

        Returns:
            pd.DataFrame: One row per record.
        """
        folder = _project_folder(project)
        engines = sorted({r.get("engine") for r in _read_store(folder)["approvals"]})
        rows = []
        for name in engines:
            for st in RasEngineQualification.status(folder, engine=name, engine_path=engine_path):
                rec = st.record or {}
                rows.append({
                    "engine": st.engine, "family": rec.get("family"), "scope": st.scope,
                    "config": json.dumps(st.config, sort_keys=True),
                    "engine_version": rec.get("engine_version"),
                    "hecras_version": (rec.get("reference") or {}).get("hecras_version"),
                    "approved_utc": rec.get("approved_utc"), "approved_by": rec.get("approved_by"),
                    "valid": st.valid, "reasons": "; ".join(st.reasons),
                })
        return pd.DataFrame(rows, columns=["engine", "family", "scope", "config", "engine_version",
                                           "hecras_version", "approved_utc", "approved_by",
                                           "valid", "reasons"])

    @staticmethod
    @log_call
    def revoke(project: Optional[Union[str, Path, Any]] = None, engine: str = "fast-mesh",
               scope: Optional[Union[str, int, Path]] = None,
               config: Optional[Mapping[str, Any]] = None) -> int:
        """Remove saved approvals; the project reverts to the native engine for them.

        Args:
            project: ``RasPrj``, project folder or ``.prj``.
            engine: Engine name.
            scope: Limit to one scope (default: every scope of ``engine``).
            config: Limit to exactly this configuration.

        Returns:
            int: Number of records removed.
        """
        folder, prj_name = _project_identity(project)
        if not _store_path(folder).is_file():
            return 0
        wanted_scope = _scope_of(engine, scope) if scope is not None else None
        wanted_config = _normalize_config(config) if config is not None else None
        with _store_lock(folder):
            data = _read_store(folder)
            keep = [r for r in data["approvals"] if not (
                r.get("engine") == engine
                and (prj_name is None or _same_project_file(folder, r.get("project_file"), prj_name))
                and (wanted_scope is None or r.get("scope") == wanted_scope)
                and (wanted_config is None or r.get("config") == wanted_config))]
            removed = len(data["approvals"]) - len(keep)
            if removed:
                data["approvals"] = keep
                _write_store(folder, data)
        if removed:
            logger.info("Revoked %d %s approval(s)", removed, engine)
        return removed

    @staticmethod
    @log_call
    def resolve_engine(project: Union[str, Path, Any], family: str,
                       scope: Optional[Union[str, int, Path]] = None,
                       config: Optional[Mapping[str, Any]] = None,
                       engine_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
        """Decide which engine runs by default for a family, scope and configuration.

        The platform default wins when the family has one. Otherwise the first
        registered engine with a valid approval runs; without one, the native
        engine runs. Only ``GeomMeshEngine.build_mesh(engine="auto")`` consults
        this today; the HDF, mapping and DSS paths are unchanged.

        Returns:
            dict: ``engine`` and ``reason``.
        """
        if family not in NATIVE_ENGINES:
            raise ValueError(f"family must be one of {sorted(NATIVE_ENGINES)}, got {family!r}")
        specs = [s for s in _REGISTRY.values() if s.family == family]
        for spec in specs:
            if spec.platform_default:
                return {"engine": spec.name, "reason": "platform default"}
        native = NATIVE_ENGINES[family]
        if any(s.validator is not None and s.fingerprint is not None for s in specs):
            _, prj_name = _project_identity(project)
            if prj_name is None:
                return {"engine": native, "reason": "no single project file identified; approvals "
                                                    "apply only to the .prj they were made for"}
        reasons = []
        for spec in specs:
            if spec.validator is None or spec.fingerprint is None:
                continue
            try:
                statuses = RasEngineQualification.status(project, engine=spec.name, scope=scope,
                                                         config=config, engine_path=engine_path)
            except ValueError as exc:  # unreadable or malformed store: fail safe to native
                logger.warning("Approval store unusable; using the native engine: %s", exc)
                reasons.append(f"approval store unusable: {exc}")
                continue
            for st in statuses:
                if st.valid:
                    return {"engine": spec.name,
                            "reason": f"valid approval ({st.record.get('approved_utc')}, "
                                      f"{spec.name} {st.record.get('engine_version')})",
                            # The exact build the approval names; callers must run
                            # only this build (see GeomMeshEngine.build_mesh).
                            "approved_identity": {
                                "version": st.record.get("engine_version"),
                                "git_commit": st.record.get("engine_git_commit"),
                                "executable_sha256": st.record.get("engine_executable_sha256")}}
                reasons.append(f"{spec.name} approval invalid: {', '.join(st.reasons)}")
            if not statuses:
                reasons.append(f"no {spec.name} approval")
        native = NATIVE_ENGINES[family]
        return {"engine": native, "reason": "; ".join(reasons) or "no approvable engine registered"}

    # -- gap reports ------------------------------------------------------

    @staticmethod
    @log_call
    def write_gap_report(report: EngineQualificationReport, output_dir: Union[str, Path],
                         include_project_data: bool = False) -> Dict[str, str]:
        """Write a gap-report bundle (markdown and JSON) for a non-equivalent result.

        By default the bundle holds no project data: area names become
        ``area-1``, ``area-2``, ..., and no coordinates, values, paths, project
        names or user names are written. ``include_project_data=True`` adds
        area names and file names; review the bundle before sharing it.

        The bundle includes a pre-filled GitHub issue for the fast-mesh
        repository and guidance for preparing a PR. Nothing is posted.

        Args:
            report: A qualification report.
            output_dir: Folder for ``fast-mesh-gap-report.md`` and ``.json``.
            include_project_data: Opt in to area and file names.

        Returns:
            dict: ``markdown`` and ``json`` paths.
        """
        from .geom._fast_mesh_engine import ISSUES_URL, REPOSITORY_STATUS, REPOSITORY_URL

        out = Path(output_dir)
        out.mkdir(parents=True, exist_ok=True)
        aliases = {a["name"]: (a["name"] if include_project_data else f"area-{i}")
                   for i, a in enumerate(report.areas, 1)}
        tables = report.tables
        mismatches = []
        if not tables.empty and "status" in tables:
            for _, row in tables[tables["status"] != "identical"].iterrows():
                area = row.get("area")
                mismatches.append({
                    "area": aliases.get(area, area if include_project_data else "area-?"),
                    "table": row.get("table"),
                    "status": row.get("status"),
                    "reference_shape": row.get("reference_shape"),
                    "candidate_shape": row.get("candidate_shape"),
                    "differing_elements": _int_or_none(row.get("differing_elements")),
                    "differing_rows": _int_or_none(row.get("differing_rows")),
                    "first_differing_row": _int_or_none(row.get("first_differing_row")),
                })
        checks = {}
        for name, value in report.checks.items():
            if not isinstance(value, dict):
                continue
            entry = {"passed": value.get("passed")}
            for key in ("codes", "reasons"):
                if value.get(key):
                    entry[key] = [c for c in value[key] if _SAFE_CODE.match(str(c))]
            if "code" in value and _SAFE_CODE.match(str(value["code"])):
                entry["code"] = value["code"]
            if "count" in value:
                entry["count"] = value["count"]
            if include_project_data and value.get("detail"):
                entry["detail"] = value["detail"]
            checks[name] = entry
        identity = report.engine_identity
        environment = {
            "engine": report.engine,
            "engine_version": identity.get("version"),
            "engine_git_commit": identity.get("git_commit"),
            "profile": report.config.get("profile"),
            "seeds": report.config.get("seeds"),
            "repair": report.config.get("repair"),
            "reference": f"HEC-RAS {report.reference.get('hecras_version')} via "
                         f"{report.reference.get('method')}",
            "ras_commander_version": report.ras_commander_version,
            "python": platform.python_version(),
            "platform": f"{platform.system()} {platform.machine()}",
        }
        area_cells = [{"area": aliases.get(a["name"]), "real_cells": a.get("real_cells")}
                      for a in report.areas]
        n_bad = len({(m["area"], m["table"]) for m in mismatches})
        title = (f"{report.config.get('profile')}: {report.status.replace('_', ' ')} vs HEC-RAS "
                 f"{report.reference.get('hecras_version')} ({n_bad} mesh table(s) differ, "
                 f"seeds {report.config.get('seeds')}, repair {report.config.get('repair')})")
        body = _issue_body(environment, report.summary(), mismatches, checks, area_cells,
                           include_project_data)
        bundle = {
            "schema": GAP_REPORT_SCHEMA,
            "created_utc": _utc_now(),
            "contains_project_data": bool(include_project_data),
            "status": report.status,
            "environment": environment,
            "summary": report.summary(),
            "areas": area_cells,
            "mismatching_tables": mismatches,
            "checks": checks,
            "issue": {"repository": REPOSITORY_URL, "new_issue_url": ISSUES_URL,
                      "repository_status": REPOSITORY_STATUS,
                      "title": title, "body": body},
            "posted": False,
        }
        json_path = out / f"{GAP_REPORT_STEM}.json"
        md_path = out / f"{GAP_REPORT_STEM}.md"
        json_path.write_text(json.dumps(bundle, indent=2, default=str) + "\n", encoding="utf-8")
        md_path.write_text(_gap_markdown(title, body, include_project_data), encoding="utf-8")
        logger.info("Wrote fast-mesh gap report (nothing posted): %s", md_path)
        return {"markdown": str(md_path), "json": str(json_path)}

register_engine staticmethod

Python
register_engine(spec: EngineSpec, replace: bool = False) -> EngineSpec

Register an engine and its equivalence check (extension point).

Parameters:

Name Type Description Default
spec EngineSpec

Engine registration. validator and fingerprint make approvals possible; without them the engine can only be the platform default or run by explicit request.

required
replace bool

Allow replacing an existing registration.

False

Returns:

Type Description
EngineSpec

The registered spec.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def register_engine(spec: EngineSpec, replace: bool = False) -> EngineSpec:
    """Register an engine and its equivalence check (extension point).

    Args:
        spec: Engine registration. ``validator`` and ``fingerprint`` make
            approvals possible; without them the engine can only be the
            platform default or run by explicit request.
        replace: Allow replacing an existing registration.

    Returns:
        EngineSpec: The registered spec.
    """
    if spec.family not in NATIVE_ENGINES:
        raise ValueError(f"family must be one of {sorted(NATIVE_ENGINES)}, got {spec.family!r}")
    if spec.name in _REGISTRY and not replace:
        raise ValueError(f"engine {spec.name!r} is already registered")
    _REGISTRY[spec.name] = spec
    return spec

unregister_engine staticmethod

Python
unregister_engine(name: str) -> None

Remove a registration added with :meth:register_engine. Built-ins are re-registered on reset.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def unregister_engine(name: str) -> None:
    """Remove a registration added with :meth:`register_engine`. Built-ins are re-registered on reset."""
    _REGISTRY.pop(name, None)
    if name in ("fast-mesh", "fast-hdf", "fast-map", "fast-dss", "fast-preprocess", "fast-unsteady"):
        _register_builtin()

registered_engines staticmethod

Python
registered_engines() -> pd.DataFrame

List registered engines (schema engine_registry).

Returns:

Type Description
DataFrame

engine, family, platform_default, status,

DataFrame

has_equivalence_check, description.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def registered_engines() -> pd.DataFrame:
    """List registered engines (schema ``engine_registry``).

    Returns:
        pd.DataFrame: ``engine``, ``family``, ``platform_default``, ``status``,
        ``has_equivalence_check``, ``description``.
    """
    return pd.DataFrame([
        {"engine": s.name, "family": s.family, "platform_default": s.platform_default,
         "status": s.status, "has_equivalence_check": s.validator is not None,
         "description": s.description}
        for s in _REGISTRY.values()
    ], columns=["engine", "family", "platform_default", "status",
                "has_equivalence_check", "description"])

validate staticmethod

Python
validate(engine: str, project: Optional[Union[str, Path, Any]] = None, **kwargs) -> EngineQualificationReport

Run the registered equivalence check for engine.

Raises:

Type Description
KeyError

Unknown engine.

NotImplementedError

The engine has no equivalence check yet.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def validate(engine: str, project: Optional[Union[str, Path, Any]] = None, **kwargs) -> EngineQualificationReport:
    """Run the registered equivalence check for ``engine``.

    Raises:
        KeyError: Unknown engine.
        NotImplementedError: The engine has no equivalence check yet.
    """
    spec = _REGISTRY.get(engine)
    if spec is None:
        raise KeyError(f"unknown engine {engine!r}; registered: {sorted(_REGISTRY)}")
    if spec.validator is None:
        raise NotImplementedError(
            f"{engine} has no per-project equivalence check in RAS Commander yet "
            f"(status {spec.status}). Register one with RasEngineQualification.register_engine. "
            "Its existing behaviour is unchanged.")
    return spec.validator(project, **kwargs)

compare_mesh_tables staticmethod

Python
compare_mesh_tables(reference_hdf: Union[str, Path], candidate_hdf: Union[str, Path]) -> pd.DataFrame

Compare the 15 mesh tables of every 2D area in two geometry HDF files.

Comparison is exact: same shape, same dtype, same bytes (-0.0 and 0.0 differ). Only counts and indices are reported, never values.

Parameters:

Name Type Description Default
reference_hdf Union[str, Path]

Native HEC-RAS geometry HDF (the reference).

required
candidate_hdf Union[str, Path]

Candidate geometry HDF (for example fast-mesh's).

required

Returns:

Type Description
DataFrame

One row per area and table (schema engine_mesh_qualification).

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def compare_mesh_tables(reference_hdf: Union[str, Path],
                        candidate_hdf: Union[str, Path]) -> pd.DataFrame:
    """Compare the 15 mesh tables of every 2D area in two geometry HDF files.

    Comparison is exact: same shape, same dtype, same bytes (``-0.0`` and
    ``0.0`` differ). Only counts and indices are reported, never values.

    Args:
        reference_hdf: Native HEC-RAS geometry HDF (the reference).
        candidate_hdf: Candidate geometry HDF (for example fast-mesh's).

    Returns:
        pd.DataFrame: One row per area and table (schema ``engine_mesh_qualification``).
    """
    import h5py

    rows = []
    with h5py.File(reference_hdf, "r") as ref, h5py.File(candidate_hdf, "r") as cand:
        ref_areas, cand_areas = _area_names(ref), _area_names(cand)
        ordered = ref_areas + [a for a in cand_areas if a not in ref_areas]
        for area in ordered:
            for table in MESH_TABLES:
                key = f"Geometry/2D Flow Areas/{area}/{table}"
                row = {"area": area, "table": table}
                in_ref, in_cand = key in ref, key in cand
                if not in_ref or not in_cand:
                    row.update(status="missing_reference" if not in_ref else "missing_candidate")
                    for col in ("reference_shape", "candidate_shape", "reference_dtype",
                                "candidate_dtype", "differing_elements", "differing_rows",
                                "first_differing_row", "max_abs_difference"):
                        row[col] = None
                else:
                    row.update(_compare_arrays(ref[key][()], cand[key][()]))
                rows.append(row)
    columns = ["area", "table", "status", "reference_shape", "candidate_shape",
               "reference_dtype", "candidate_dtype", "differing_elements",
               "differing_rows", "first_differing_row", "max_abs_difference"]
    return pd.DataFrame(rows, columns=columns)

validate_mesh staticmethod

Python
validate_mesh(project: Optional[Union[str, Path, Any]] = None, geometry: Union[str, int, Path] = None, profile: str = 'hec701-exact', repair: bool = False, seeds: str = 'stored', plan: Optional[Union[str, int]] = None, hecras_version: str = '7.0.1', workspace: Optional[Union[str, Path]] = None, keep_projects: bool = False, engine_path: Optional[Union[str, Path]] = None, timeout: float = 3600, write_gap_report: bool = True, ras_object: Optional[Any] = None) -> EngineQualificationReport

Prove (or disprove) that fast-mesh reproduces HEC-RAS's mesh for one geometry.

Run this on your own project before relying on the experimental fast-mesh engine. The source project is never modified:

  1. The native reference is built on a staged copy: HEC-RAS hecras_version geometry preprocessing through GeomPreprocessor.run_geometry_preprocessor (after GeomMesh.generate_all when seeds="generated").
  2. fast-mesh meshes another copy (mesh --out-dir) from the source geometry text and source geometry HDF.
  3. The 15 mesh tables of every 2D area are compared byte for byte, and the run manifest is checked (schema, validation, profile and label, official_equivalent, output hashes, warnings).
  4. The source tree fingerprint is checked before and after.

When the result is not equivalent and the native reference succeeded, a gap report (markdown and JSON, no project data) is written to the workspace. Nothing is posted. When it is equivalent, call report.approve() to let engine="auto" use fast-mesh for this geometry and these settings.

Parameters:

Name Type Description Default
project Optional[Union[str, Path, Any]]

RasPrj, project folder or .prj (default: ras_object).

None
geometry Union[str, int, Path]

Geometry number, "gNN" or .g## path.

None
profile str

Must be "hec701-exact"; RAS2025 has no native reference here.

'hec701-exact'
repair bool

fast-mesh --repair (and native GeomMesh.generate_all repair).

False
seeds str

"stored" (default) or "generated".

'stored'
plan Optional[Union[str, int]]

Plan for native preprocessing (default: first plan using the geometry).

None
hecras_version str

Reference HEC-RAS version (default "7.0.1").

'7.0.1'
workspace Optional[Union[str, Path]]

Folder for staged copies and reports (default: a new temp folder). Keep it short; HEC-RAS needs short paths.

None
keep_projects bool

Keep the two meshed project copies after comparison.

False
engine_path Optional[Union[str, Path]]

Explicit fast-mesh executable.

None
timeout float

Seconds allowed for each engine run.

3600
write_gap_report bool

Write the gap-report bundle on non-equivalence.

True
ras_object Optional[Any]

Optional RasPrj for the source project.

None

Returns:

Type Description
EngineQualificationReport

status is equivalent,

EngineQualificationReport

not_equivalent, fast_mesh_failed, comparison_failed (an

EngineQualificationReport

output could not be compared), native_reference_failed, or

EngineQualificationReport

reference_not_qualifying (the reference was not HEC-RAS 7.0.1, which

EngineQualificationReport

hec701-exact requires), or engine_changed (the fast-mesh

EngineQualificationReport

executable resolved at the start is not the build that produced the

EngineQualificationReport

candidate). Only equivalent can be approved.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def validate_mesh(
    project: Optional[Union[str, Path, Any]] = None,
    geometry: Union[str, int, Path] = None,
    profile: str = "hec701-exact",
    repair: bool = False,
    seeds: str = "stored",
    plan: Optional[Union[str, int]] = None,
    hecras_version: str = "7.0.1",
    workspace: Optional[Union[str, Path]] = None,
    keep_projects: bool = False,
    engine_path: Optional[Union[str, Path]] = None,
    timeout: float = 3600,
    write_gap_report: bool = True,
    ras_object: Optional[Any] = None,
) -> EngineQualificationReport:
    """Prove (or disprove) that fast-mesh reproduces HEC-RAS's mesh for one geometry.

    Run this on your own project before relying on the experimental
    fast-mesh engine. The source project is never modified:

    1. The native reference is built on a staged copy: HEC-RAS
       ``hecras_version`` geometry preprocessing through
       ``GeomPreprocessor.run_geometry_preprocessor`` (after
       ``GeomMesh.generate_all`` when ``seeds="generated"``).
    2. fast-mesh meshes another copy (``mesh --out-dir``) from the source
       geometry text and source geometry HDF.
    3. The 15 mesh tables of every 2D area are compared byte for byte, and
       the run manifest is checked (schema, validation, profile and label,
       ``official_equivalent``, output hashes, warnings).
    4. The source tree fingerprint is checked before and after.

    When the result is not equivalent and the native reference succeeded,
    a gap report (markdown and JSON, no project data) is written to the
    workspace. Nothing is posted. When it is equivalent, call
    ``report.approve()`` to let ``engine="auto"`` use fast-mesh for this
    geometry and these settings.

    Args:
        project: ``RasPrj``, project folder or ``.prj`` (default: ``ras_object``).
        geometry: Geometry number, ``"gNN"`` or ``.g##`` path.
        profile: Must be ``"hec701-exact"``; RAS2025 has no native reference here.
        repair: fast-mesh ``--repair`` (and native ``GeomMesh.generate_all`` repair).
        seeds: ``"stored"`` (default) or ``"generated"``.
        plan: Plan for native preprocessing (default: first plan using the geometry).
        hecras_version: Reference HEC-RAS version (default ``"7.0.1"``).
        workspace: Folder for staged copies and reports (default: a new temp folder).
            Keep it short; HEC-RAS needs short paths.
        keep_projects: Keep the two meshed project copies after comparison.
        engine_path: Explicit fast-mesh executable.
        timeout: Seconds allowed for each engine run.
        write_gap_report: Write the gap-report bundle on non-equivalence.
        ras_object: Optional ``RasPrj`` for the source project.

    Returns:
        EngineQualificationReport: ``status`` is ``equivalent``,
        ``not_equivalent``, ``fast_mesh_failed``, ``comparison_failed`` (an
        output could not be compared), ``native_reference_failed``, or
        ``reference_not_qualifying`` (the reference was not HEC-RAS 7.0.1, which
        ``hec701-exact`` requires), or ``engine_changed`` (the fast-mesh
        executable resolved at the start is not the build that produced the
        candidate). Only ``equivalent`` can be approved.
    """
    from .geom import _fast_mesh_engine as engine
    from .geom.GeomMeshEngine import GeomMeshEngine, _geometry_suffix, resolve_project_files
    from .RasQualification import RasQualification

    if profile not in engine.QUALIFIABLE_PROFILES:
        raise NotImplementedError(
            f"profile {profile!r} cannot be qualified through RAS Commander: there is no "
            "native reference for it. Only 'hec701-exact' (HEC-RAS 7.0.1) is qualifiable.")
    if seeds not in engine.SEED_SOURCES:
        raise ValueError(f"seeds must be one of {engine.SEED_SOURCES}, got {seeds!r}")
    files = resolve_project_files(project if project is not None else ras_object, geometry,
                                  ras_object)
    source = files["project_folder"]
    scope = _geometry_suffix(files["geometry_file"])
    config = {"profile": profile, "repair": bool(repair), "seeds": seeds}
    if workspace is not None:
        requested = Path(workspace).absolute().resolve()
        if requested == source or source in requested.parents:
            raise ValueError(f"workspace must be outside the source project: {requested}")
    # Resolve the engine once and pin that executable for the whole validation,
    # so the report can only credit the build that produced the candidate.
    resolved_engine = engine.engine_info(engine_path)
    pinned_executable = resolved_engine["executable"]
    identity = {k: resolved_engine[k] for k in _IDENTITY_KEYS}
    before = RasQualification.project_tree_fingerprint(source)
    fingerprints = _mesh_fingerprint(files["project_file"], scope)
    if workspace is None:
        work = Path(tempfile.mkdtemp(prefix="rasq-mesh-"))
    else:
        requested.mkdir(parents=True, exist_ok=True)
        work = Path(tempfile.mkdtemp(prefix=f"mesh-{scope}-", dir=requested))
    logger.info("Validating fast-mesh %s (%s, seeds %s, repair %s) against HEC-RAS %s for %s",
                identity["version"], profile, seeds, repair, _version_label(hecras_version), scope)
    report = EngineQualificationReport(
        engine="fast-mesh", family="mesh", scope=scope, config=config,
        project_folder=str(source), project_file=files["project_file"].name,
        equivalent=False, status="running",
        engine_identity=identity,
        reference={"hecras_version": _version_label(hecras_version), "method":
                   "GeomPreprocessor.run_geometry_preprocessor", "plan": None},
        fingerprints=fingerprints, workspace=str(work), created_utc=_utc_now(),
        ras_commander_version=_ras_commander_version())

    native_dir = work / "native" / source.name
    fast_dir = work / "fast-mesh" / source.name
    native = fast = None
    try:
        try:
            native = GeomMeshEngine.build_mesh(
                files["geometry_file"], native_dir, engine="native", seeds=seeds, repair=repair,
                plan=plan, hecras_version=hecras_version, timeout=timeout,
                project=files["project_file"])
            report.reference["plan"] = native.engine_details.get("plan")
            report.reference["hecras_version_resolved"] = native.engine_version
        except Exception as exc:  # native failure is not an engine gap
            report.status = "native_reference_failed"
            report.checks["native_reference"] = {"passed": False, "error": type(exc).__name__,
                                                 "detail": str(exc)[:2000]}
            logger.error("Native reference failed; fast-mesh not judged: %s", exc)
        if native is not None:
            report.checks["native_reference"] = {"passed": True}
            # hec701-exact claims HEC-RAS 7.0.1 equivalence, so only a 7.0.1
            # reference can qualify it (the resolved install's version folder).
            resolved = str(native.engine_version)
            report.checks["reference_version"] = {
                "passed": resolved == REFERENCE_VERSIONS[profile],
                "required": REFERENCE_VERSIONS[profile], "value": _version_label(resolved)}
            if not report.checks["reference_version"]["passed"]:
                report.status = "reference_not_qualifying"
            try:
                fast = GeomMeshEngine.build_mesh(
                    files["geometry_file"], fast_dir, engine="fast-mesh", profile=profile,
                    seeds=seeds, repair=repair, engine_path=pinned_executable, timeout=timeout,
                    project=files["project_file"])
                report.checks["fast_mesh_run"] = {"passed": True}
                built = {k: fast.engine_details.get(k) for k in _IDENTITY_KEYS}
                changed = sorted(k for k in _IDENTITY_KEYS if built[k] != identity[k])
                report.checks["engine_identity"] = {"passed": not changed, "changed": changed}
                if changed:
                    if report.status == "running":
                        report.status = "engine_changed"
                    logger.error("The fast-mesh executable changed during validation (%s); "
                                 "the result is not credited to either build.", ", ".join(changed))
            except engine.FastMeshEngineError as exc:
                if report.status == "running":
                    report.status = "fast_mesh_failed"
                report.checks["fast_mesh_run"] = {"passed": False, "code": exc.code,
                                                  "area": exc.area, "detail": exc.message[:2000]}
            if fast is not None:
                try:
                    report.tables = RasEngineQualification.compare_mesh_tables(
                        native.geometry_hdf, fast.geometry_hdf)
                    hashes = engine.verify_outputs(fast.manifest, fast.project_folder, expected={
                        "geometry_hdf": fast.geometry_hdf.name,
                        "geometry_text": fast.geometry_file.name})
                    report.checks.update(_manifest_checks(fast.manifest, hashes, profile))
                    import h5py
                    with h5py.File(native.geometry_hdf, "r") as ref:
                        report.areas = [{"name": a, "real_cells": _cell_count(ref, a)}
                                        for a in _area_names(ref)]
                    tables_ok = not report.tables.empty and bool(
                        (report.tables["status"] == "identical").all())
                    report.checks["mesh_tables"] = {
                        "passed": tables_ok,
                        "identical": int((report.tables["status"] == "identical").sum()),
                        "compared": int(len(report.tables))}
                except Exception as exc:  # unreadable/unsupported HDF: not equivalent
                    if report.status == "running":
                        report.status = "comparison_failed"
                    report.checks["mesh_comparison"] = {
                        "passed": False, "error": type(exc).__name__, "detail": str(exc)[:2000]}
                    logger.error("Mesh comparison failed; reported as not equivalent: %s", exc)
        if report.tables.empty and "table" not in report.tables:
            report.tables = pd.DataFrame(columns=["area", "table", "status"])
    finally:
        # Always check the source and clean up, whatever failed above.
        after = RasQualification.project_tree_fingerprint(source)
        report.source_unchanged = before == after
        report.checks["source_unchanged"] = {"passed": report.source_unchanged}
        if not keep_projects:
            for folder in (work / "native", work / "fast-mesh"):
                shutil.rmtree(folder, ignore_errors=True)
    if report.status == "running":
        report.equivalent = all(v.get("passed") for v in report.checks.values()
                                if isinstance(v, dict) and "passed" in v)
        report.status = "equivalent" if report.equivalent else "not_equivalent"
    else:
        report.equivalent = False
    if (not report.equivalent and write_gap_report
            and report.status not in ("native_reference_failed", "reference_not_qualifying",
                                      "engine_changed")):
        report.gap_report = RasEngineQualification.write_gap_report(report, work / "gap-report")
    report_path = work / "qualification_report.json"
    report.report_path = str(report_path)
    report_path.write_text(json.dumps(report.to_dict(), indent=2, default=str) + "\n",
                           encoding="utf-8")
    summary = report.summary()
    logger.info("fast-mesh qualification for %s: %s (%d/%d tables identical)", scope,
                report.status, summary["tables_identical"], summary["tables_compared"])
    if report.equivalent:
        logger.info("Equivalent. Call report.approve() to let engine='auto' use fast-mesh "
                    "for %s with these settings.", scope)
    elif report.gap_report:
        logger.warning("Not equivalent. Review the gap report at %s and file an issue or PR "
                       "(nothing was posted; keep private data out).",
                       report.gap_report.get("markdown"))
    return report

approve staticmethod

Python
approve(report: EngineQualificationReport, user: Optional[str] = None, note: Optional[str] = None, engine_path: Optional[Union[str, Path]] = None) -> EngineApprovalStatus

Save an approval from a fully equivalent qualification report.

Writes <project>/.ras-commander/engine_approvals.json (the only write this module makes to a project). The inputs and the installed engine must still match the report.

Parameters:

Name Type Description Default
report EngineQualificationReport

Report from :meth:validate_mesh (or another registered check).

required
user Optional[str]

Recorded approver (default: the signed-in user name).

None
note Optional[str]

Optional free-text note.

None
engine_path Optional[Union[str, Path]]

Explicit engine executable for the version check.

None

Returns:

Type Description
EngineApprovalStatus

The saved record, valid.

Raises:

Type Description
ValueError

The report is not equivalent, or the inputs or engine changed.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def approve(report: EngineQualificationReport, user: Optional[str] = None,
            note: Optional[str] = None,
            engine_path: Optional[Union[str, Path]] = None) -> EngineApprovalStatus:
    """Save an approval from a fully equivalent qualification report.

    Writes ``<project>/.ras-commander/engine_approvals.json`` (the only
    write this module makes to a project). The inputs and the installed
    engine must still match the report.

    Args:
        report: Report from :meth:`validate_mesh` (or another registered check).
        user: Recorded approver (default: the signed-in user name).
        note: Optional free-text note.
        engine_path: Explicit engine executable for the version check.

    Returns:
        EngineApprovalStatus: The saved record, valid.

    Raises:
        ValueError: The report is not equivalent, or the inputs or engine changed.
    """
    if not report.equivalent:
        raise ValueError(f"cannot approve: report status is {report.status!r}, not equivalent")
    spec = _REGISTRY.get(report.engine)
    if spec is None or spec.fingerprint is None or spec.version_probe is None:
        raise ValueError(f"engine {report.engine!r} has no registered fingerprint and version probe")
    folder = Path(report.project_folder)
    current = spec.fingerprint(_project_ref(folder, report.project_file), report.scope)
    if current != report.fingerprints:
        changed = sorted(k for k in set(current) | set(report.fingerprints)
                         if current.get(k) != report.fingerprints.get(k))
        raise ValueError(f"cannot approve: inputs changed since validation: {changed}")
    identity = spec.version_probe(engine_path)
    for key in ("version", "git_commit", "executable_sha256"):
        if identity.get(key) != report.engine_identity.get(key):
            raise ValueError(f"cannot approve: engine {key} changed since validation "
                             f"({report.engine_identity.get(key)} -> {identity.get(key)})")
    if not report.project_file:
        raise ValueError("cannot approve: the report does not name its project file")
    config = _normalize_config(report.config)
    record = {
        "id": _record_id(report.engine, report.scope, config, report.project_file),
        "engine": report.engine,
        "family": report.family,
        "scope": report.scope,
        "project_file": report.project_file,
        "config": config,
        "engine_version": identity.get("version"),
        "engine_git_commit": identity.get("git_commit"),
        "engine_executable_sha256": identity.get("executable_sha256"),
        "fingerprints": report.fingerprints,
        "reference": report.reference,
        "approved_utc": _utc_now(),
        "approved_by": user or getpass.getuser(),
        "ras_commander_version": _ras_commander_version(),
        "report_summary": report.summary(),
        "validated_utc": report.created_utc,
        "note": note,
    }
    with _store_lock(folder):
        data = _read_store(folder)
        data["approvals"] = [r for r in data["approvals"] if not (
            r.get("engine") == record["engine"] and r.get("scope") == record["scope"]
            and r.get("config") == record["config"]
            and _same_project_file(folder, r.get("project_file"), record["project_file"]))] + [record]
        _validate_store(data, _store_path(folder))
        path = _write_store(folder, data)
    logger.info("Saved %s approval for %s (%s) in %s", report.engine, report.scope,
                record["id"], path.name)
    return EngineApprovalStatus(engine=report.engine, scope=report.scope, config=config,
                                valid=True, reasons=[], record=record)

status staticmethod

Python
status(project: Optional[Union[str, Path, Any]] = None, engine: str = 'fast-mesh', scope: Optional[Union[str, int, Path]] = None, config: Optional[Mapping[str, Any]] = None, engine_path: Optional[Union[str, Path]] = None) -> List[EngineApprovalStatus]

Check saved approvals against the current inputs and installed engine.

Approvals belong to one project file. A RasPrj, a .prj path or a folder with a single .prj returns only that project's records; a folder holding several projects returns every project's records.

Parameters:

Name Type Description Default
project Optional[Union[str, Path, Any]]

RasPrj, project folder or .prj (default: global ras).

None
engine str

Engine name.

'fast-mesh'
scope Optional[Union[str, int, Path]]

Limit to one scope (for fast-mesh, the geometry: "02", "g02").

None
config Optional[Mapping[str, Any]]

Limit to records with exactly this configuration (for fast-mesh: profile, repair, seeds).

None
engine_path Optional[Union[str, Path]]

Explicit engine executable for the version check.

None

Returns:

Type Description
list[EngineApprovalStatus]

One entry per matching record, with

List[EngineApprovalStatus]

valid and every reason it is not.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def status(project: Optional[Union[str, Path, Any]] = None, engine: str = "fast-mesh",
           scope: Optional[Union[str, int, Path]] = None,
           config: Optional[Mapping[str, Any]] = None,
           engine_path: Optional[Union[str, Path]] = None) -> List[EngineApprovalStatus]:
    """Check saved approvals against the current inputs and installed engine.

    Approvals belong to one project file. A ``RasPrj``, a ``.prj`` path or a
    folder with a single ``.prj`` returns only that project's records; a
    folder holding several projects returns every project's records.

    Args:
        project: ``RasPrj``, project folder or ``.prj`` (default: global ``ras``).
        engine: Engine name.
        scope: Limit to one scope (for fast-mesh, the geometry: ``"02"``, ``"g02"``).
        config: Limit to records with exactly this configuration
            (for fast-mesh: ``profile``, ``repair``, ``seeds``).
        engine_path: Explicit engine executable for the version check.

    Returns:
        list[EngineApprovalStatus]: One entry per matching record, with
        ``valid`` and every reason it is not.
    """
    folder, prj_name = _project_identity(project)
    spec = _REGISTRY.get(engine)
    wanted_scope = _scope_of(engine, scope) if scope is not None else None
    wanted_config = _normalize_config(config) if config is not None else None
    records = [r for r in _read_store(folder)["approvals"] if r.get("engine") == engine
               and (prj_name is None or _same_project_file(folder, r.get("project_file"), prj_name))
               and (wanted_scope is None or r.get("scope") == wanted_scope)
               and (wanted_config is None or r.get("config") == wanted_config)]
    identity: Optional[Dict[str, Any]] = None
    identity_error: Optional[str] = None
    if records and spec is not None and spec.version_probe is not None:
        try:
            identity = spec.version_probe(engine_path)
        except Exception as exc:
            identity_error = f"engine unavailable: {type(exc).__name__}"
    results = []
    for record in records:
        reasons: List[str] = []
        if spec is None or spec.fingerprint is None:
            reasons.append(f"engine {engine!r} is not registered with a fingerprint")
        else:
            saved_prints = record.get("fingerprints") or {}
            try:
                current = spec.fingerprint(_project_ref(folder, record.get("project_file")),
                                           record["scope"])
            except (OSError, ValueError) as exc:
                current = {}
                reasons.append(f"inputs unavailable: {exc}")
            if not saved_prints:
                reasons.append("no input fingerprints recorded")
            for key in sorted(set(current) - set(saved_prints)):
                reasons.append(f"{key} not fingerprinted in the approval")
            for key, saved in sorted(saved_prints.items()):
                now = current.get(key)
                if now is None and current:
                    reasons.append(f"{key} no longer tracked")
                elif now is not None and now.get("sha256") != saved.get("sha256"):
                    reasons.append(f"{key} changed" if now.get("sha256") else f"{key} missing")
        if spec is None or spec.version_probe is None:
            # Matching inputs alone never validate an approval: the engine's
            # identity must be checkable too.
            reasons.append(f"engine {engine!r} registration cannot check engine identity "
                           "(no version probe)")
        elif identity_error:
            reasons.append(identity_error)
        elif identity is not None:
            if identity.get("version") != record.get("engine_version"):
                reasons.append(f"engine version changed ({record.get('engine_version')} -> "
                               f"{identity.get('version')})")
            if identity.get("git_commit") != record.get("engine_git_commit"):
                reasons.append("engine commit changed")
            if identity.get("executable_sha256") != record.get("engine_executable_sha256"):
                reasons.append("engine executable changed")
        results.append(EngineApprovalStatus(engine=engine, scope=record["scope"],
                                            config=record.get("config") or {},
                                            valid=not reasons, reasons=reasons, record=record))
    return results

list_approvals staticmethod

Python
list_approvals(project: Optional[Union[str, Path, Any]] = None, engine_path: Optional[Union[str, Path]] = None) -> pd.DataFrame

List every saved approval with its current validity (schema engine_approvals).

Returns:

Type Description
DataFrame

One row per record.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def list_approvals(project: Optional[Union[str, Path, Any]] = None,
                   engine_path: Optional[Union[str, Path]] = None) -> pd.DataFrame:
    """List every saved approval with its current validity (schema ``engine_approvals``).

    Returns:
        pd.DataFrame: One row per record.
    """
    folder = _project_folder(project)
    engines = sorted({r.get("engine") for r in _read_store(folder)["approvals"]})
    rows = []
    for name in engines:
        for st in RasEngineQualification.status(folder, engine=name, engine_path=engine_path):
            rec = st.record or {}
            rows.append({
                "engine": st.engine, "family": rec.get("family"), "scope": st.scope,
                "config": json.dumps(st.config, sort_keys=True),
                "engine_version": rec.get("engine_version"),
                "hecras_version": (rec.get("reference") or {}).get("hecras_version"),
                "approved_utc": rec.get("approved_utc"), "approved_by": rec.get("approved_by"),
                "valid": st.valid, "reasons": "; ".join(st.reasons),
            })
    return pd.DataFrame(rows, columns=["engine", "family", "scope", "config", "engine_version",
                                       "hecras_version", "approved_utc", "approved_by",
                                       "valid", "reasons"])

revoke staticmethod

Python
revoke(project: Optional[Union[str, Path, Any]] = None, engine: str = 'fast-mesh', scope: Optional[Union[str, int, Path]] = None, config: Optional[Mapping[str, Any]] = None) -> int

Remove saved approvals; the project reverts to the native engine for them.

Parameters:

Name Type Description Default
project Optional[Union[str, Path, Any]]

RasPrj, project folder or .prj.

None
engine str

Engine name.

'fast-mesh'
scope Optional[Union[str, int, Path]]

Limit to one scope (default: every scope of engine).

None
config Optional[Mapping[str, Any]]

Limit to exactly this configuration.

None

Returns:

Type Description
int

Number of records removed.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def revoke(project: Optional[Union[str, Path, Any]] = None, engine: str = "fast-mesh",
           scope: Optional[Union[str, int, Path]] = None,
           config: Optional[Mapping[str, Any]] = None) -> int:
    """Remove saved approvals; the project reverts to the native engine for them.

    Args:
        project: ``RasPrj``, project folder or ``.prj``.
        engine: Engine name.
        scope: Limit to one scope (default: every scope of ``engine``).
        config: Limit to exactly this configuration.

    Returns:
        int: Number of records removed.
    """
    folder, prj_name = _project_identity(project)
    if not _store_path(folder).is_file():
        return 0
    wanted_scope = _scope_of(engine, scope) if scope is not None else None
    wanted_config = _normalize_config(config) if config is not None else None
    with _store_lock(folder):
        data = _read_store(folder)
        keep = [r for r in data["approvals"] if not (
            r.get("engine") == engine
            and (prj_name is None or _same_project_file(folder, r.get("project_file"), prj_name))
            and (wanted_scope is None or r.get("scope") == wanted_scope)
            and (wanted_config is None or r.get("config") == wanted_config))]
        removed = len(data["approvals"]) - len(keep)
        if removed:
            data["approvals"] = keep
            _write_store(folder, data)
    if removed:
        logger.info("Revoked %d %s approval(s)", removed, engine)
    return removed

resolve_engine staticmethod

Python
resolve_engine(project: Union[str, Path, Any], family: str, scope: Optional[Union[str, int, Path]] = None, config: Optional[Mapping[str, Any]] = None, engine_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]

Decide which engine runs by default for a family, scope and configuration.

The platform default wins when the family has one. Otherwise the first registered engine with a valid approval runs; without one, the native engine runs. Only GeomMeshEngine.build_mesh(engine="auto") consults this today; the HDF, mapping and DSS paths are unchanged.

Returns:

Type Description
dict

engine and reason.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def resolve_engine(project: Union[str, Path, Any], family: str,
                   scope: Optional[Union[str, int, Path]] = None,
                   config: Optional[Mapping[str, Any]] = None,
                   engine_path: Optional[Union[str, Path]] = None) -> Dict[str, Any]:
    """Decide which engine runs by default for a family, scope and configuration.

    The platform default wins when the family has one. Otherwise the first
    registered engine with a valid approval runs; without one, the native
    engine runs. Only ``GeomMeshEngine.build_mesh(engine="auto")`` consults
    this today; the HDF, mapping and DSS paths are unchanged.

    Returns:
        dict: ``engine`` and ``reason``.
    """
    if family not in NATIVE_ENGINES:
        raise ValueError(f"family must be one of {sorted(NATIVE_ENGINES)}, got {family!r}")
    specs = [s for s in _REGISTRY.values() if s.family == family]
    for spec in specs:
        if spec.platform_default:
            return {"engine": spec.name, "reason": "platform default"}
    native = NATIVE_ENGINES[family]
    if any(s.validator is not None and s.fingerprint is not None for s in specs):
        _, prj_name = _project_identity(project)
        if prj_name is None:
            return {"engine": native, "reason": "no single project file identified; approvals "
                                                "apply only to the .prj they were made for"}
    reasons = []
    for spec in specs:
        if spec.validator is None or spec.fingerprint is None:
            continue
        try:
            statuses = RasEngineQualification.status(project, engine=spec.name, scope=scope,
                                                     config=config, engine_path=engine_path)
        except ValueError as exc:  # unreadable or malformed store: fail safe to native
            logger.warning("Approval store unusable; using the native engine: %s", exc)
            reasons.append(f"approval store unusable: {exc}")
            continue
        for st in statuses:
            if st.valid:
                return {"engine": spec.name,
                        "reason": f"valid approval ({st.record.get('approved_utc')}, "
                                  f"{spec.name} {st.record.get('engine_version')})",
                        # The exact build the approval names; callers must run
                        # only this build (see GeomMeshEngine.build_mesh).
                        "approved_identity": {
                            "version": st.record.get("engine_version"),
                            "git_commit": st.record.get("engine_git_commit"),
                            "executable_sha256": st.record.get("engine_executable_sha256")}}
            reasons.append(f"{spec.name} approval invalid: {', '.join(st.reasons)}")
        if not statuses:
            reasons.append(f"no {spec.name} approval")
    native = NATIVE_ENGINES[family]
    return {"engine": native, "reason": "; ".join(reasons) or "no approvable engine registered"}

write_gap_report staticmethod

Python
write_gap_report(report: EngineQualificationReport, output_dir: Union[str, Path], include_project_data: bool = False) -> Dict[str, str]

Write a gap-report bundle (markdown and JSON) for a non-equivalent result.

By default the bundle holds no project data: area names become area-1, area-2, ..., and no coordinates, values, paths, project names or user names are written. include_project_data=True adds area names and file names; review the bundle before sharing it.

The bundle includes a pre-filled GitHub issue for the fast-mesh repository and guidance for preparing a PR. Nothing is posted.

Parameters:

Name Type Description Default
report EngineQualificationReport

A qualification report.

required
output_dir Union[str, Path]

Folder for fast-mesh-gap-report.md and .json.

required
include_project_data bool

Opt in to area and file names.

False

Returns:

Type Description
dict

markdown and json paths.

Source code in ras_commander/RasEngineQualification.py
Python
@staticmethod
@log_call
def write_gap_report(report: EngineQualificationReport, output_dir: Union[str, Path],
                     include_project_data: bool = False) -> Dict[str, str]:
    """Write a gap-report bundle (markdown and JSON) for a non-equivalent result.

    By default the bundle holds no project data: area names become
    ``area-1``, ``area-2``, ..., and no coordinates, values, paths, project
    names or user names are written. ``include_project_data=True`` adds
    area names and file names; review the bundle before sharing it.

    The bundle includes a pre-filled GitHub issue for the fast-mesh
    repository and guidance for preparing a PR. Nothing is posted.

    Args:
        report: A qualification report.
        output_dir: Folder for ``fast-mesh-gap-report.md`` and ``.json``.
        include_project_data: Opt in to area and file names.

    Returns:
        dict: ``markdown`` and ``json`` paths.
    """
    from .geom._fast_mesh_engine import ISSUES_URL, REPOSITORY_STATUS, REPOSITORY_URL

    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)
    aliases = {a["name"]: (a["name"] if include_project_data else f"area-{i}")
               for i, a in enumerate(report.areas, 1)}
    tables = report.tables
    mismatches = []
    if not tables.empty and "status" in tables:
        for _, row in tables[tables["status"] != "identical"].iterrows():
            area = row.get("area")
            mismatches.append({
                "area": aliases.get(area, area if include_project_data else "area-?"),
                "table": row.get("table"),
                "status": row.get("status"),
                "reference_shape": row.get("reference_shape"),
                "candidate_shape": row.get("candidate_shape"),
                "differing_elements": _int_or_none(row.get("differing_elements")),
                "differing_rows": _int_or_none(row.get("differing_rows")),
                "first_differing_row": _int_or_none(row.get("first_differing_row")),
            })
    checks = {}
    for name, value in report.checks.items():
        if not isinstance(value, dict):
            continue
        entry = {"passed": value.get("passed")}
        for key in ("codes", "reasons"):
            if value.get(key):
                entry[key] = [c for c in value[key] if _SAFE_CODE.match(str(c))]
        if "code" in value and _SAFE_CODE.match(str(value["code"])):
            entry["code"] = value["code"]
        if "count" in value:
            entry["count"] = value["count"]
        if include_project_data and value.get("detail"):
            entry["detail"] = value["detail"]
        checks[name] = entry
    identity = report.engine_identity
    environment = {
        "engine": report.engine,
        "engine_version": identity.get("version"),
        "engine_git_commit": identity.get("git_commit"),
        "profile": report.config.get("profile"),
        "seeds": report.config.get("seeds"),
        "repair": report.config.get("repair"),
        "reference": f"HEC-RAS {report.reference.get('hecras_version')} via "
                     f"{report.reference.get('method')}",
        "ras_commander_version": report.ras_commander_version,
        "python": platform.python_version(),
        "platform": f"{platform.system()} {platform.machine()}",
    }
    area_cells = [{"area": aliases.get(a["name"]), "real_cells": a.get("real_cells")}
                  for a in report.areas]
    n_bad = len({(m["area"], m["table"]) for m in mismatches})
    title = (f"{report.config.get('profile')}: {report.status.replace('_', ' ')} vs HEC-RAS "
             f"{report.reference.get('hecras_version')} ({n_bad} mesh table(s) differ, "
             f"seeds {report.config.get('seeds')}, repair {report.config.get('repair')})")
    body = _issue_body(environment, report.summary(), mismatches, checks, area_cells,
                       include_project_data)
    bundle = {
        "schema": GAP_REPORT_SCHEMA,
        "created_utc": _utc_now(),
        "contains_project_data": bool(include_project_data),
        "status": report.status,
        "environment": environment,
        "summary": report.summary(),
        "areas": area_cells,
        "mismatching_tables": mismatches,
        "checks": checks,
        "issue": {"repository": REPOSITORY_URL, "new_issue_url": ISSUES_URL,
                  "repository_status": REPOSITORY_STATUS,
                  "title": title, "body": body},
        "posted": False,
    }
    json_path = out / f"{GAP_REPORT_STEM}.json"
    md_path = out / f"{GAP_REPORT_STEM}.md"
    json_path.write_text(json.dumps(bundle, indent=2, default=str) + "\n", encoding="utf-8")
    md_path.write_text(_gap_markdown(title, body, include_project_data), encoding="utf-8")
    logger.info("Wrote fast-mesh gap report (nothing posted): %s", md_path)
    return {"markdown": str(md_path), "json": str(json_path)}

EngineQualificationReport dataclass

Result of an engine equivalence check (for fast-mesh: :meth:RasEngineQualification.validate_mesh).

tables has one row per area and mesh table (schema engine_mesh_qualification). equivalent is True only when every table is byte-identical, every engine check passed and the source project was not modified. Call :meth:approve to save an approval.

Source code in ras_commander/RasEngineQualification.py
Python
@dataclass
class EngineQualificationReport:
    """Result of an engine equivalence check (for fast-mesh: :meth:`RasEngineQualification.validate_mesh`).

    ``tables`` has one row per area and mesh table (schema
    ``engine_mesh_qualification``). ``equivalent`` is True only when every
    table is byte-identical, every engine check passed and the source project
    was not modified. Call :meth:`approve` to save an approval.
    """

    engine: str
    family: str
    scope: str
    config: Dict[str, Any]
    project_folder: str
    equivalent: bool
    status: str
    project_file: Optional[str] = None
    engine_identity: Dict[str, Any] = field(default_factory=dict)
    reference: Dict[str, Any] = field(default_factory=dict)
    fingerprints: Dict[str, Dict[str, Optional[str]]] = field(default_factory=dict)
    tables: pd.DataFrame = field(default_factory=pd.DataFrame)
    checks: Dict[str, Any] = field(default_factory=dict)
    areas: List[Dict[str, Any]] = field(default_factory=list)
    source_unchanged: Optional[bool] = None
    workspace: Optional[str] = None
    report_path: Optional[str] = None
    gap_report: Optional[Dict[str, str]] = None
    created_utc: str = ""
    ras_commander_version: str = ""

    def summary(self) -> Dict[str, Any]:
        """Counts only: no paths, names or coordinates."""
        tables = self.tables
        identical = int((tables["status"] == "identical").sum()) if not tables.empty else 0
        return {
            "status": self.status,
            "equivalent": self.equivalent,
            "areas": len(self.areas),
            "real_cells": int(sum(a.get("real_cells") or 0 for a in self.areas)),
            "tables_compared": int(len(tables)),
            "tables_identical": identical,
            "tables_mismatched": int(len(tables)) - identical,
            "checks_failed": sorted(k for k, v in self.checks.items()
                                    if isinstance(v, dict) and v.get("passed") is False),
        }

    def to_dict(self) -> Dict[str, Any]:
        """JSON-serializable form (``ras-commander-engine-qualification/v1``)."""
        data = {k: v for k, v in asdict(self).items() if k != "tables"}
        data["schema"] = REPORT_SCHEMA
        data["tables"] = json.loads(self.tables.to_json(orient="records")) if not self.tables.empty else []
        data["summary"] = self.summary()
        return data

    def approve(self, user: Optional[str] = None, note: Optional[str] = None,
                engine_path: Optional[Union[str, Path]] = None) -> "EngineApprovalStatus":
        """Save an approval for this report; see :meth:`RasEngineQualification.approve`."""
        return RasEngineQualification.approve(self, user=user, note=note, engine_path=engine_path)

summary

Python
summary() -> Dict[str, Any]

Counts only: no paths, names or coordinates.

Source code in ras_commander/RasEngineQualification.py
Python
def summary(self) -> Dict[str, Any]:
    """Counts only: no paths, names or coordinates."""
    tables = self.tables
    identical = int((tables["status"] == "identical").sum()) if not tables.empty else 0
    return {
        "status": self.status,
        "equivalent": self.equivalent,
        "areas": len(self.areas),
        "real_cells": int(sum(a.get("real_cells") or 0 for a in self.areas)),
        "tables_compared": int(len(tables)),
        "tables_identical": identical,
        "tables_mismatched": int(len(tables)) - identical,
        "checks_failed": sorted(k for k, v in self.checks.items()
                                if isinstance(v, dict) and v.get("passed") is False),
    }

to_dict

Python
to_dict() -> Dict[str, Any]

JSON-serializable form (ras-commander-engine-qualification/v1).

Source code in ras_commander/RasEngineQualification.py
Python
def to_dict(self) -> Dict[str, Any]:
    """JSON-serializable form (``ras-commander-engine-qualification/v1``)."""
    data = {k: v for k, v in asdict(self).items() if k != "tables"}
    data["schema"] = REPORT_SCHEMA
    data["tables"] = json.loads(self.tables.to_json(orient="records")) if not self.tables.empty else []
    data["summary"] = self.summary()
    return data

approve

Python
approve(user: Optional[str] = None, note: Optional[str] = None, engine_path: Optional[Union[str, Path]] = None) -> 'EngineApprovalStatus'

Save an approval for this report; see :meth:RasEngineQualification.approve.

Source code in ras_commander/RasEngineQualification.py
Python
def approve(self, user: Optional[str] = None, note: Optional[str] = None,
            engine_path: Optional[Union[str, Path]] = None) -> "EngineApprovalStatus":
    """Save an approval for this report; see :meth:`RasEngineQualification.approve`."""
    return RasEngineQualification.approve(self, user=user, note=note, engine_path=engine_path)

EngineSpec dataclass

Registration of an engine for qualification and default resolution.

Attributes:

Name Type Description
name str

Engine identifier (for example "fast-mesh").

family str

Operation family: mesh, hdf, map, dss, preprocess or unsteady.

platform_default bool

True when the engine already runs by default (approvals are then not needed and not consulted).

status str

"experimental", "default", "optional" or "planned".

description str

One-line description.

validator Optional[Callable[..., 'EngineQualificationReport']]

Equivalence check validator(project, **kwargs) -> EngineQualificationReport. None marks an extension point without a check yet.

fingerprint Optional[Callable[[Path, str], Dict[str, Dict[str, Optional[str]]]]]

fingerprint(project_folder, scope) -> {name: {"path", "sha256"}} of the inputs an approval is bound to.

version_probe Optional[Callable[[Optional[Union[str, Path]]], Dict[str, Any]]]

version_probe(engine_path) -> {"version", "git_commit", "executable_sha256"}; raises when the engine is unavailable.

Source code in ras_commander/RasEngineQualification.py
Python
@dataclass
class EngineSpec:
    """Registration of an engine for qualification and default resolution.

    Attributes:
        name: Engine identifier (for example ``"fast-mesh"``).
        family: Operation family: ``mesh``, ``hdf``, ``map``, ``dss``,
            ``preprocess`` or ``unsteady``.
        platform_default: True when the engine already runs by default
            (approvals are then not needed and not consulted).
        status: ``"experimental"``, ``"default"``, ``"optional"`` or ``"planned"``.
        description: One-line description.
        validator: Equivalence check ``validator(project, **kwargs) -> EngineQualificationReport``.
            ``None`` marks an extension point without a check yet.
        fingerprint: ``fingerprint(project_folder, scope) -> {name: {"path", "sha256"}}``
            of the inputs an approval is bound to.
        version_probe: ``version_probe(engine_path) -> {"version", "git_commit", "executable_sha256"}``;
            raises when the engine is unavailable.
    """

    name: str
    family: str
    platform_default: bool = False
    status: str = "experimental"
    description: str = ""
    validator: Optional[Callable[..., "EngineQualificationReport"]] = None
    fingerprint: Optional[Callable[[Path, str], Dict[str, Dict[str, Optional[str]]]]] = None
    version_probe: Optional[Callable[[Optional[Union[str, Path]]], Dict[str, Any]]] = None

EngineApprovalStatus dataclass

Validity of one saved approval (see :meth:RasEngineQualification.status).

Source code in ras_commander/RasEngineQualification.py
Python
@dataclass
class EngineApprovalStatus:
    """Validity of one saved approval (see :meth:`RasEngineQualification.status`)."""

    engine: str
    scope: str
    config: Dict[str, Any]
    valid: bool
    reasons: List[str]
    record: Optional[Dict[str, Any]] = None