Skip to content

Stored Maps

Stored maps turn existing computed results into raster or polygon products. They do not run a hydraulic simulation. Supply a valid result HDF, the intended terrain association, map types and a profile or output timestep supported by the method.

Entry point Use Return
RasMap.store_all_maps Canonical orchestration across its documented modes Report dictionary
RasProcess.store_maps Selected products for one plan/profile Dictionary of map types to path lists
RasProcess.store_maps_at_timesteps Selected output times Nested dictionaries of product paths
RasProcess.store_maps_at_steady_profiles Selected steady profiles in one helper launch DataFrame
estimate_store_map_resources, profile_store_maps Resource estimate or an actual profiled export Typed estimate/profile result
Result registration and calculated layers RASMapper result tree and expressions XML / .rasscript edits; does not itself produce a stored raster
Raster batch/composite methods Existing maps or selected plans Export DataFrame or raster path

The headless RasProcess.store_maps() implementation uses the native RasStoreMapHelper.exe; the namespace also wraps other RasProcess operations. Native export needs the matching installed HEC-RAS components, with Windows or an explicitly configured supported Wine environment. RasMap also retains GUI postprocessing: inspect the chosen mode's requirements before unattended use. The compatibility RasProcess.store_all_maps() delegates to RasMap.store_all_maps(mode="all_plans").

Use returned product evidence and expected output files to check completion. A layer visible in the RASMapper tree is not proof that its raster was generated. For depth-comparison products see Benefits analysis; for terrain surface export see Terrain, which is distinct from result mapping.

601 — headless stored maps contains retained execution outputs. 125 — arrival and duration maps currently has no retained code-cell outputs; use it as a workflow example, not execution evidence.

A separate retained Ether Hollow control qualifies native HEC-RAS 7.0.1 arrival, duration and percent rasters with horizontal rendering, one explicitly selected terrain, a 0.5-foot wetness threshold and five regular output times. Across 21,292 wet pixels, percent matches the fraction of wet stored samples; arrival matches the first wet output time, and duration matches the observed single-period time support. All product grids match the registered terrain. The opt-in tests/test_stored_maps_native_contract.py checks these contracts against hash-pinned external fixtures. This evidence does not execute notebook 125 or qualify sloping rendering, irregular intervals, initially wet conditions, multiple wet periods, threshold equality or general recession semantics.

Native inundation boundary

Pass inundation_boundary=True to request RAS Mapper's Inundation Boundary stored layer. Disable the three default raster products for a boundary-only export:

Python
from ras_commander import RasProcess

products = RasProcess.store_maps(
    "02", profile="Max", render_mode="sloping",
    wse=False, depth=False, velocity=False,
    inundation_boundary=True,
    output_path="stored-boundary",
)
boundaries = products.get("inundation_boundary", [])  # list[Path] of .shp files

This uses native RASResultsMap storage through the packaged helper: MapType="depth", OutputMode="Stored Polygon Specified Depth", and ContourPolygonValue="0". In HEC-RAS 7.0.1, this combination is recognized by the native IsIndundationBoundaryMap property. There is no separate MapTypes.InundationBoundary member in that runtime. It does not polygonize an exported depth raster in Python.

HEC's RAS Mapper User's Manual 6.6, Managing Results Maps — Inundation Boundary describes this as a stored polygon at the zero-depth contour for the selected water-surface profile and associated terrain. Depth contours at other values are a separate Depth map configuration; this flag selects the zero contour.

The result dictionary contains primary SHP paths. Native names can include the contour value, for example Inundation Boundary (Max Value_0).shp. output_path moves the freshly generated companion files, including SHX, DBF, and PRJ when present. The call restores the original .rasmap on success or failure. Existing raster defaults and return types are unchanged.

The collector requires a fresh SHP/SHX/DBF bundle with nonempty polygon records. Missing, empty, truncated, incomplete, or unchanged products are omitted with a warning; any files written remain available for inspection. A helper failure raises RuntimeError. These structure checks do not assess polygon topology or hydraulic accuracy. Inspect the returned paths before using the product.

Use profile="Max", "Min", or an available output timestamp. Boundary generation uses the ordered serial helper path; explicit parallel workers are unsupported. RasMap.store_all_maps(mode="selected", map_types=["inundation_boundary"]) routes to the same implementation. The steady-profile entry point retains its existing final-selected-profile boundary behavior and DataFrame return. Other depth contours, contour bands, and the Mapper wet/dry editing layers are outside this flag's scope.

The opt-in tests/test_native_inundation_boundary.py copies a computed public project, exports maximum and middle-timestep boundaries, checks readable, valid, nonempty polygons and CRS, and verifies source-file hashes and .rasmap restoration. Set RAS_NATIVE_BOUNDARY_PROJECT to the source .prj, RAS_NATIVE_BOUNDARY_PLAN to its plan number (default 02), and RAS_NATIVE_BOUNDARY_VERSION to an installed runtime (default 7.0.1). Use a short scratch directory with pytest's --basetemp option. Runtime qualification for this change covers sloping rendering with Windows HEC-RAS 7.0.1 on the public Davis Storm System. Both profiles produced valid, nonempty multipart polygon features in EPSG:2871. A horizontal-rendering attempt on that copy reported a native Store-Map fatal error; its cause is unresolved. This evidence does not qualify horizontal boundary exports, other runtime versions, or Linux/Wine boundary exports.

Orchestration, result registration and calculated layers

Class for parsing and accessing information from HEC-RAS mapper configuration files (.rasmap).

This class provides methods to extract paths to terrain, soil, land cover data, and various project settings from the .rasmap file associated with a HEC-RAS project. It also includes functionality to automate the post-processing of stored maps.

postprocess_stored_maps staticmethod

Python
postprocess_stored_maps(plan_number: Union[str, List[str]], specify_terrain: Optional[str] = None, layers: Union[str, List[str]] = None, ras_object: Optional[Any] = None, auto_click_compute: bool = True) -> bool

Automates the generation of stored floodplain map outputs (e.g., .tif files).

This function modifies the plan and .rasmap files to generate floodplain maps for one or more plans, then restores the original files.

Parameters:

Name Type Description Default
plan_number Union[str, List[str]]

Plan number(s) to generate maps for.

required
specify_terrain Optional[str]

The name of a specific terrain to use.

None
layers Union[str, List[str]]

A list of map layers to generate. Defaults to ['WSEL', 'Velocity', 'Depth'].

None
ras_object Optional[Any]

The RAS project object.

None
auto_click_compute bool

If True, uses GUI automation to automatically click "Run > Unsteady Flow Analysis" and "Compute" button. If False, just opens HEC-RAS and waits for manual execution. Defaults to True.

True

Returns:

Type Description
bool

True if the process completed successfully, False otherwise.

Notes
  • auto_click_compute=True: Automated GUI workflow (clicks menu and Compute button)
  • auto_click_compute=False: Manual workflow (user must click Compute)
  • Automatically calls ensure_rasmap_compatible() to upgrade 5.0.7→6.x .rasmap files
Source code in ras_commander/RasMap.py
Python
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
@staticmethod
@log_call
def postprocess_stored_maps(
    plan_number: Union[str, List[str]],
    specify_terrain: Optional[str] = None,
    layers: Union[str, List[str]] = None,
    ras_object: Optional[Any] = None,
    auto_click_compute: bool = True,
) -> bool:
    """
    Automates the generation of stored floodplain map outputs (e.g., .tif files).

    This function modifies the plan and .rasmap files to generate floodplain maps
    for one or more plans, then restores the original files.

    Args:
        plan_number (Union[str, List[str]]): Plan number(s) to generate maps for.
        specify_terrain (Optional[str]): The name of a specific terrain to use.
        layers (Union[str, List[str]], optional): A list of map layers to generate.
            Defaults to ['WSEL', 'Velocity', 'Depth'].
        ras_object (Optional[Any]): The RAS project object.
        auto_click_compute (bool, optional): If True, uses GUI automation to automatically
            click "Run > Unsteady Flow Analysis" and "Compute" button. If False, just
            opens HEC-RAS and waits for manual execution. Defaults to True.

    Returns:
        bool: True if the process completed successfully, False otherwise.

    Notes:
        - auto_click_compute=True: Automated GUI workflow (clicks menu and Compute button)
        - auto_click_compute=False: Manual workflow (user must click Compute)
        - Automatically calls ensure_rasmap_compatible() to upgrade 5.0.7→6.x .rasmap files
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # ── Version validation: only 6.x is verified for correct output ──
    # HEC-RAS 5.0.7 floodplain mapping is UNTESTED and may produce
    # incorrect results if the project was ever opened in a newer version.
    # Verified 2026-03-23: GUI floodplain mapping (Run RASMapper= -1)
    # produces pixel-perfect output for HEC-RAS 6.3.1 and 6.6.
    ras_version = getattr(ras_obj, "ras_version", None) or ""
    if ras_version.startswith("5.") or ras_version.startswith("4."):
        raise RuntimeError(
            f"postprocess_stored_maps() is not supported for HEC-RAS {ras_version}.\n\n"
            "REASON: HEC-RAS 5.x floodplain mapping output has not been validated\n"
            "against manual RASMapper benchmarks, and 5.x projects opened in newer\n"
            "versions become corrupted. Only HEC-RAS 6.x (6.3.1, 6.6+) is verified\n"
            "to produce pixel-perfect raster output via the GUI floodplain mapping path.\n\n"
            "If you need 5.x support, please open a GitHub issue with test data."
        )

    # Ensure .rasmap compatibility (upgrade 5.0.7 to 6.x if needed)
    logger.debug("Checking .rasmap compatibility")
    compat_result = RasMap.ensure_rasmap_compatible(
        ras_object=ras_obj, auto_upgrade=True
    )

    if compat_result["status"] == "manual_needed":
        logger.error(
            f".rasmap upgrade required but failed: {compat_result['message']}\n\n"
            "Manual steps required:\n"
            "1. Open project in HEC-RAS\n"
            "2. Click 'GIS Tools' > 'RAS Mapper'\n"
            "3. Wait for RASMapper to open (this upgrades .rasmap)\n"
            "4. Close RASMapper and HEC-RAS\n"
            "5. Re-run this function"
        )
        return False
    elif compat_result["status"] == "upgraded":
        logger.debug(".rasmap successfully upgraded: %s", compat_result["message"])
    else:  # 'ready'
        logger.debug(
            ".rasmap compatibility check passed: %s", compat_result["message"]
        )

    if layers is None:
        layers = ["WSEL", "Velocity", "Depth"]
    elif isinstance(layers, str):
        layers = [layers]

    # Convert plan_number to list if it's a string
    plan_number_list = (
        [plan_number] if isinstance(plan_number, str) else plan_number
    )

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    rasmap_backup_path = rasmap_path.with_suffix(
        f"{rasmap_path.suffix}.storedmap.bak"
    )

    # Store plan paths and their backups
    plan_paths = []
    plan_backup_paths = []
    plan_results_folders = {}  # Map plan_num to results folder name

    for plan_num in plan_number_list:
        plan_path = Path(RasPlan.get_plan_path(plan_num, ras_obj))
        plan_backup_path = plan_path.with_suffix(
            f"{plan_path.suffix}.storedmap.bak"
        )
        plan_paths.append(plan_path)
        plan_backup_paths.append(plan_backup_path)

        # Get the Short Identifier for this plan to determine results folder
        plan_df = ras_obj.plan_df
        plan_info = plan_df[plan_df["plan_number"] == plan_num]
        if not plan_info.empty:
            short_id = plan_info.iloc[0]["Short Identifier"]
            if pd.notna(short_id) and short_id:
                plan_results_folders[plan_num] = short_id
            else:
                # Fallback: use plan number if no Short Identifier
                plan_results_folders[plan_num] = f"Plan_{plan_num}"
                logger.warning(
                    f"Plan {plan_num} has no Short Identifier, using 'Plan_{plan_num}' as folder name"
                )
        else:
            plan_results_folders[plan_num] = f"Plan_{plan_num}"
            logger.warning(
                f"Could not find plan {plan_num} in plan_df, using 'Plan_{plan_num}' as folder name"
            )

    def _create_map_element(name, map_type, results_folder, profile_name="Max"):
        # Generate filename: "WSE (Max).vrt", "Depth (Max).vrt", etc.
        filename = f"{name} ({profile_name}).vrt"
        relative_path = f".\\{results_folder}\\{filename}"

        map_params = {
            "MapType": map_type,
            "OutputMode": "Stored Current Terrain",
            "StoredFilename": relative_path,  # Required for stored maps
            "ProfileIndex": "2147483647",
            "ProfileName": profile_name,
        }

        # Create Layer element with Filename attribute
        layer_elem = ET.Element(
            "Layer",
            Name=name,
            Type="RASResultsMap",
            Checked="True",
            Filename=relative_path,  # Required for stored maps
        )

        map_params_elem = ET.SubElement(layer_elem, "MapParameters")
        for k, v in map_params.items():
            map_params_elem.set(k, str(v))
        return layer_elem

    try:
        # --- 1. Backup and Modify Plan Files ---
        for plan_num, plan_path, plan_backup_path in zip(
            plan_number_list, plan_paths, plan_backup_paths
        ):
            logger.debug(
                "Backing up plan file %s to %s", plan_path, plan_backup_path
            )
            shutil.copy2(plan_path, plan_backup_path)

            logger.debug(
                "Updating plan run flags for floodplain mapping for plan %s",
                plan_num,
            )
            RasPlan.update_run_flags(
                plan_num,
                geometry_preprocessor=True,
                unsteady_flow_simulation=False,
                post_processor=False,
                floodplain_mapping=True,
                ras_object=ras_obj,
            )

        # --- 2. Backup and Modify RASMAP File ---
        logger.debug(
            "Backing up rasmap file %s to %s", rasmap_path, rasmap_backup_path
        )
        shutil.copy2(rasmap_path, rasmap_backup_path)

        tree = ET.parse(rasmap_path)
        root = tree.getroot()

        results_section = root.find("Results")
        if results_section is None:
            raise ValueError(f"No <Results> section found in {rasmap_path}")

        # Process each plan's results layer
        for plan_num in plan_number_list:
            plan_hdf_part = f".p{plan_num}.hdf"
            results_layer = None
            for layer in results_section.findall("Layer[@Type='RASResults']"):
                filename = layer.get("Filename")
                if filename and plan_hdf_part.lower() in filename.lower():
                    results_layer = layer
                    break

            if results_layer is None:
                # Create a new RASResults layer for this plan
                plan_hdf_filename = f".\\{ras_obj.project_name}.p{plan_num}.hdf"
                plan_info = ras_obj.plan_df[
                    ras_obj.plan_df["plan_number"] == plan_num
                ]
                if not plan_info.empty:
                    layer_name = plan_info.iloc[0].get(
                        "Plan Title", f"Plan {plan_num}"
                    )
                    if pd.isna(layer_name) or not layer_name:
                        layer_name = f"Plan {plan_num}"
                else:
                    layer_name = f"Plan {plan_num}"

                results_layer = ET.SubElement(
                    results_section,
                    "Layer",
                    Name=layer_name,
                    Type="RASResults",
                    Checked="True",
                    Expanded="True",
                    Filename=plan_hdf_filename,
                )
                logger.debug(
                    "Created new RASResults layer '%s' for plan %s (none existed in .rasmap)",
                    layer_name,
                    plan_num,
                )

            # Map user-provided layer names to HEC-RAS variable names and map types
            # Note: "WSE" is the correct HEC-RAS convention (not "WSEL")
            map_definitions = {
                "WSE": "elevation",
                "WSEL": "elevation",  # Accept both for backward compatibility, but use "WSE" in output
                "Velocity": "velocity",
                "Depth": "depth",
            }

            # Get the results folder for this plan
            results_folder = plan_results_folders.get(plan_num, f"Plan_{plan_num}")

            for layer_name in layers:
                if layer_name in map_definitions:
                    map_type = map_definitions[layer_name]

                    # Convert WSEL to WSE for output (HEC-RAS convention)
                    output_name = "WSE" if layer_name == "WSEL" else layer_name

                    map_elem = _create_map_element(
                        output_name, map_type, results_folder
                    )
                    results_layer.append(map_elem)
                    logger.debug(
                        "Added '%s' stored map to results layer for plan %s",
                        output_name,
                        plan_num,
                    )

        if specify_terrain:
            terrains_elem = root.find("Terrains")
            if terrains_elem is not None:
                for layer in list(terrains_elem):
                    if layer.get("Name") != specify_terrain:
                        terrains_elem.remove(layer)
                logger.debug(
                    "Filtered terrains, keeping only '%s'", specify_terrain
                )

        _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=True)

        # --- 3. Execute HEC-RAS ---
        if auto_click_compute:
            # Use GUI automation to automatically click menu and Compute button
            logger.info("Using GUI automation to run floodplain mapping...")

            # Note: For multiple plans, we run the first plan's automation
            # The user can manually run additional plans if needed
            first_plan = plan_number_list[0]

            from .RasGuiAutomation import RasGuiAutomation

            success = RasGuiAutomation.open_and_compute(
                plan_number=first_plan,
                ras_object=ras_obj,
                auto_click_compute=True,
                wait_for_user=True,
            )

            if len(plan_number_list) > 1:
                logger.info(
                    f"Note: GUI automation ran plan {first_plan}. "
                    f"Please manually run remaining plans: {', '.join(plan_number_list[1:])}"
                )

            if not success:
                logger.error("Floodplain mapping computation failed.")
                return False

        else:
            # Manual mode: Just open HEC-RAS and wait for user to execute
            logger.info("Opening HEC-RAS...")
            ras_exe = ras_obj.ras_exe_path
            prj_path = f'"{str(ras_obj.prj_file)}"'
            command = f"{ras_exe} {prj_path}"

            try:
                import sys
                import subprocess

                if sys.platform == "win32":
                    hecras_process = subprocess.Popen(command)
                else:
                    hecras_process = subprocess.Popen([ras_exe, prj_path])

                logger.debug(
                    "HEC-RAS opened with Process ID: %s", hecras_process.pid
                )
                logger.info(
                    f"Please run plan(s) {', '.join(plan_number_list)} using the 'Compute Multiple' window in HEC-RAS to generate floodplain mapping results."
                )

                # Wait for HEC-RAS to close
                logger.debug("Waiting for HEC-RAS to close")
                hecras_process.wait()
                logger.debug("HEC-RAS has closed")

                success = True

            except Exception as e:
                logger.error(f"Failed to launch HEC-RAS: {e}")
                success = False

            if not success:
                logger.error("Floodplain mapping computation failed.")
                return False

        logger.info("Floodplain mapping computation successful.")
        return True

    except Exception as e:
        logger.error(f"Error in postprocess_stored_maps: {e}")
        return False

    finally:
        # --- 4. Restore Files ---
        for plan_path, plan_backup_path in zip(plan_paths, plan_backup_paths):
            if plan_backup_path.exists():
                logger.debug(
                    "Restoring original plan file from %s", plan_backup_path
                )
                shutil.move(plan_backup_path, plan_path)
        if rasmap_backup_path.exists():
            logger.debug(
                "Restoring original rasmap file from %s", rasmap_backup_path
            )
            shutil.move(rasmap_backup_path, rasmap_path)

store_all_maps staticmethod

Python
store_all_maps(plan_number: Optional[Union[str, int, float, Sequence[Union[str, int, float]]]] = None, render_mode: str = None, ras_object: Optional[Any] = None, timeout: int = 600, *, mode: str = 'auto', output_folder: Optional[str] = None, output_path: Optional[Union[str, Path]] = None, profile: str = 'Max', profiles: Optional[Union[str, int, Sequence[Union[str, int]]]] = None, timesteps: Optional[Union[int, str, datetime, Sequence[Union[int, str, datetime]]]] = None, max_timesteps: Optional[int] = None, map_types: Optional[Union[str, Sequence[str]]] = None, wse: Optional[bool] = None, depth: Optional[bool] = None, velocity: Optional[bool] = None, froude: Optional[bool] = None, shear_stress: Optional[bool] = None, depth_x_velocity: Optional[bool] = None, depth_x_velocity_sq: Optional[bool] = None, inundation_boundary: Optional[bool] = None, arrival_time: Optional[bool] = None, duration: Optional[bool] = None, percent_inundated: Optional[bool] = None, arrival_depth: float = 0.0, clear_existing: bool = True, fix_georef: bool = True, ras_version: Optional[str] = None, terrain_name: Optional[str] = None, benefit_area: Optional[BenefitAreaConfig] = None, performance: Optional[StoreMapPerformanceOptions] = None, raise_on_error: bool = False) -> Dict[str, Any]

Generate RASMapper stored maps through one canonical API.

mode selects the operation without requiring a second store_all_maps implementation:

  • "configured" runs ras-commander's packaged RAS Mapper helper for every stored map already configured in the .rasmap. This is the compatibility behavior of historic RasMap.store_all_maps(plan_number) calls.
  • "native" is a deprecated alias for "configured". It does not invoke RasProcess.exe: that executable does not honor the required stored-map interpolation/render-mode behavior.
  • "selected" configures and generates selected map products for one or more plans. performance=StoreMapPerformanceOptions(...) enables memory-admitted map-level parallelism.
  • "timesteps" generates selected products for requested output timesteps.
  • "steady_profiles" configures every selected steady profile in one XML transaction and invokes aggregate StoreAllMaps once per plan.
  • "all_plans" applies the selected-map configuration to every project plan with an HDF result.
  • "auto" preserves a plain historic call as "configured", uses "all_plans" when plan_number is omitted, and otherwise selects "selected" or "timesteps" when advanced options are supplied.

The result always contains success, resolved mode, plans, and render_mode. Configured plan results add files_by_type; timestep results add a nested timesteps mapping. File paths are strings so the summary is directly JSON serializable.

Parameters:

Name Type Description Default
plan_number Optional[Union[str, int, float, Sequence[Union[str, int, float]]]]

One flexible plan number (for example 1 or "01") or a plan sequence for configured/selected/ timesteps. Omit it for all_plans.

None
render_mode str

Optional water-surface rendering override.

None
ras_object RasPrj

Initialized project object; defaults to the active project.

None
timeout int

Per-helper timeout in seconds.

600
mode str

auto, configured, selected, timesteps, steady_profiles, or all_plans. native remains a deprecated compatibility alias for configured.

'auto'
output_folder Optional[str]

Relative .rasmap StoredFilename folder name for configured non-timestep modes. It is not an output destination.

None
output_path Optional[Union[str, Path]]

Destination directory to which generated products are moved. Multi-plan modes create plan_XX children.

None
profile str

Max, Min, or a timestamp for configured non-timestep modes.

'Max'
profiles Optional[Union[str, int, Sequence[Union[str, int]]]]

Steady-profile selectors for steady_profiles mode. None selects all profiles; exact names and zero-based indexes may be mixed in a sequence.

None
timesteps Optional[Union[int, str, datetime, Sequence[Union[int, str, datetime]]]]

Timestep selectors for timesteps mode.

None
max_timesteps Optional[int]

Optional cap applied after timestep selection.

None
map_types Optional[Union[str, Sequence[str]]]

One product name or a sequence of names. Exactly the listed products are generated. Do not combine with individual raster/product flags, except inundation_boundary (see below). Defaults, when neither map_types nor any flag is given, are WSE/Depth/Velocity for selected/all-plans, Depth only for timesteps, and Depth plus one inundation boundary for steady_profiles.

None
wse Optional[bool]

Individual Water Surface Elevation product flag. Once any individual product flag is given, only flags set to True are generated.

None
depth Optional[bool]

Individual Depth product flag.

None
velocity Optional[bool]

Individual Velocity product flag.

None
froude Optional[bool]

Individual Froude number product flag.

None
shear_stress Optional[bool]

Individual Shear Stress product flag.

None
depth_x_velocity Optional[bool]

Individual depth-times-velocity product flag.

None
depth_x_velocity_sq Optional[bool]

Individual depth-times-velocity-squared product flag.

None
arrival_time Optional[bool]

Individual Arrival Time product flag.

None
duration Optional[bool]

Individual Duration product flag.

None
percent_inundated Optional[bool]

Individual Percent Inundated product flag.

None
inundation_boundary Optional[bool]

Individual inundation boundary polygon flag. May also be passed together with map_types to add (True) or explicitly omit (False) the boundary polygon; False conflicts with a map_types entry of "inundation_boundary". For steady_profiles, map_types=["depth"] therefore yields Depth rasters only.

None
arrival_depth float

Threshold for whole-simulation configured products.

0.0
clear_existing bool

Clear existing stored maps before adding new ones.

True
fix_georef bool

Apply georeferencing fixes to generated rasters.

True
ras_version Optional[str]

Optional installed mapping-runtime version.

None
terrain_name Optional[str]

Registered terrain selection for non-timestep modes.

None
benefit_area Optional[BenefitAreaConfig]

Optional single-plan benefit-area configuration.

None
performance Optional[StoreMapPerformanceOptions]

Typed map-helper execution and memory policy.

None
raise_on_error bool

Re-raise a per-plan runtime failure instead of retaining it in the summary. For steady_profiles, a plan whose StoreAllMaps run omitted some requested products is reported with success=False, error, the preserved files, per-product stored_maps (each with status), and missing; with raise_on_error=True the :class:~ras_commander.RasProcess.StoredMapProductsIncompleteError is re-raised after those products are preserved.

False

Raises:

Type Description
ValueError

If the selected mode cannot honor an option, no plans are available, or no map product is selected.

Source code in ras_commander/RasMap.py
Python
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
@staticmethod
@log_call
def store_all_maps(
    plan_number: Optional[
        Union[
            str,
            int,
            float,
            Sequence[Union[str, int, float]],
        ]
    ] = None,
    render_mode: str = None,
    ras_object: Optional[Any] = None,
    timeout: int = 600,
    *,
    mode: str = "auto",
    output_folder: Optional[str] = None,
    output_path: Optional[Union[str, Path]] = None,
    profile: str = "Max",
    profiles: Optional[
        Union[str, int, Sequence[Union[str, int]]]
    ] = None,
    timesteps: Optional[
        Union[int, str, datetime, Sequence[Union[int, str, datetime]]]
    ] = None,
    max_timesteps: Optional[int] = None,
    map_types: Optional[Union[str, Sequence[str]]] = None,
    wse: Optional[bool] = None,
    depth: Optional[bool] = None,
    velocity: Optional[bool] = None,
    froude: Optional[bool] = None,
    shear_stress: Optional[bool] = None,
    depth_x_velocity: Optional[bool] = None,
    depth_x_velocity_sq: Optional[bool] = None,
    inundation_boundary: Optional[bool] = None,
    arrival_time: Optional[bool] = None,
    duration: Optional[bool] = None,
    percent_inundated: Optional[bool] = None,
    arrival_depth: float = 0.0,
    clear_existing: bool = True,
    fix_georef: bool = True,
    ras_version: Optional[str] = None,
    terrain_name: Optional[str] = None,
    benefit_area: Optional[BenefitAreaConfig] = None,
    performance: Optional[StoreMapPerformanceOptions] = None,
    raise_on_error: bool = False,
) -> Dict[str, Any]:
    """Generate RASMapper stored maps through one canonical API.

    ``mode`` selects the operation without requiring a second
    ``store_all_maps`` implementation:

    - ``"configured"`` runs ras-commander's packaged RAS Mapper helper
      for every stored map already configured in the ``.rasmap``. This is
      the compatibility behavior of historic
      ``RasMap.store_all_maps(plan_number)`` calls.
    - ``"native"`` is a deprecated alias for ``"configured"``. It does
      not invoke ``RasProcess.exe``: that executable does not honor the
      required stored-map interpolation/render-mode behavior.
    - ``"selected"`` configures and generates selected map products for
      one or more plans. ``performance=StoreMapPerformanceOptions(...)``
      enables memory-admitted map-level parallelism.
    - ``"timesteps"`` generates selected products for requested output
      timesteps.
    - ``"steady_profiles"`` configures every selected steady profile in
      one XML transaction and invokes aggregate ``StoreAllMaps`` once per
      plan.
    - ``"all_plans"`` applies the selected-map configuration to every
      project plan with an HDF result.
    - ``"auto"`` preserves a plain historic call as ``"configured"``,
      uses ``"all_plans"`` when ``plan_number`` is omitted, and otherwise
      selects ``"selected"`` or ``"timesteps"`` when advanced options are
      supplied.

    The result always contains ``success``, resolved ``mode``, ``plans``,
    and ``render_mode``. Configured plan results add ``files_by_type``;
    timestep results add a nested ``timesteps`` mapping. File paths are
    strings so the summary is directly JSON serializable.

    Args:
        plan_number: One flexible plan number (for example ``1`` or
            ``"01"``) or a plan sequence for ``configured``/``selected``/
            ``timesteps``. Omit it for ``all_plans``.
        render_mode: Optional water-surface rendering override.
        ras_object (RasPrj, optional): Initialized project object; defaults to the active project.
        timeout: Per-helper timeout in seconds.
        mode: ``auto``, ``configured``, ``selected``, ``timesteps``,
            ``steady_profiles``, or ``all_plans``. ``native`` remains a
            deprecated compatibility alias for ``configured``.
        output_folder: Relative ``.rasmap`` StoredFilename folder name for
            configured non-timestep modes. It is not an output destination.
        output_path: Destination directory to which generated products are
            moved. Multi-plan modes create ``plan_XX`` children.
        profile: ``Max``, ``Min``, or a timestamp for configured
            non-timestep modes.
        profiles: Steady-profile selectors for ``steady_profiles`` mode.
            ``None`` selects all profiles; exact names and zero-based
            indexes may be mixed in a sequence.
        timesteps: Timestep selectors for ``timesteps`` mode.
        max_timesteps: Optional cap applied after timestep selection.
        map_types: One product name or a sequence of names. Exactly the
            listed products are generated. Do not combine with individual
            raster/product flags, except ``inundation_boundary`` (see
            below). Defaults, when neither ``map_types`` nor any flag is
            given, are WSE/Depth/Velocity for selected/all-plans, Depth
            only for timesteps, and Depth plus one inundation boundary for
            steady_profiles.
        wse: Individual Water Surface Elevation product flag. Once any
            individual product flag is given, only flags set to True are generated.
        depth: Individual Depth product flag.
        velocity: Individual Velocity product flag.
        froude: Individual Froude number product flag.
        shear_stress: Individual Shear Stress product flag.
        depth_x_velocity: Individual depth-times-velocity product flag.
        depth_x_velocity_sq: Individual depth-times-velocity-squared product flag.
        arrival_time: Individual Arrival Time product flag.
        duration: Individual Duration product flag.
        percent_inundated: Individual Percent Inundated product flag.
        inundation_boundary: Individual inundation boundary polygon flag.
            May also be passed together with
            ``map_types`` to add (True) or explicitly omit (False) the
            boundary polygon; False conflicts with a ``map_types`` entry of
            ``"inundation_boundary"``. For steady_profiles,
            ``map_types=["depth"]`` therefore yields Depth rasters only.
        arrival_depth: Threshold for whole-simulation configured products.
        clear_existing: Clear existing stored maps before adding new ones.
        fix_georef: Apply georeferencing fixes to generated rasters.
        ras_version: Optional installed mapping-runtime version.
        terrain_name: Registered terrain selection for non-timestep modes.
        benefit_area: Optional single-plan benefit-area configuration.
        performance: Typed map-helper execution and memory policy.
        raise_on_error: Re-raise a per-plan runtime failure instead of
            retaining it in the summary. For steady_profiles, a plan whose
            StoreAllMaps run omitted some requested products is reported
            with ``success=False``, ``error``, the preserved ``files``,
            per-product ``stored_maps`` (each with ``status``), and
            ``missing``; with ``raise_on_error=True`` the
            :class:`~ras_commander.RasProcess.StoredMapProductsIncompleteError`
            is re-raised after those products are preserved.

    Raises:
        ValueError: If the selected mode cannot honor an option, no plans
            are available, or no map product is selected.
    """
    from .RasProcess import RasProcess

    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    requested_mode = str(mode).strip().casefold().replace("-", "_")
    if requested_mode == "native":
        warnings.warn(
            "mode='native' is deprecated because stored maps are generated "
            "by ras-commander's packaged RAS Mapper helper, not "
            "RasProcess.exe. Use mode='configured'.",
            DeprecationWarning,
            stacklevel=2,
        )

    mode_aliases = {
        "legacy": "configured",
        "native": "configured",
        "native_all": "configured",
        "plan": "selected",
        "project": "all_plans",
        "all": "all_plans",
    }
    resolved_mode = mode_aliases.get(requested_mode, requested_mode)
    valid_modes = {
        "auto",
        "configured",
        "selected",
        "timesteps",
        "steady_profiles",
        "all_plans",
    }
    if resolved_mode not in valid_modes:
        raise ValueError(
            "mode must be auto, configured, selected, timesteps, "
            "steady_profiles, or all_plans"
        )

    requested_flags = {
        "wse": wse,
        "depth": depth,
        "velocity": velocity,
        "froude": froude,
        "shear_stress": shear_stress,
        "depth_x_velocity": depth_x_velocity,
        "depth_x_velocity_sq": depth_x_velocity_sq,
        "inundation_boundary": inundation_boundary,
        "arrival_time": arrival_time,
        "duration": duration,
        "percent_inundated": percent_inundated,
    }
    advanced_requested = any(
        (
            output_folder is not None,
            output_path is not None,
            profile != "Max",
            profiles is not None,
            timesteps is not None,
            max_timesteps is not None,
            map_types is not None,
            any(value is not None for value in requested_flags.values()),
            arrival_depth != 0.0,
            clear_existing is not True,
            fix_georef is not True,
            ras_version is not None,
            terrain_name is not None,
            benefit_area is not None,
            performance is not None,
            raise_on_error is not False,
        )
    )
    if resolved_mode == "auto":
        if profiles is not None:
            resolved_mode = "steady_profiles"
        elif timesteps is not None or max_timesteps is not None:
            resolved_mode = "timesteps"
        elif plan_number is None:
            resolved_mode = "all_plans"
        elif advanced_requested:
            resolved_mode = "selected"
        else:
            resolved_mode = "configured"

    if resolved_mode == "configured":
        if plan_number is None:
            raise ValueError("plan_number is required for mode='configured'")
        if not isinstance(plan_number, (str, int, float)) and not list(plan_number):
            raise ValueError("mode='configured' requires at least one plan")
        if advanced_requested:
            raise ValueError(
                "mode='configured' only accepts plan_number, render_mode, "
                "ras_object, and timeout; use mode='selected' for output, "
                "map, terrain, or performance options"
            )
        configured_plan_numbers = (
            [RasUtils.normalize_ras_number(plan_number)]
            if isinstance(plan_number, (str, int, float))
            else [RasUtils.normalize_ras_number(value) for value in plan_number]
        )
        result = RasMap._store_all_maps_configured(
            (
                configured_plan_numbers[0]
                if len(configured_plan_numbers) == 1
                else configured_plan_numbers
            ),
            render_mode=render_mode,
            ras_object=ras_obj,
            timeout=timeout,
        )
        result["mode"] = "configured"
        return result

    if resolved_mode == "all_plans" and plan_number is not None:
        raise ValueError("plan_number must be omitted for mode='all_plans'")
    if resolved_mode in {
        "selected",
        "timesteps",
        "steady_profiles",
    } and plan_number is None:
        raise ValueError(f"plan_number is required for mode='{resolved_mode}'")
    if resolved_mode != "timesteps" and timesteps is not None:
        raise ValueError("timesteps are only valid with mode='timesteps'")
    if resolved_mode != "timesteps" and max_timesteps is not None:
        raise ValueError("max_timesteps is only valid with mode='timesteps'")
    if resolved_mode != "steady_profiles" and profiles is not None:
        raise ValueError(
            "profiles are only valid with mode='steady_profiles'"
        )
    if resolved_mode == "timesteps":
        unsupported_timestep_options = []
        if output_folder is not None:
            unsupported_timestep_options.append("output_folder (use output_path)")
        if profile != "Max":
            unsupported_timestep_options.append("profile")
        if arrival_depth != 0.0:
            unsupported_timestep_options.append("arrival_depth")
        if terrain_name is not None:
            unsupported_timestep_options.append("terrain_name")
        if benefit_area is not None:
            unsupported_timestep_options.append("benefit_area")
        if unsupported_timestep_options:
            raise ValueError(
                "mode='timesteps' does not support: "
                + ", ".join(unsupported_timestep_options)
            )

    if resolved_mode == "steady_profiles":
        unsupported_steady_options = []
        if output_folder is not None:
            unsupported_steady_options.append("output_folder (use output_path)")
        if profile != "Max":
            unsupported_steady_options.append("profile (use profiles)")
        if timesteps is not None or max_timesteps is not None:
            unsupported_steady_options.append("timesteps")
        if arrival_depth != 0.0:
            unsupported_steady_options.append("arrival_depth")
        if benefit_area is not None:
            unsupported_steady_options.append("benefit_area")
        for product in ("arrival_time", "duration", "percent_inundated"):
            if requested_flags.get(product):
                unsupported_steady_options.append(product)
        if unsupported_steady_options:
            raise ValueError(
                "mode='steady_profiles' does not support: "
                + ", ".join(unsupported_steady_options)
            )

    supported_map_types = tuple(requested_flags)
    if resolved_mode == "steady_profiles":
        # Flow is a profile-dependent RASMapper product supported by the
        # steady batch engine, but it has no legacy individual boolean
        # flag on this facade. It is therefore selected through map_types.
        supported_map_types += ("flow",)
    supported_map_type_set = set(supported_map_types)
    explicit_map_selection = map_types is not None or any(
        value is not None for value in requested_flags.values()
    )
    if map_types is not None:
        # inundation_boundary is a polygon companion product, so it may be
        # combined with map_types; the raster flags may not.
        if any(
            value is not None
            for name, value in requested_flags.items()
            if name != "inundation_boundary"
        ):
            raise ValueError(
                "map_types cannot be combined with individual map flags "
                "(only inundation_boundary may be combined with map_types)"
            )
        map_type_values = (map_types,) if isinstance(map_types, str) else map_types
        normalized_types = {
            str(value).strip().casefold().replace(" ", "_")
            for value in map_type_values
        }
        unknown_types = sorted(normalized_types - supported_map_type_set)
        if unknown_types:
            raise ValueError("unsupported map_types: " + ", ".join(unknown_types))
        map_flags = {name: name in normalized_types for name in supported_map_types}
        if inundation_boundary is not None:
            if (
                "inundation_boundary" in normalized_types
                and not inundation_boundary
            ):
                raise ValueError(
                    "inundation_boundary=False conflicts with "
                    "map_types containing 'inundation_boundary'"
                )
            map_flags["inundation_boundary"] = bool(inundation_boundary)
    elif any(value is not None for value in requested_flags.values()):
        map_flags = {name: bool(value) for name, value in requested_flags.items()}
    elif benefit_area is not None:
        # BenefitArea has configuration-dependent defaults in RasProcess.
        map_flags = dict(requested_flags)
    elif resolved_mode == "steady_profiles":
        # Historic steady default: Depth plus one boundary polygon.
        map_flags = {
            name: name in {"depth", "inundation_boundary"}
            for name in supported_map_types
        }
    elif resolved_mode == "timesteps":
        map_flags = {name: name == "depth" for name in supported_map_types}
    else:
        map_flags = {
            name: name in {"wse", "depth", "velocity"}
            for name in supported_map_types
        }

    if explicit_map_selection and not any(map_flags.values()):
        raise ValueError("At least one stored-map product must be selected")

    if resolved_mode == "timesteps":
        unsupported_timestep_products = sorted(
            name
            for name in (
                "inundation_boundary",
                "arrival_time",
                "duration",
                "percent_inundated",
            )
            if map_flags.get(name)
        )
        if unsupported_timestep_products:
            raise ValueError(
                "mode='timesteps' does not support: "
                + ", ".join(unsupported_timestep_products)
            )

    if resolved_mode == "steady_profiles":
        unsupported_steady_products = sorted(
            name
            for name in ("arrival_time", "duration", "percent_inundated")
            if map_flags.get(name)
        )
        if unsupported_steady_products:
            raise ValueError(
                "mode='steady_profiles' does not support: "
                + ", ".join(unsupported_steady_products)
            )

    if resolved_mode == "all_plans":
        plan_numbers = [
            RasUtils.normalize_ras_number(row["plan_number"])
            for _, row in ras_obj.plan_df.iterrows()
            if (
                ras_obj.project_folder
                / f"{ras_obj.project_name}.p{RasUtils.normalize_ras_number(row['plan_number'])}.hdf"
            ).exists()
        ]
    else:
        raw_plan_numbers = (
            [plan_number]
            if isinstance(plan_number, (str, int, float))
            else list(plan_number)
        )
        plan_numbers = [
            RasUtils.normalize_ras_number(value) for value in raw_plan_numbers
        ]

    if not plan_numbers:
        raise ValueError("No plans with HDF results are available for stored maps")
    if benefit_area is not None and len(plan_numbers) != 1:
        raise ValueError("benefit_area requires exactly one selected plan")

    summary: Dict[str, Any] = {
        "success": True,
        "mode": resolved_mode,
        "plans": {},
        "render_mode": (
            normalize_store_map_render_mode(render_mode)
            if render_mode is not None
            else None
        ),
    }
    multiple_plans = len(plan_numbers) > 1 or resolved_mode == "all_plans"

    for plan_num in plan_numbers:
        plan_output_folder = (
            f"{output_folder}_{plan_num}"
            if output_folder is not None and multiple_plans
            else output_folder
        )
        plan_output_path = (
            Path(output_path) / f"plan_{plan_num}"
            if output_path is not None and multiple_plans
            else output_path
        )
        shared_arguments = {
            "plan_number": plan_num,
            "output_folder": plan_output_folder,
            "output_path": plan_output_path,
            "profile": profile,
            "render_mode": render_mode,
            **map_flags,
            "arrival_depth": arrival_depth,
            "clear_existing": clear_existing,
            "fix_georef": fix_georef,
            "ras_object": ras_obj,
            "ras_version": ras_version,
            "timeout": timeout,
            "performance": performance,
        }
        if terrain_name is not None:
            shared_arguments["terrain_name"] = terrain_name
        if benefit_area is not None:
            shared_arguments["benefit_area"] = benefit_area

        try:
            if resolved_mode == "timesteps":
                timestep_arguments = {
                    key: value
                    for key, value in shared_arguments.items()
                    if key
                    not in {
                        "output_folder",
                        "profile",
                        "inundation_boundary",
                        "arrival_time",
                        "duration",
                        "percent_inundated",
                        "arrival_depth",
                        "terrain_name",
                        "benefit_area",
                    }
                }
                generated_by_timestep = RasProcess.store_maps_at_timesteps(
                    timesteps=timesteps,
                    max_timesteps=max_timesteps,
                    **timestep_arguments,
                )
                timestep_summary = {
                    timestamp: {
                        map_type: [str(path) for path in paths]
                        for map_type, paths in generated.items()
                    }
                    for timestamp, generated in generated_by_timestep.items()
                }
                flat_files = [
                    path
                    for generated in timestep_summary.values()
                    for paths in generated.values()
                    for path in paths
                ]
                summary["plans"][plan_num] = {
                    "success": True,
                    "timesteps": timestep_summary,
                    "files": flat_files,
                }
            elif resolved_mode == "steady_profiles":
                steady_map_types = [
                    name
                    for name in (
                        "wse",
                        "depth",
                        "velocity",
                        "froude",
                        "shear_stress",
                        "depth_x_velocity",
                        "depth_x_velocity_sq",
                        "flow",
                    )
                    if map_flags.get(name)
                ]
                if not steady_map_types:
                    raise ValueError(
                        "At least one steady profile raster product is required"
                    )
                frame = RasProcess.store_maps_at_steady_profiles(
                    plan_number=plan_num,
                    profiles=profiles,
                    output_path=plan_output_path,
                    map_types=steady_map_types,
                    render_mode=render_mode,
                    clear_existing=clear_existing,
                    fix_georef=fix_georef,
                    ras_object=ras_obj,
                    ras_version=ras_version,
                    timeout=timeout,
                    terrain_name=terrain_name,
                    inundation_boundary=bool(
                        map_flags.get("inundation_boundary")
                    ),
                    raise_on_missing=True,
                    performance=performance,
                )
                records = frame.to_dict(orient="records")
                grouped_profiles = []
                for profile_index in frame["profile_index"].drop_duplicates():
                    profile_rows = frame[
                        frame["profile_index"] == profile_index
                    ]
                    grouped_profiles.append(
                        {
                            "profile_index": int(profile_index),
                            "profile_name": str(
                                profile_rows.iloc[0]["profile_name"]
                            ),
                            "products": profile_rows.to_dict(orient="records"),
                        }
                    )
                flat_files = list(
                    dict.fromkeys(
                        path
                        for record in records
                        for path in record["files"]
                    )
                )
                output_directories = sorted(
                    {str(Path(path).parent) for path in flat_files}
                )
                summary["plans"][plan_num] = {
                    "success": True,
                    "output_dir": (
                        output_directories[0]
                        if len(output_directories) == 1
                        else None
                    ),
                    "files": flat_files,
                    "stored_maps": records,
                    "profiles": grouped_profiles,
                    "performance": json.loads(
                        json.dumps(frame.attrs, default=str)
                    ),
                }
            else:
                generated = RasProcess.store_maps(**shared_arguments)
                files_by_type = {
                    map_type: [str(path) for path in paths]
                    for map_type, paths in generated.items()
                }
                flat_files = [
                    path for paths in files_by_type.values() for path in paths
                ]
                output_directories = sorted(
                    {str(Path(path).parent) for path in flat_files}
                )
                summary["plans"][plan_num] = {
                    "success": True,
                    "output_dir": (
                        output_directories[0]
                        if len(output_directories) == 1
                        else None
                    ),
                    "files": flat_files,
                    "files_by_type": files_by_type,
                }
        except Exception as exc:
            logger.error("Failed to generate maps for plan %s: %s", plan_num, exc)
            summary["success"] = False
            summary["plans"][plan_num] = {
                "success": False,
                "error": str(exc),
            }
            partial_frame = getattr(exc, "frame", None)
            if isinstance(partial_frame, pd.DataFrame):
                # StoredMapProductsIncompleteError: the generated products
                # were preserved on disk, so report them with the missing
                # ones instead of discarding the file list.
                partial_records = json.loads(
                    partial_frame.to_json(orient="records")
                )
                summary["plans"][plan_num].update(
                    {
                        "files": list(
                            dict.fromkeys(
                                path
                                for record in partial_records
                                if record.get("status") == "generated"
                                for path in record["files"]
                            )
                        ),
                        "stored_maps": partial_records,
                        "missing": [
                            record
                            for record in partial_records
                            if record.get("status") != "generated"
                        ],
                    }
                )
            if raise_on_error:
                raise

    return summary

get_results_folder staticmethod

Python
get_results_folder(plan_number: Union[str, int, float], ras_object=None) -> Path

Get the folder path containing raster results for a specified plan.

HEC-RAS creates output folders based on the plan's Short Identifier. Windows folder naming replaces special characters with underscores.

Parameters:

Name Type Description Default
plan_number Union[str, int, float]

Plan number (accepts flexible formats like 1, "01", "001").

required
ras_object RasPrj

Optional RAS object instance.

None

Returns:

Type Description
Path

Path to the mapping output folder.

Raises:

Type Description
ValueError

If the plan number is not found or output folder doesn't exist.

Examples:

Python Console Session
>>> folder = RasMap.get_results_folder("01")
>>> folder = RasMap.get_results_folder(1)
>>> folder = RasMap.get_results_folder("08", ras_object=my_project)
Notes
  • Normalizes plan number to two-digit format ("01", "02", etc.)
  • Retrieves Short Identifier from plan_df
  • Normalizes Short ID for Windows folder naming (special chars -> underscores)
  • Searches project folder for matching output directory
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_results_folder(
    plan_number: Union[str, int, float], ras_object=None
) -> Path:
    """
    Get the folder path containing raster results for a specified plan.

    HEC-RAS creates output folders based on the plan's Short Identifier.
    Windows folder naming replaces special characters with underscores.

    Args:
        plan_number (Union[str, int, float]): Plan number (accepts flexible formats like 1, "01", "001").
        ras_object (RasPrj, optional): Optional RAS object instance.

    Returns:
        Path: Path to the mapping output folder.

    Raises:
        ValueError: If the plan number is not found or output folder doesn't exist.

    Examples:
        >>> folder = RasMap.get_results_folder("01")
        >>> folder = RasMap.get_results_folder(1)
        >>> folder = RasMap.get_results_folder("08", ras_object=my_project)

    Notes:
        - Normalizes plan number to two-digit format ("01", "02", etc.)
        - Retrieves Short Identifier from plan_df
        - Normalizes Short ID for Windows folder naming (special chars -> underscores)
        - Searches project folder for matching output directory
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Normalize plan number to two-digit format
    plan_number = RasUtils.normalize_ras_number(plan_number)

    # Get plan metadata from plan_df
    plan_df = ras_obj.plan_df
    plan_info = plan_df[plan_df["plan_number"] == plan_number]

    if plan_info.empty:
        raise ValueError(
            f"Plan {plan_number} not found in project. "
            f"Available plans: {list(plan_df['plan_number'])}"
        )

    short_id = plan_info.iloc[0]["Short Identifier"]

    if pd.isna(short_id) or not short_id:
        raise ValueError(
            f"Plan {plan_number} does not have a Short Identifier. "
            "Check the plan file for missing metadata."
        )

    # Normalize Short ID to match Windows folder naming
    # RASMapper replaces special characters for Windows compatibility
    replacements = {
        "/": "_",
        "\\": "_",
        ":": "_",
        "*": "_",
        "?": "_",
        '"': "_",
        "<": "_",
        ">": "_",
        "|": "_",
        "+": "_",
        " ": "_",
    }

    normalized = short_id
    for old, new in replacements.items():
        normalized = normalized.replace(old, new)

    # Remove trailing underscores
    normalized = normalized.rstrip("_")

    # Search for output folder in project directory
    project_folder = ras_obj.project_folder

    # Try exact match with Short ID
    exact_match = project_folder / short_id
    if exact_match.exists() and exact_match.is_dir():
        logger.debug("Found output folder by exact match: %s", exact_match)
        return exact_match

    # Try normalized name
    normalized_match = project_folder / normalized
    if normalized_match.exists() and normalized_match.is_dir():
        logger.debug(
            "Found output folder by normalized match: %s", normalized_match
        )
        return normalized_match

    # Try partial match (contains)
    for item in project_folder.iterdir():
        if not item.is_dir():
            continue
        folder_name = item.name
        # Check if short_id is contained in folder name or vice versa
        if short_id in folder_name or folder_name in short_id:
            logger.debug("Found output folder by partial match: %s", item)
            return item
        # Check normalized version
        if normalized in folder_name or folder_name in normalized:
            logger.debug(
                "Found output folder by normalized partial match: %s", item
            )
            return item

    # No folder found
    raise ValueError(
        f"Output folder not found for plan {plan_number} (Short ID: '{short_id}'). "
        f"Expected folder name: '{normalized}' in {project_folder}. "
        "Ensure the plan has been run and RASMapper has exported results."
    )

get_results_raster staticmethod

Python
get_results_raster(plan_number: Union[str, int, float], variable_name: str, ras_object=None) -> Path

Get the .vrt file path for a specified plan and variable name.

This function locates VRT (Virtual Raster) files exported by RASMapper for a specific hydraulic variable (e.g., WSE, Depth, Velocity).

Parameters:

Name Type Description Default
plan_number Union[str, int, float]

Plan number (accepts flexible formats).

required
variable_name str

Variable name to search for in VRT filenames (e.g., "WSE", "Depth", "Velocity").

required
ras_object RasPrj

Optional RAS object instance.

None

Returns:

Type Description
Path

Path to the matching .vrt file.

Raises:

Type Description
ValueError

If no matching files or multiple matching files are found.

Examples:

Python Console Session
>>> vrt = RasMap.get_results_raster("01", "WSE")
>>> vrt = RasMap.get_results_raster(1, "Depth")
>>> vrt = RasMap.get_results_raster("08", "WSE (Max)", ras_object=my_project)
Notes
  • Uses get_results_folder() to locate the output directory
  • Searches for .vrt files containing the variable_name (case-insensitive)
  • If multiple files match, lists all matches and raises an error
  • User should make variable_name more specific to narrow results
  • VRT files are lightweight virtual rasters that reference underlying .tif tiles
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def get_results_raster(
    plan_number: Union[str, int, float], variable_name: str, ras_object=None
) -> Path:
    """
    Get the .vrt file path for a specified plan and variable name.

    This function locates VRT (Virtual Raster) files exported by RASMapper
    for a specific hydraulic variable (e.g., WSE, Depth, Velocity).

    Args:
        plan_number (Union[str, int, float]): Plan number (accepts flexible formats).
        variable_name (str): Variable name to search for in VRT filenames (e.g., "WSE", "Depth", "Velocity").
        ras_object (RasPrj, optional): Optional RAS object instance.

    Returns:
        Path: Path to the matching .vrt file.

    Raises:
        ValueError: If no matching files or multiple matching files are found.

    Examples:
        >>> vrt = RasMap.get_results_raster("01", "WSE")
        >>> vrt = RasMap.get_results_raster(1, "Depth")
        >>> vrt = RasMap.get_results_raster("08", "WSE (Max)", ras_object=my_project)

    Notes:
        - Uses get_results_folder() to locate the output directory
        - Searches for .vrt files containing the variable_name (case-insensitive)
        - If multiple files match, lists all matches and raises an error
        - User should make variable_name more specific to narrow results
        - VRT files are lightweight virtual rasters that reference underlying .tif tiles
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Get the mapping folder for this plan
    mapping_folder = RasMap.get_results_folder(plan_number, ras_obj)

    # List all .vrt files in the folder
    vrt_files = list(mapping_folder.glob("*.vrt"))

    if not vrt_files:
        raise ValueError(
            f"No .vrt files found in mapping folder: {mapping_folder}. "
            "Ensure RASMapper has exported raster results for this plan."
        )

    # Filter files containing variable_name (case-insensitive)
    matching_files = [
        f for f in vrt_files if variable_name.lower() in f.name.lower()
    ]

    # Handle results
    if len(matching_files) == 0:
        available_files = [f.name for f in vrt_files]
        raise ValueError(
            f"No .vrt files found matching variable name '{variable_name}' in {mapping_folder}. "
            f"Available files: {available_files}. "
            "Try making variable_name more specific or check for typos."
        )
    elif len(matching_files) == 1:
        logger.debug("Found matching VRT file: %s", matching_files[0])
        return matching_files[0]
    else:
        logger.debug(
            "Multiple .vrt files match '%s': %s",
            variable_name,
            [f.name for f in matching_files],
        )

        raise ValueError(
            f"Multiple .vrt files ({len(matching_files)}) match variable name '{variable_name}'. "
            f"Matching files: {[f.name for f in matching_files]}. "
            "Please make variable_name more specific (e.g., 'WSE (Max)' instead of 'WSE')."
        )

scan_results_folders staticmethod

Python
scan_results_folders(ras_folder: Path) -> Dict[str, Dict]

Scan RAS project folder for results folders containing raster files.

Parameters:

Name Type Description Default
ras_folder Path

Path to HEC-RAS project folder containing .prj file

required

Returns:

Type Description
Dictionary mapping folder names to folder information
{folder_name

{'path': Path, 'has_vrt': bool, 'has_tif': bool}}

Examples:

Python Console Session
>>> folders = RasMap.scan_results_folders(Path("/path/to/project"))
>>> for name, info in folders.items():
...     print(f"{name}: {info['path']}")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def scan_results_folders(ras_folder: Path) -> Dict[str, Dict]:
    """
    Scan RAS project folder for results folders containing raster files.

    Args:
        ras_folder: Path to HEC-RAS project folder containing .prj file

    Returns:
        Dictionary mapping folder names to folder information:
        {folder_name: {'path': Path, 'has_vrt': bool, 'has_tif': bool}}

    Examples:
        >>> folders = RasMap.scan_results_folders(Path("/path/to/project"))
        >>> for name, info in folders.items():
        ...     print(f"{name}: {info['path']}")
    """
    results = {}
    for folder in ras_folder.iterdir():
        if folder.is_dir() and not folder.name.startswith("."):
            # Check for raster files
            tif_files = list(folder.glob("*.tif"))
            vrt_files = list(folder.glob("*.vrt"))

            if tif_files or vrt_files:
                results[folder.name] = {
                    "path": folder,
                    "has_vrt": len(vrt_files) > 0,
                    "has_tif": len(tif_files) > 0,
                }
                logger.debug(
                    f"Found results folder: {folder.name} "
                    f"(VRT: {len(vrt_files)}, TIF: {len(tif_files)})"
                )
    return results

find_results_folder staticmethod

Python
find_results_folder(ras_folder: Path, short_id: str) -> Optional[Path]

Find results folder for a plan Short ID.

Parameters:

Name Type Description Default
ras_folder Path

Path to HEC-RAS project folder

required
short_id str

Plan Short Identifier (from plan file)

required

Returns:

Type Description
Optional[Path]

Path to results folder, or None if not found

Examples:

Python Console Session
>>> folder = RasMap.find_results_folder(Path("/path/to/project"), "H100_CP")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def find_results_folder(ras_folder: Path, short_id: str) -> Optional[Path]:
    """
    Find results folder for a plan Short ID.

    Args:
        ras_folder: Path to HEC-RAS project folder
        short_id: Plan Short Identifier (from plan file)

    Returns:
        Path to results folder, or None if not found

    Examples:
        >>> folder = RasMap.find_results_folder(Path("/path/to/project"), "H100_CP")
    """
    # Normalize Short ID to match Windows folder naming
    # RASMapper replaces special characters for Windows compatibility
    replacements = {
        "/": "_",
        "\\": "_",
        ":": "_",
        "*": "_",
        "?": "_",
        '"': "_",
        "<": "_",
        ">": "_",
        "|": "_",
        "+": "_",
        " ": "_",
    }

    normalized = short_id
    for old, new in replacements.items():
        normalized = normalized.replace(old, new)

    # Remove trailing underscores
    normalized = normalized.rstrip("_")

    # Scan for folders
    folders = RasMap.scan_results_folders(ras_folder)

    # Try exact match
    if short_id in folders:
        return folders[short_id]["path"]

    # Try normalized name
    if normalized in folders:
        return folders[normalized]["path"]

    # Try partial match
    for folder_name, folder_info in folders.items():
        # Check if short_id is contained in folder name or vice versa
        if short_id in folder_name or folder_name in short_id:
            return folder_info["path"]
        # Check normalized version
        if normalized in folder_name or folder_name in normalized:
            return folder_info["path"]

    return None

resolve_raster_paths staticmethod

Python
resolve_raster_paths(results_folder: Path) -> Dict[str, Optional[Path]]

Resolve WSE and Depth raster paths from results folder.

Priority order: 1. Unsteady flow VRT files (e.g., "Depth (Max).vrt") 2. Steady flow VRT files (e.g., "Depth.vrt") 3. Unsteady flow TIF files (e.g., "Depth (Max).tif") 4. Steady flow TIF files (e.g., "Depth.tif")

Parameters:

Name Type Description Default
results_folder Path

Path to RASMapper results folder

required

Returns:

Type Description
Dict[str, Optional[Path]]

Dictionary with 'wse' and 'depth' paths (or None if not found)

Examples:

Python Console Session
>>> rasters = RasMap.resolve_raster_paths(Path("/path/to/project/H100_CP"))
>>> wse_path = rasters['wse']
>>> depth_path = rasters['depth']
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def resolve_raster_paths(results_folder: Path) -> Dict[str, Optional[Path]]:
    """
    Resolve WSE and Depth raster paths from results folder.

    Priority order:
    1. Unsteady flow VRT files (e.g., "Depth (Max).vrt")
    2. Steady flow VRT files (e.g., "Depth.vrt")
    3. Unsteady flow TIF files (e.g., "Depth (Max).tif")
    4. Steady flow TIF files (e.g., "Depth.tif")

    Args:
        results_folder: Path to RASMapper results folder

    Returns:
        Dictionary with 'wse' and 'depth' paths (or None if not found)

    Examples:
        >>> rasters = RasMap.resolve_raster_paths(Path("/path/to/project/H100_CP"))
        >>> wse_path = rasters['wse']
        >>> depth_path = rasters['depth']
    """
    result = {"wse": None, "depth": None}

    # Priority 1: Look for unsteady flow VRT files (with "max")
    for vrt_file in results_folder.glob("*.vrt"):
        name_lower = vrt_file.name.lower()
        if "depth" in name_lower and "max" in name_lower:
            result["depth"] = vrt_file
            logger.debug(f"Found unsteady depth VRT: {vrt_file.name}")
        elif "wse" in name_lower and "max" in name_lower:
            result["wse"] = vrt_file
            logger.debug(f"Found unsteady WSE VRT: {vrt_file.name}")

    # Priority 2: Look for steady flow VRT files (without "max") - only if not already found
    if not result["depth"] or not result["wse"]:
        for vrt_file in results_folder.glob("*.vrt"):
            name_lower = vrt_file.name.lower()
            name_base = vrt_file.stem.lower()

            # Match depth files - steady flow patterns
            if (
                not result["depth"]
                and "depth" in name_lower
                and "max" not in name_lower
            ):
                if (
                    name_base == "depth"
                    or name_base.startswith("depth (")
                    or name_base.startswith("depth ")
                    or name_base.startswith("depth_grid")
                ):
                    result["depth"] = vrt_file
                    logger.debug(f"Found steady depth VRT: {vrt_file.name}")

            # Match WSE files - steady flow patterns
            elif (
                not result["wse"]
                and "wse" in name_lower
                and "max" not in name_lower
            ):
                if (
                    name_base == "wse"
                    or name_base.startswith("wse (")
                    or name_base.startswith("wse ")
                    or name_base.startswith("wse_grid")
                ):
                    result["wse"] = vrt_file
                    logger.debug(f"Found steady WSE VRT: {vrt_file.name}")

    # Priority 3: Fall back to unsteady flow TIF files if no VRT found
    if not result["depth"] or not result["wse"]:
        for tif_file in results_folder.glob("*.tif"):
            name_lower = tif_file.name.lower()
            if (
                not result["depth"]
                and "depth" in name_lower
                and "max" in name_lower
            ):
                result["depth"] = tif_file
                logger.debug(f"Found unsteady depth TIF: {tif_file.name}")
            elif not result["wse"] and "wse" in name_lower and "max" in name_lower:
                result["wse"] = tif_file
                logger.debug(f"Found unsteady WSE TIF: {tif_file.name}")

    # Priority 4: Fall back to steady flow TIF files if still not found
    if not result["depth"] or not result["wse"]:
        for tif_file in results_folder.glob("*.tif"):
            name_lower = tif_file.name.lower()
            name_base = tif_file.stem.lower()

            # Match depth TIF files - steady flow patterns
            if (
                not result["depth"]
                and "depth" in name_lower
                and "max" not in name_lower
            ):
                if (
                    name_base == "depth"
                    or name_base.startswith("depth (")
                    or name_base.startswith("depth ")
                    or name_base.startswith("depth_grid")
                ):
                    result["depth"] = tif_file
                    logger.debug(f"Found steady depth TIF: {tif_file.name}")

            # Match WSE TIF files - steady flow patterns
            elif (
                not result["wse"]
                and "wse" in name_lower
                and "max" not in name_lower
            ):
                if (
                    name_base == "wse"
                    or name_base.startswith("wse (")
                    or name_base.startswith("wse ")
                    or name_base.startswith("wse_grid")
                ):
                    result["wse"] = tif_file
                    logger.debug(f"Found steady WSE TIF: {tif_file.name}")

    # Log detected model type
    if result["depth"] or result["wse"]:
        depth_path = str(result.get("depth", "")).lower()
        wse_path = str(result.get("wse", "")).lower()
        if "max" in depth_path or "max" in wse_path:
            logger.debug("Detected unsteady flow model in %s", results_folder.name)
        else:
            logger.debug("Detected steady flow model in %s", results_folder.name)

    return result

find_steady_raster staticmethod

Python
find_steady_raster(results_folder: Path, profile_name: str, raster_type: str) -> Optional[Path]

Find steady state raster for a specific profile.

Parameters:

Name Type Description Default
results_folder Path

Path to RASMapper results folder

required
profile_name str

Profile name (e.g., "1Pct", "10Pct", "50Pct")

required
raster_type str

Type of raster ('WSE' or 'Depth')

required

Returns:

Type Description
Optional[Path]

Path to raster file, or None if not found

Examples:

Python Console Session
>>> raster = RasMap.find_steady_raster(Path("/path/to/project/H100_CP"), "10Pct", "WSE")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def find_steady_raster(
    results_folder: Path, profile_name: str, raster_type: str
) -> Optional[Path]:
    """
    Find steady state raster for a specific profile.

    Args:
        results_folder: Path to RASMapper results folder
        profile_name: Profile name (e.g., "1Pct", "10Pct", "50Pct")
        raster_type: Type of raster ('WSE' or 'Depth')

    Returns:
        Path to raster file, or None if not found

    Examples:
        >>> raster = RasMap.find_steady_raster(Path("/path/to/project/H100_CP"), "10Pct", "WSE")
    """
    # Search patterns for steady state profile-specific rasters
    # Pattern 1: Standard format with parentheses "WSE (1Pct).vrt"
    pattern1 = f"{raster_type} ({profile_name}).vrt"
    vrt_path = results_folder / pattern1
    if vrt_path.exists():
        logger.debug(f"Found steady raster (pattern 1): {vrt_path.name}")
        return vrt_path

    # Pattern 2: Terrain-specific variant "WSE (1Pct).Terrain.{terrain_name}.tif"
    pattern2 = f"{raster_type} ({profile_name}).Terrain.*.tif"
    tif_files = list(results_folder.glob(pattern2))
    if tif_files:
        logger.debug(f"Found steady raster (pattern 2): {tif_files[0].name}")
        return tif_files[0]

    # Pattern 3: Underscore format "WSE_1Pct.vrt"
    pattern3 = f"{raster_type}_{profile_name}.vrt"
    alt_vrt = results_folder / pattern3
    if alt_vrt.exists():
        logger.debug(f"Found steady raster (pattern 3): {alt_vrt.name}")
        return alt_vrt

    # Pattern 4: Space instead of underscore "WSE 1Pct.vrt"
    pattern4 = f"{raster_type} {profile_name}.vrt"
    space_vrt = results_folder / pattern4
    if space_vrt.exists():
        logger.debug(f"Found steady raster (pattern 4): {space_vrt.name}")
        return space_vrt

    # Pattern 5: TIF variant without terrain suffix
    pattern5 = f"{raster_type} ({profile_name}).tif"
    tif_path = results_folder / pattern5
    if tif_path.exists():
        logger.debug(f"Found steady raster (pattern 5): {tif_path.name}")
        return tif_path

    logger.warning(
        f"Could not find steady state raster for profile '{profile_name}', type {raster_type}. "
        f"Searched in: {results_folder}"
    )
    return None

list_results_plans staticmethod

Python
list_results_plans(ras_object=None) -> List[Dict[str, Any]]

List all plan result layers in the RASMapper configuration file.

Enumerates all <Layer Type="RASResults"> entries under the <Results> section of the .rasmap file. These are the valid host plans for calculated layers.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
List[Dict[str, Any]]

List of dicts with keys: - name (str): Plan result layer name (e.g., "Prop_10yr_Reg_BO") - filename (str): Relative path to the plan HDF file - checked (bool): Whether the layer is visible

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> plans = RasMap.list_results_plans()
>>> for p in plans:
...     print(f"{p['name']} - {p['filename']}")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_results_plans(ras_object=None) -> List[Dict[str, Any]]:
    """
    List all plan result layers in the RASMapper configuration file.

    Enumerates all ``<Layer Type="RASResults">`` entries under the ``<Results>``
    section of the ``.rasmap`` file. These are the valid host plans for
    calculated layers.

    Args:
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        List[Dict[str, Any]]: List of dicts with keys:
            - ``name`` (str): Plan result layer name (e.g., "Prop_10yr_Reg_BO")
            - ``filename`` (str): Relative path to the plan HDF file
            - ``checked`` (bool): Whether the layer is visible

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> plans = RasMap.list_results_plans()
        >>> for p in plans:
        ...     print(f"{p['name']} - {p['filename']}")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return []

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return []

    results = root.find("Results")
    if results is None:
        logger.debug("No Results section found in .rasmap")
        return []

    plans = []
    for layer in results.findall("Layer"):
        if layer.get("Type") == "RASResults":
            plans.append(
                {
                    "name": layer.get("Name", ""),
                    "filename": layer.get("Filename", ""),
                    "checked": layer.get("Checked", "True").lower() == "true",
                }
            )

    logger.debug("Found %d results plan(s) in .rasmap", len(plans))
    return plans

ensure_results_plan_layer staticmethod

Python
ensure_results_plan_layer(plan_number_or_path: Union[str, int, float, Path], *, name: Optional[str] = None, checked: bool = True, expanded: bool = True, ras_object=None) -> Dict[str, Any]

Ensure a plan HDF is registered in the RASMapper Results tree.

This is useful after cloning and computing a plan programmatically, when command-line execution creates <project>.p##.hdf but does not add a corresponding RASResults layer to the project .rasmap.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def ensure_results_plan_layer(
    plan_number_or_path: Union[str, int, float, Path],
    *,
    name: Optional[str] = None,
    checked: bool = True,
    expanded: bool = True,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Ensure a plan HDF is registered in the RASMapper ``Results`` tree.

    This is useful after cloning and computing a plan programmatically, when
    command-line execution creates ``<project>.p##.hdf`` but does not add a
    corresponding ``RASResults`` layer to the project ``.rasmap``.
    """
    plan_path = _resolve_plan_file_for_rasmap(
        plan_number_or_path,
        ras_object=ras_object,
    )
    project_folder = plan_path.parent
    project_name = _project_name_from_plan_path(plan_path)
    rasmap_path = expected_rasmap_path(project_folder, project_name)
    hdf_path = Path(str(plan_path) + ".hdf")

    if not hdf_path.exists():
        raise FileNotFoundError(f"Plan results HDF not found: {hdf_path}")

    if rasmap_path.exists():
        try:
            tree = ET.parse(rasmap_path)
            root = tree.getroot()
        except ET.ParseError as e:
            raise ValueError(f"Error parsing .rasmap XML: {e}") from e
    else:
        root = ET.Element("RASMapper")
        tree = ET.ElementTree(root)

    results = root.find("Results")
    if results is None:
        results = ET.Element("Results", {"Checked": "True", "Expanded": "True"})
        root.append(results)
    else:
        results.set("Checked", results.get("Checked", "True"))
        results.set("Expanded", results.get("Expanded", "True"))

    rel_hdf = _rasmap_relative_path(project_folder, hdf_path)
    rel_hdf_norm = _normalize_rasmap_filename(rel_hdf)
    layer = None
    for candidate in results.findall("Layer"):
        if candidate.get("Type") != "RASResults":
            continue
        if _normalize_rasmap_filename(candidate.get("Filename")) == rel_hdf_norm:
            layer = candidate
            break

    if layer is None:
        layer = ET.SubElement(results, "Layer")

    layer_name = name or _plan_display_name_for_rasmap(plan_path)
    layer.set("Name", layer_name)
    layer.set("Type", "RASResults")
    layer.set("Checked", "True" if checked else "False")
    layer.set("Expanded", "True" if expanded else "False")
    layer.set("Filename", rel_hdf)

    _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=False)
    record = {
        "name": layer_name,
        "filename": rel_hdf,
        "checked": checked,
        "expanded": expanded,
        "rasmap_path": rasmap_path,
    }
    logger.info("Ensured RASResults layer '%s'", layer_name)
    logger.debug("Updated RASMapper file: %s", rasmap_path)
    return record

list_results_map_layers staticmethod

Python
list_results_map_layers(ras_object=None) -> List[Dict[str, Any]]

List RASResultsMap child layers under RASMapper result plans.

Returns dictionaries with the parent result plan name, layer name, visibility, and raw MapParameters attributes.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_results_map_layers(ras_object=None) -> List[Dict[str, Any]]:
    """
    List ``RASResultsMap`` child layers under RASMapper result plans.

    Returns dictionaries with the parent result plan name, layer name,
    visibility, and raw ``MapParameters`` attributes.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return []

    try:
        root = ET.parse(rasmap_path).getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return []

    results = root.find("Results")
    if results is None:
        return []

    layers = []
    for results_layer in results.findall("Layer"):
        if results_layer.get("Type") != "RASResults":
            continue
        for child in results_layer.findall("Layer"):
            if child.get("Type") != "RASResultsMap":
                continue
            map_parameters = child.find("MapParameters")
            layers.append(
                {
                    "name": child.get("Name", ""),
                    "parent_plan": results_layer.get("Name", ""),
                    "checked": child.get("Checked", "False").lower() == "true",
                    "filename": child.get("Filename", ""),
                    "map_parameters": (
                        dict(map_parameters.attrib)
                        if map_parameters is not None
                        else {}
                    ),
                }
            )

    logger.debug("Found %d result map layer(s) in .rasmap", len(layers))
    return layers

add_results_map_layer staticmethod

Python
add_results_map_layer(host_plan_name: str, layer_name: str, map_type: str, *, terrain_name: Optional[str] = None, profile_index: int = 2147483647, profile_name: str = 'Max', checked: bool = True, replace_existing: bool = True, ras_object=None) -> Dict[str, Any]

Add a RASResultsMap child layer under an existing RASMapper result plan.

This is useful for tutorial workflows that need first-class map layers such as Depth * Velocity before comparing floodway encroachment results.

Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_results_map_layer(
    host_plan_name: str,
    layer_name: str,
    map_type: str,
    *,
    terrain_name: Optional[str] = None,
    profile_index: int = 2147483647,
    profile_name: str = "Max",
    checked: bool = True,
    replace_existing: bool = True,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Add a ``RASResultsMap`` child layer under an existing RASMapper result plan.

    This is useful for tutorial workflows that need first-class map layers
    such as ``Depth * Velocity`` before comparing floodway encroachment
    results.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        raise FileNotFoundError(f"RASMapper file not found: {rasmap_path}")

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        raise ValueError(f"Error parsing .rasmap XML: {e}") from e

    results = root.find("Results")
    if results is None:
        raise ValueError("No Results section found in .rasmap")

    host_layer = None
    for layer in results.findall("Layer"):
        if (
            layer.get("Type") == "RASResults"
            and layer.get("Name") == host_plan_name
        ):
            host_layer = layer
            break

    if host_layer is None:
        raise ValueError(
            f"RASResults plan '{host_plan_name}' not found in .rasmap Results section"
        )

    if replace_existing:
        for child in list(host_layer.findall("Layer")):
            if (
                child.get("Type") == "RASResultsMap"
                and child.get("Name") == layer_name
            ):
                host_layer.remove(child)

    result_map = ET.SubElement(
        host_layer,
        "Layer",
        {
            "Name": layer_name,
            "Type": "RASResultsMap",
            "Checked": "True" if checked else "False",
        },
    )
    map_parameters = ET.SubElement(result_map, "MapParameters")
    map_parameters.set("MapType", map_type)
    map_parameters.set("LayerName", layer_name)
    if terrain_name:
        map_parameters.set("Terrain", terrain_name)
    map_parameters.set("ProfileIndex", str(profile_index))
    map_parameters.set("ProfileName", profile_name)
    map_parameters.set("ArrivalDepth", "0")

    _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=False)
    record = {
        "name": layer_name,
        "parent_plan": host_plan_name,
        "checked": checked,
        "map_parameters": dict(map_parameters.attrib),
    }
    logger.info(
        "Added result map layer '%s' to plan '%s'", layer_name, host_plan_name
    )
    return record

list_calculated_layers staticmethod

Python
list_calculated_layers(ras_object=None) -> List[Dict[str, Any]]

List all calculated layers across all plan results in the RASMapper configuration.

Enumerates all <Layer Type="CalculatedLayer"> entries nested within <Layer Type="RASResults"> blocks.

Parameters:

Name Type Description Default
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
List[Dict[str, Any]]

List of dicts with keys: - name (str): Calculated layer name - parent_plan (str): Name of the host RASResults plan - filename (str): Relative path to the .rasscript file - checked (bool): Whether the layer is visible - profile_index (str): ProfileIndex attribute value - raster_maps (List[Dict]): Input raster maps, each with result, map_type, profile_index, animation_behavior - terrains (List[str]): Input terrain layer names

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> layers = RasMap.list_calculated_layers()
>>> for l in layers:
...     print(f"{l['name']} (under {l['parent_plan']})")
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def list_calculated_layers(ras_object=None) -> List[Dict[str, Any]]:
    """
    List all calculated layers across all plan results in the RASMapper configuration.

    Enumerates all ``<Layer Type="CalculatedLayer">`` entries nested within
    ``<Layer Type="RASResults">`` blocks.

    Args:
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        List[Dict[str, Any]]: List of dicts with keys:
            - ``name`` (str): Calculated layer name
            - ``parent_plan`` (str): Name of the host RASResults plan
            - ``filename`` (str): Relative path to the .rasscript file
            - ``checked`` (bool): Whether the layer is visible
            - ``profile_index`` (str): ProfileIndex attribute value
            - ``raster_maps`` (List[Dict]): Input raster maps, each with
              ``result``, ``map_type``, ``profile_index``, ``animation_behavior``
            - ``terrains`` (List[str]): Input terrain layer names

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> layers = RasMap.list_calculated_layers()
        >>> for l in layers:
        ...     print(f"{l['name']} (under {l['parent_plan']})")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return []

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return []

    results = root.find("Results")
    if results is None:
        return []

    calc_layers = []
    for results_layer in results.findall("Layer"):
        if results_layer.get("Type") != "RASResults":
            continue
        parent_plan = results_layer.get("Name", "")

        for child in results_layer.findall("Layer"):
            if child.get("Type") != "CalculatedLayer":
                continue

            raster_maps = []
            for rm in child.findall("RasterMap"):
                raster_maps.append(
                    {
                        "result": rm.get("Result", ""),
                        "map_type": rm.get("MapType", ""),
                        "profile_index": rm.get("ProfileIndex", ""),
                        "animation_behavior": rm.get("AnimationBehavior", ""),
                    }
                )

            terrains = [t.get("Name", "") for t in child.findall("Terrain")]

            calc_layers.append(
                {
                    "name": child.get("Name", ""),
                    "parent_plan": parent_plan,
                    "filename": child.get("Filename", ""),
                    "checked": child.get("Checked", "False").lower() == "true",
                    "profile_index": child.get("ProfileIndex", "0"),
                    "raster_maps": raster_maps,
                    "terrains": terrains,
                }
            )

    logger.debug("Found %d calculated layer(s) in .rasmap", len(calc_layers))
    return calc_layers

add_calculated_layer staticmethod

Python
add_calculated_layer(layer_name: str, host_plan_name: str, script_content: str, raster_maps: List[Dict[str, str]], terrain_names: List[str], checked: bool = True, profile_index: int = 0, ras_object=None) -> bool

Add a calculated layer to the RASMapper configuration and write its .rasscript file.

Creates a .rasscript file in the Calculated Layers/ subdirectory and registers it as a <Layer Type="CalculatedLayer"> under the specified host plan's <Layer Type="RASResults"> block. Includes a default viewport-dynamic diverging color ramp (blue=benefit, red=adverse).

If a calculated layer with the same name already exists in the host plan, it is replaced (matching the add_terrain_layer convention).

Parameters:

Name Type Description Default
layer_name str

Display name for the calculated layer.

required
host_plan_name str

Name of the RASResults plan to nest this layer under. Must match a <Layer Name="..." Type="RASResults"> in the rasmap.

required
script_content str

Full VB.NET .rasscript content string.

required
raster_maps List[Dict[str, str]]

List of dicts defining input raster maps. Each dict should have: - result (str): Plan result name - map_type (str, optional): Default "elevation" - animation_behavior (str, optional): Default "Fixed Profile" - profile_index (str, optional): Default "2147483647" (Max)

required
terrain_names List[str]

List of terrain layer names (order must match inputTiles indices in the script).

required
checked bool

Whether the layer is visible in RASMapper. Default True.

True
profile_index int

ProfileIndex attribute for the calculated layer. Default 0.

0
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
bool

True if the layer was successfully added.

Raises:

Type Description
FileNotFoundError

If the .rasmap file does not exist.

ValueError

If host_plan_name is not found in the Results section.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> RasMap.add_calculated_layer(
...     layer_name="CompareWSE_10yr_Reg",
...     host_plan_name="Prop_10yr_Reg_BO",
...     script_content=script_text,
...     raster_maps=[
...         {"result": "Exist_10yr_Reg_BO"},
...         {"result": "Prop_10yr_Reg_BO"},
...     ],
...     terrain_names=["Bathy_QESDrone_", "Terrain_Proposed_20260313"],
... )
Notes
  • Creates the Calculated Layers directory if it doesn't exist.
  • Replaces any existing calculated layer with the same name in the host plan.
  • The .rasscript file is written with UTF-8 encoding.
  • inputTiles indices in the script must match the order of RasterMap then Terrain children in the XML.
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_calculated_layer(
    layer_name: str,
    host_plan_name: str,
    script_content: str,
    raster_maps: List[Dict[str, str]],
    terrain_names: List[str],
    checked: bool = True,
    profile_index: int = 0,
    ras_object=None,
) -> bool:
    """
    Add a calculated layer to the RASMapper configuration and write its .rasscript file.

    Creates a ``.rasscript`` file in the ``Calculated Layers/`` subdirectory and
    registers it as a ``<Layer Type="CalculatedLayer">`` under the specified host
    plan's ``<Layer Type="RASResults">`` block. Includes a default viewport-dynamic
    diverging color ramp (blue=benefit, red=adverse).

    If a calculated layer with the same name already exists in the host plan, it is
    replaced (matching the ``add_terrain_layer`` convention).

    Args:
        layer_name: Display name for the calculated layer.
        host_plan_name: Name of the RASResults plan to nest this layer under.
            Must match a ``<Layer Name="..." Type="RASResults">`` in the rasmap.
        script_content: Full VB.NET ``.rasscript`` content string.
        raster_maps: List of dicts defining input raster maps. Each dict should have:
            - ``result`` (str): Plan result name
            - ``map_type`` (str, optional): Default ``"elevation"``
            - ``animation_behavior`` (str, optional): Default ``"Fixed Profile"``
            - ``profile_index`` (str, optional): Default ``"2147483647"`` (Max)
        terrain_names: List of terrain layer names (order must match inputTiles
            indices in the script).
        checked: Whether the layer is visible in RASMapper. Default True.
        profile_index: ProfileIndex attribute for the calculated layer. Default 0.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        bool: True if the layer was successfully added.

    Raises:
        FileNotFoundError: If the .rasmap file does not exist.
        ValueError: If ``host_plan_name`` is not found in the Results section.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> RasMap.add_calculated_layer(
        ...     layer_name="CompareWSE_10yr_Reg",
        ...     host_plan_name="Prop_10yr_Reg_BO",
        ...     script_content=script_text,
        ...     raster_maps=[
        ...         {"result": "Exist_10yr_Reg_BO"},
        ...         {"result": "Prop_10yr_Reg_BO"},
        ...     ],
        ...     terrain_names=["Bathy_QESDrone_", "Terrain_Proposed_20260313"],
        ... )

    Notes:
        - Creates the ``Calculated Layers`` directory if it doesn't exist.
        - Replaces any existing calculated layer with the same name in the host plan.
        - The .rasscript file is written with UTF-8 encoding.
        - inputTiles indices in the script must match the order of RasterMap
          then Terrain children in the XML.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        raise FileNotFoundError(f"RASMapper file not found: {rasmap_path}")

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return False

    # Find the Results section
    results = root.find("Results")
    if results is None:
        raise ValueError("No Results section found in .rasmap")

    # Find the host plan's RASResults layer
    host_layer = None
    for layer in results.findall("Layer"):
        if (
            layer.get("Type") == "RASResults"
            and layer.get("Name") == host_plan_name
        ):
            host_layer = layer
            break

    if host_layer is None:
        raise ValueError(
            f"RASResults plan '{host_plan_name}' not found in .rasmap Results section"
        )

    # Remove existing calculated layer with same name (replace-if-exists)
    for child in host_layer.findall("Layer"):
        if (
            child.get("Type") == "CalculatedLayer"
            and child.get("Name") == layer_name
        ):
            host_layer.remove(child)
            logger.info(f"Replacing existing calculated layer '{layer_name}'")

    # Create Calculated Layers directory
    calc_dir = ras_obj.project_folder / "Calculated Layers"
    calc_dir.mkdir(parents=True, exist_ok=True)

    # Write .rasscript file
    script_path = calc_dir / f"{layer_name}.rasscript"
    script_path.write_text(script_content, encoding="utf-8")
    logger.debug("Written script: %s", script_path.name)

    # Build relative path with .\ prefix and backslashes
    rel_path_str = f".\\Calculated Layers\\{layer_name}.rasscript"

    # Build XML element
    calc_elem = ET.SubElement(host_layer, "Layer")
    calc_elem.set("Name", layer_name)
    calc_elem.set("Type", "CalculatedLayer")
    calc_elem.set("Checked", "True" if checked else "False")
    calc_elem.set("Filename", rel_path_str)
    calc_elem.set("ProfileIndex", str(profile_index))

    resample = ET.SubElement(calc_elem, "ResampleMethod")
    resample.text = "near"

    # Symbology with viewport-dynamic diverging color ramp
    symbology = ET.SubElement(calc_elem, "Symbology")
    surface_fill = ET.SubElement(symbology, "SurfaceFill")
    surface_fill.set("Colors", _WSE_COMPARISON_DEFAULT_COLORS)
    surface_fill.set("Values", _WSE_COMPARISON_DEFAULT_VALUES)
    surface_fill.set("Stretched", "True")
    surface_fill.set("AlphaTag", "255")
    surface_fill.set("UseDatasetMinMax", "False")
    surface_fill.set("RegenerateForScreen", "True")

    surface = ET.SubElement(calc_elem, "Surface")
    surface.set("On", "True")

    # Add RasterMap inputs
    for rm in raster_maps:
        rm_elem = ET.SubElement(calc_elem, "RasterMap")
        rm_elem.set("Result", rm["result"])
        rm_elem.set("MapType", rm.get("map_type", "elevation"))
        rm_elem.set(
            "AnimationBehavior", rm.get("animation_behavior", "Fixed Profile")
        )
        rm_elem.set("ProfileIndex", rm.get("profile_index", "2147483647"))

    # Add Terrain inputs
    for terrain_name in terrain_names:
        t_elem = ET.SubElement(calc_elem, "Terrain")
        t_elem.set("Name", terrain_name)

    # Write updated rasmap
    _write_ras_xml(tree, rasmap_path, encoding="utf-8", xml_declaration=False)
    logger.info(f"Added calculated layer '{layer_name}' to plan '{host_plan_name}'")
    return True

remove_calculated_layer staticmethod

Python
remove_calculated_layer(layer_name: str, host_plan_name: Optional[str] = None, delete_script: bool = False, ras_object=None) -> bool

Remove a calculated layer from the RASMapper configuration.

Parameters:

Name Type Description Default
layer_name str

Name of the calculated layer to remove.

required
host_plan_name Optional[str]

If provided, only search within that specific RASResults block. If None, searches all RASResults blocks and removes the first match.

None
delete_script bool

If True, also delete the .rasscript file from disk.

False
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
bool

True if the layer was found and removed, False if not found.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> init_ras_project("/path/to/project", "7.0")
>>> RasMap.remove_calculated_layer("CompareWSE_10yr_Reg", delete_script=True)
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def remove_calculated_layer(
    layer_name: str,
    host_plan_name: Optional[str] = None,
    delete_script: bool = False,
    ras_object=None,
) -> bool:
    """
    Remove a calculated layer from the RASMapper configuration.

    Args:
        layer_name: Name of the calculated layer to remove.
        host_plan_name: If provided, only search within that specific RASResults
            block. If None, searches all RASResults blocks and removes the first match.
        delete_script: If True, also delete the ``.rasscript`` file from disk.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        bool: True if the layer was found and removed, False if not found.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> init_ras_project("/path/to/project", "7.0")
        >>> RasMap.remove_calculated_layer("CompareWSE_10yr_Reg", delete_script=True)
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    if not rasmap_path.exists():
        logger.warning(f"RASMapper file not found: {rasmap_path}")
        return False

    try:
        tree = ET.parse(rasmap_path)
        root = tree.getroot()
    except ET.ParseError as e:
        logger.error(f"Error parsing .rasmap XML: {e}")
        return False

    results = root.find("Results")
    if results is None:
        logger.warning("No Results section found in .rasmap")
        return False

    # Determine which RASResults layers to search
    search_layers = []
    for layer in results.findall("Layer"):
        if layer.get("Type") != "RASResults":
            continue
        if host_plan_name is None or layer.get("Name") == host_plan_name:
            search_layers.append(layer)

    # Find and remove
    for results_layer in search_layers:
        for child in results_layer.findall("Layer"):
            if (
                child.get("Type") == "CalculatedLayer"
                and child.get("Name") == layer_name
            ):
                script_filename = child.get("Filename", "")
                results_layer.remove(child)

                _write_ras_xml(
                    tree, rasmap_path, encoding="utf-8", xml_declaration=False
                )
                logger.info(
                    f"Removed calculated layer '{layer_name}' from "
                    f"'{results_layer.get('Name')}'"
                )

                if delete_script and script_filename:
                    # Resolve relative path from project folder
                    script_rel = script_filename.replace("\\", "/").lstrip("./")
                    script_path = ras_obj.project_folder / script_rel
                    script_path.unlink(missing_ok=True)
                    logger.debug("Deleted script file: %s", script_path.name)
                    logger.debug("Deleted script path: %s", script_path)

                return True

    logger.warning(f"Calculated layer '{layer_name}' not found in .rasmap")
    return False

add_wse_comparison_layers staticmethod

Python
add_wse_comparison_layers(plan_pairs: List[Dict[str, str]], exist_terrain: str, prop_terrain: str, layer_name_template: str = 'CompareWSE_{tag}', host_plan: str = 'proposed', ras_object=None) -> List[str]

Add WSE comparison calculated layers for multiple existing/proposed plan pairs.

Generates .rasscript files and registers calculated layers for each pair. The formula is Proposed WSE - Existing WSE:

  • Positive values = WSE raised by project (rise / adverse impact)
  • Negative values = WSE lowered by project (drop / benefit)

When a cell is dry in one plan, the terrain elevation for that plan's scenario is used as the WSE fallback.

Parameters:

Name Type Description Default
plan_pairs List[Dict[str, str]]

List of dicts, each with keys: - exist_plan (str): Name of the existing conditions plan result - prop_plan (str): Name of the proposed conditions plan result - tag (str): Short identifier used in layer naming (e.g., "10yr_Reg")

required
exist_terrain str

Terrain layer name for existing conditions (dry-cell fallback).

required
prop_terrain str

Terrain layer name for proposed conditions (dry-cell fallback).

required
layer_name_template str

Format string for layer names. Must contain {tag}. Default: "CompareWSE_{tag}".

'CompareWSE_{tag}'
host_plan str

Which plan to host the calculated layer under — "proposed" (default) or "existing".

'proposed'
ras_object RasPrj

Optional RasPrj object instance.

None

Returns:

Type Description
List[str]

Names of successfully created layers.

Raises:

Type Description
ValueError

If a referenced plan name is not found in the Results section, or if a terrain name is not found in the Terrains section.

Examples:

Python Console Session
>>> from ras_commander import init_ras_project, RasMap
>>> ras = init_ras_project("/path/to/project", "7.0")
>>> created = RasMap.add_wse_comparison_layers(
...     plan_pairs=[
...         {"exist_plan": "Exist_10yr_Reg_BO", "prop_plan": "Prop_10yr_Reg_BO", "tag": "10yr_Reg"},
...         {"exist_plan": "Exist_10yr_Loc_BO", "prop_plan": "Prop_10yr_Loc_BO", "tag": "10yr_Loc"},
...         {"exist_plan": "Exist_100yr_Reg_BO", "prop_plan": "Prop_100yr_Reg_BO", "tag": "100yr_Reg"},
...     ],
...     exist_terrain="Bathy_QESDrone_",
...     prop_terrain="Terrain_Proposed_20260313",
... )
>>> print(f"Created {len(created)} comparison layers")
Notes
  • Each plan pair generates one .rasscript file and one rasmap XML entry.
  • Layers are hosted under the proposed plan by default (host_plan="proposed").
  • Uses Max profile (ProfileIndex=2147483647) with Fixed Profile animation.
  • Includes a viewport-dynamic diverging color ramp by default.
Source code in ras_commander/RasMap.py
Python
@staticmethod
@log_call
def add_wse_comparison_layers(
    plan_pairs: List[Dict[str, str]],
    exist_terrain: str,
    prop_terrain: str,
    layer_name_template: str = "CompareWSE_{tag}",
    host_plan: str = "proposed",
    ras_object=None,
) -> List[str]:
    """
    Add WSE comparison calculated layers for multiple existing/proposed plan pairs.

    Generates ``.rasscript`` files and registers calculated layers for each pair.
    The formula is ``Proposed WSE - Existing WSE``:

    - **Positive values** = WSE raised by project (rise / adverse impact)
    - **Negative values** = WSE lowered by project (drop / benefit)

    When a cell is dry in one plan, the terrain elevation for that plan's scenario
    is used as the WSE fallback.

    Args:
        plan_pairs: List of dicts, each with keys:
            - ``exist_plan`` (str): Name of the existing conditions plan result
            - ``prop_plan`` (str): Name of the proposed conditions plan result
            - ``tag`` (str): Short identifier used in layer naming (e.g., "10yr_Reg")
        exist_terrain: Terrain layer name for existing conditions (dry-cell fallback).
        prop_terrain: Terrain layer name for proposed conditions (dry-cell fallback).
        layer_name_template: Format string for layer names. Must contain ``{tag}``.
            Default: ``"CompareWSE_{tag}"``.
        host_plan: Which plan to host the calculated layer under — ``"proposed"``
            (default) or ``"existing"``.
        ras_object (RasPrj, optional): Optional RasPrj object instance.

    Returns:
        List[str]: Names of successfully created layers.

    Raises:
        ValueError: If a referenced plan name is not found in the Results section,
            or if a terrain name is not found in the Terrains section.

    Examples:
        >>> from ras_commander import init_ras_project, RasMap
        >>> ras = init_ras_project("/path/to/project", "7.0")
        >>> created = RasMap.add_wse_comparison_layers(
        ...     plan_pairs=[
        ...         {"exist_plan": "Exist_10yr_Reg_BO", "prop_plan": "Prop_10yr_Reg_BO", "tag": "10yr_Reg"},
        ...         {"exist_plan": "Exist_10yr_Loc_BO", "prop_plan": "Prop_10yr_Loc_BO", "tag": "10yr_Loc"},
        ...         {"exist_plan": "Exist_100yr_Reg_BO", "prop_plan": "Prop_100yr_Reg_BO", "tag": "100yr_Reg"},
        ...     ],
        ...     exist_terrain="Bathy_QESDrone_",
        ...     prop_terrain="Terrain_Proposed_20260313",
        ... )
        >>> print(f"Created {len(created)} comparison layers")

    Notes:
        - Each plan pair generates one ``.rasscript`` file and one rasmap XML entry.
        - Layers are hosted under the proposed plan by default (``host_plan="proposed"``).
        - Uses Max profile (ProfileIndex=2147483647) with Fixed Profile animation.
        - Includes a viewport-dynamic diverging color ramp by default.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Validate referenced plans exist
    existing_plans = RasMap.list_results_plans(ras_object=ras_obj)
    plan_names = {p["name"] for p in existing_plans}

    for pair in plan_pairs:
        for key in ("exist_plan", "prop_plan", "tag"):
            if key not in pair:
                raise ValueError(
                    f"Missing required key '{key}' in plan_pairs entry: {pair}"
                )
        if pair["exist_plan"] not in plan_names:
            raise ValueError(
                f"Existing plan '{pair['exist_plan']}' not found in .rasmap Results. "
                f"Available plans: {sorted(plan_names)}"
            )
        if pair["prop_plan"] not in plan_names:
            raise ValueError(
                f"Proposed plan '{pair['prop_plan']}' not found in .rasmap Results. "
                f"Available plans: {sorted(plan_names)}"
            )

    # Validate terrain names exist
    rasmap_path = expected_rasmap_path(ras_obj.project_folder, ras_obj.project_name)
    terrain_names = RasMap.get_terrain_names(rasmap_path)
    for t_name in (exist_terrain, prop_terrain):
        if t_name not in terrain_names:
            raise ValueError(
                f"Terrain '{t_name}' not found in .rasmap. "
                f"Available terrains: {terrain_names}"
            )

    # Generate calculated layers
    exist_terrain_var = _sanitize_vbnet_identifier(exist_terrain)
    prop_terrain_var = _sanitize_vbnet_identifier(prop_terrain)

    created = []
    for pair in plan_pairs:
        layer_name = layer_name_template.format(tag=pair["tag"])
        host_plan_name = (
            pair["prop_plan"] if host_plan == "proposed" else pair["exist_plan"]
        )

        script_content = _WSE_COMPARISON_RASSCRIPT_TEMPLATE.format(
            layer_name=layer_name,
            exist_plan=pair["exist_plan"],
            prop_plan=pair["prop_plan"],
            exist_terrain_name=exist_terrain,
            prop_terrain_name=prop_terrain,
            exist_terrain_var=exist_terrain_var,
            prop_terrain_var=prop_terrain_var,
        )

        raster_maps = [
            {"result": pair["exist_plan"]},
            {"result": pair["prop_plan"]},
        ]

        success = RasMap.add_calculated_layer(
            layer_name=layer_name,
            host_plan_name=host_plan_name,
            script_content=script_content,
            raster_maps=raster_maps,
            terrain_names=[exist_terrain, prop_terrain],
            ras_object=ras_obj,
        )

        if success:
            created.append(layer_name)
            logger.debug("Created WSE comparison layer: %s", layer_name)
        else:
            logger.warning(f"Failed to create layer: {layer_name}")

    logger.info(
        f"Created {len(created)} of {len(plan_pairs)} WSE comparison layers"
    )
    return created

Headless mapping, resources and raster products

Native command failures

The packaged RasStoreMapHelper.exe runs installed RAS Mapper library commands. Aggregate exports use StoreAllMapsCommand; independent map exports use the StoreMapCommand factories followed by headless native map storage. Both routes use the same Commander helper executable, not different mapping engines.

Native aggregate commands can report a fatal error through their progress reporter and return without throwing. Commander captures these messages, returns a nonzero helper exit code, and raises an error from RasProcess.store_maps(). Files left by a failed command are not evidence of a completed export. The helper does not retry automatically or repair missing pixel values.

In Windows HEC-RAS 7.0.1 tests of the public Davis pipe-network example, aggregate horizontal Max exports intermittently failed during pipe-rendering cache updates inside RASPipeNetworks.RenderMeshPipeRenderOptions.SetLastMesh. The captured exception reached DataRow mutation from parallel pipe rasterization. Failed exports could leave all-nodata TIFFs without georeferencing. The project PRJ, result HDF and terrain agreed on EPSG:2871; explicit projection initialization still reproduced the failure, as did exports with Python georeferencing repair disabled.

A diagnostic control restricted inherited process affinity to one logical CPU: all 20 aggregate calls completed, and all 10 calls with georeferencing repair enabled exactly matched the Rust comparison on 4,883 wet pixels after a strict depth greater than 0.5 ft filter. Four-CPU diagnostic controls failed in 5 of 8 calls, including a separate control with explicit projection initialization. These observations support a native concurrency defect; they do not establish a general repair. max_workers=1 limits helper processes, not native internal threads. Commander does not automatically apply this Windows affinity control, and independent exports are not a guaranteed workaround.

Sloping render options

RasProcess.store_maps(render_mode=None) reads the project's current render configuration through RasMap.get_water_surface_render_mode(). For slopingPretty, the helper receives both reduce_shallow_to_horizontal and use_depth_weighted_faces; it does not replace explicit settings with helper defaults. Bare mode names retain their existing default behavior.

Configure these flags with RasMap.set_water_surface_render_mode() before calling store_maps(render_mode=None). Setting the configuration is a persistent project edit. The stored-map call restores the configuration present at its own entry, including the selected flags; it does not undo a preceding setter call. These options affect native sloping interpolation and are distinct from the optional pixel depth cutoff applied after mapping. See HEC's Mapping Options for the two sloping modes and their display controls.

Static class for automating HEC-RAS operations via RasProcess.exe CLI.

This class provides methods to: - Find RasProcess.exe in standard HEC-RAS installation paths - Generate stored maps using StoreAllMaps command - Configure stored maps in .rasmap files - Fix georeferencing issues in generated TIFs - Run on Linux via Wine (auto-detected, no code changes needed)

All methods are static and follow the ras-commander pattern of accepting an optional ras_object parameter for multi-project support.

Example (Windows - unchanged): >>> from ras_commander import init_ras_project, RasProcess >>> init_ras_project("path/to/project", "7.0") >>> results = RasProcess.store_maps( ... plan_number="01", ... output_folder="Maps", ... wse=True, ... depth=True, ... velocity=True ... )

Example (Linux with Wine): >>> from ras_commander import init_ras_project, RasProcess >>> # Auto-detects Linux and uses default Wine prefix >>> init_ras_project("/path/to/project", "7.0") >>> results = RasProcess.store_maps(plan_number="01") >>> >>> # Or configure Wine explicitly: >>> RasProcess.configure_wine( ... wine_prefix="/opt/hecras-wine", ... ras_install_dir="/opt/hecras-wine/drive_c/HEC-RAS/6.6" ... )

get_store_maps_runtime_provenance staticmethod

Python
get_store_maps_runtime_provenance(ras_object=None) -> Dict[str, Any]

Return content identities for the actual StoreMaps runtime.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def get_store_maps_runtime_provenance(ras_object=None) -> Dict[str, Any]:
    """Return content identities for the actual StoreMaps runtime."""

    ras_obj = ras_object or ras
    ras_obj.check_initialized()
    hecras_dir = Path(str(ras_obj.ras_exe_path)).parent
    if not hecras_dir.is_dir():
        raise FileNotFoundError(f"HEC-RAS directory not found: {hecras_dir}")
    return store_maps_runtime_provenance(hecras_dir)

configure_wine staticmethod

Python
configure_wine(wine_prefix: Union[str, Path] = None, wine_executable: str = 'wine', ras_install_dir: Union[str, Path] = None) -> WineConfig

Configure Wine environment for Linux execution.

Call this once before using RasProcess on Linux if the defaults don't match your setup. If not called, auto-detection is used.

Parameters:

Name Type Description Default
wine_prefix Union[str, Path]

Path to WINEPREFIX (default: auto-detect from WINE_PREFIX_PATHS)

None
wine_executable str

Wine binary name or path used to launch Windows executables under Wine. Auxiliary tools such as winepath are resolved automatically.

'wine'
ras_install_dir Union[str, Path]

Path to directory containing RasProcess.exe and DLLs. Can be a Linux path (under drive_c/) or left None for auto-detect.

None

Returns:

Type Description
WineConfig

WineConfig instance that was set.

Example

RasProcess.configure_wine( ... wine_prefix="/opt/hecras-wine", ... ras_install_dir="/opt/hecras-wine/drive_c/HEC-RAS" ... )

Source code in ras_commander/RasProcess.py
Python
@staticmethod
def configure_wine(
    wine_prefix: Union[str, Path] = None,
    wine_executable: str = "wine",
    ras_install_dir: Union[str, Path] = None,
) -> WineConfig:
    """
    Configure Wine environment for Linux execution.

    Call this once before using RasProcess on Linux if the defaults
    don't match your setup. If not called, auto-detection is used.

    Args:
        wine_prefix: Path to WINEPREFIX (default: auto-detect from WINE_PREFIX_PATHS)
        wine_executable: Wine binary name or path used to launch
                        Windows executables under Wine. Auxiliary tools
                        such as ``winepath`` are resolved automatically.
        ras_install_dir: Path to directory containing RasProcess.exe and DLLs.
                       Can be a Linux path (under drive_c/) or left None for auto-detect.

    Returns:
        WineConfig instance that was set.

    Example:
        >>> RasProcess.configure_wine(
        ...     wine_prefix="/opt/hecras-wine",
        ...     ras_install_dir="/opt/hecras-wine/drive_c/HEC-RAS"
        ... )
    """
    if wine_prefix is None:
        wine_prefix = RasProcess._find_wine_prefix()
        if wine_prefix is None:
            raise FileNotFoundError(
                "No Wine prefix found. Searched: "
                + ", ".join(RasProcess.WINE_PREFIX_PATHS)
                + ". Set WINEPREFIX or call configure_wine(wine_prefix=...)"
            )

    wine_prefix = Path(wine_prefix)
    if not wine_prefix.exists():
        raise FileNotFoundError(f"Wine prefix not found: {wine_prefix}")

    ras_dir = Path(ras_install_dir) if ras_install_dir else None

    config = WineConfig(
        wine_prefix=wine_prefix,
        wine_executable=wine_executable,
        ras_install_dir=ras_dir,
    )
    RasProcess._wine_config = config
    ras_dir_state = "configured" if ras_dir is not None else "not configured"
    logger.info(
        "Wine configured for RasProcess: executable=%s, ras_dir=%s",
        wine_executable,
        ras_dir_state,
    )
    logger.debug(
        "Wine configuration paths: prefix=%s, ras_dir=%s", wine_prefix, ras_dir
    )
    return config

check_wine_environment staticmethod

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

Verify the Wine environment is properly configured for RasProcess.

Uses the configured wine_executable when one was provided via configure_wine().

Returns a dict with status of each component: - wine_found: bool - wine_version: str or None - wine_prefix: str or None - dotnet48: bool (checks for .NET 4.8 marker files) - gdiplus: bool (checks for native gdiplus override) - rasprocess_found: bool - hdf5_found: bool

Example

status = RasProcess.check_wine_environment() if all(status.values()): ... print("Wine environment ready!") else: ... print("Missing:", [k for k,v in status.items() if not v])

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def check_wine_environment() -> Dict[str, Any]:
    """
    Verify the Wine environment is properly configured for RasProcess.

    Uses the configured ``wine_executable`` when one was provided via
    ``configure_wine()``.

    Returns a dict with status of each component:
    - wine_found: bool
    - wine_version: str or None
    - wine_prefix: str or None
    - dotnet48: bool (checks for .NET 4.8 marker files)
    - gdiplus: bool (checks for native gdiplus override)
    - rasprocess_found: bool
    - hdf5_found: bool

    Example:
        >>> status = RasProcess.check_wine_environment()
        >>> if all(status.values()):
        ...     print("Wine environment ready!")
        >>> else:
        ...     print("Missing:", [k for k,v in status.items() if not v])
    """
    result = {
        "wine_found": False,
        "wine_version": None,
        "wine_prefix": None,
        "prefix_exists": False,
        "dotnet48": False,
        "gdiplus": False,
        "corefonts": False,
        "rasprocess_found": False,
        "hdf5_found": False,
    }

    config = RasProcess._get_wine_config()
    wine_executable = RasProcess._resolve_wine_tool_executable(
        "wine",
        config,
    )

    # Check wine binary
    try:
        proc = subprocess.run(
            [wine_executable, "--version"],
            capture_output=True,
            text=True,
            timeout=10,
            env=RasProcess._build_wine_env(
                config,
                include_winedebug=False,
            ),
        )
        if proc.returncode == 0:
            result["wine_found"] = True
            result["wine_version"] = proc.stdout.strip()
    except (FileNotFoundError, subprocess.TimeoutExpired):
        pass

    # Check Wine prefix
    if config and config.wine_prefix:
        result["wine_prefix"] = str(config.wine_prefix)
        result["prefix_exists"] = config.wine_prefix.exists()

        drive_c = config.wine_prefix / "drive_c"
        if drive_c.exists():
            # Check .NET 4.8
            dotnet_markers = [
                drive_c
                / "windows"
                / "Microsoft.NET"
                / "Framework64"
                / "v4.0.30319"
                / "mscorlib.dll",
                drive_c
                / "windows"
                / "Microsoft.NET"
                / "Framework"
                / "v4.0.30319"
                / "mscorlib.dll",
            ]
            result["dotnet48"] = any(m.exists() for m in dotnet_markers)

            # Check gdiplus native override
            gdiplus_path = drive_c / "windows" / "system32" / "gdiplus.dll"
            result["gdiplus"] = gdiplus_path.exists()

            # Check fonts
            fonts_path = drive_c / "windows" / "Fonts" / "arial.ttf"
            result["corefonts"] = fonts_path.exists()

            # Check RasProcess.exe
            rasprocess = RasProcess.find_rasprocess()
            result["rasprocess_found"] = rasprocess is not None

            # Check HDF5 DLLs
            # Search in common locations
            for search_dir in [drive_c]:
                for hdf5 in search_dir.rglob("hdf5.dll"):
                    result["hdf5_found"] = True
                    break
                if result["hdf5_found"]:
                    break

    return result

setup_wine_environment staticmethod

Python
setup_wine_environment(wine_prefix: Union[str, Path] = '/opt/hecras-wine', ras_version: str = '7.0') -> None

Print setup instructions for the Wine environment.

This does NOT automatically install — it prints the commands needed. Actual installation requires root/sudo and takes ~20 minutes.

Parameters:

Name Type Description Default
wine_prefix Union[str, Path]

Target Wine prefix path

'/opt/hecras-wine'
ras_version str

HEC-RAS version to configure for

'7.0'
Source code in ras_commander/RasProcess.py
Python
    @staticmethod
    @log_call
    def setup_wine_environment(
        wine_prefix: Union[str, Path] = "/opt/hecras-wine",
        ras_version: str = "7.0",
    ) -> None:
        """
        Print setup instructions for the Wine environment.

        This does NOT automatically install — it prints the commands needed.
        Actual installation requires root/sudo and takes ~20 minutes.

        Args:
            wine_prefix: Target Wine prefix path
            ras_version: HEC-RAS version to configure for
        """
        instructions = f"""
=== Wine Environment Setup for RasProcess.exe ===

Prerequisites: Debian/Ubuntu Linux with sudo access.
Estimated time: ~20 minutes (mostly .NET 4.8 install).

Step 1: Install Wine and winetricks
    sudo dpkg --add-architecture i386
    sudo apt update
    sudo apt install -y wine wine64 wine32 winetricks cabextract

Step 2: Create Wine prefix with .NET 4.8
    export WINEPREFIX={wine_prefix}
    export WINEARCH=win64
    export DISPLAY=
    wineboot --init
    winetricks -q dotnet48     # ~15 min, installs .NET Framework 4.8
    winetricks -q gdiplus      # Native GDI+ (required for System.Drawing)
    winetricks -q corefonts    # Arial, Times New Roman, etc.

Step 3: Copy HEC-RAS DLLs from a Windows installation
    # From a Windows machine with HEC-RAS {ras_version} installed:
    # Copy the following from C:\\Program Files (x86)\\HEC\\HEC-RAS\\{ras_version}\\
    # to {wine_prefix}/drive_c/HEC-RAS/{ras_version}/

    Required files (from HEC-RAS install root):
        RasProcess.exe
        H5Assist.dll
        HDF.PInvoke.dll
        Geospatial.Core.dll
        Geospatial.GDALAssist.dll
        Geospatial.IO.dll
        Geospatial.Rendering.dll
        BitMiracle.LibTiff.NET.dll
        Hec.Dss.dll
        HecCs.dll
        MathNet.Numerics.dll
        (and all other DLLs in the root folder)

    Required files (from HEC-RAS x64/ subfolder):
        hdf5.dll
        hdf5_hl.dll
        hdf5_tools.dll
        libifcoremd.dll
        libiomp5md.dll
        libmmd.dll

    Required folder:
        GDAL/ (entire folder with bin64/ contents)

Step 4: Verify installation
    >>> from ras_commander import RasProcess
    >>> status = RasProcess.check_wine_environment()
    >>> print(status)

Step 5: Configure (optional — auto-detection usually works)
    >>> RasProcess.configure_wine(
    ...     wine_prefix="{wine_prefix}",
    ...     ras_install_dir="{wine_prefix}/drive_c/HEC-RAS/{ras_version}"
    ... )
"""
        print(instructions)
        logger.debug(
            "Wine setup instructions printed. Follow steps to configure environment."
        )

find_rasprocess staticmethod

Python
find_rasprocess(ras_version: Optional[Union[str, Path]] = None) -> Optional[Path]

Find RasProcess.exe beside an explicit executable or discovered runtime.

On Windows, resolves the requested release before searching Program Files. On Linux, searches within the Wine prefix drive_c/ directory.

Parameters:

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

Release (e.g., "7.0.2"), executable path, or install directory. If None, searches all known paths.

None

Returns:

Type Description
Optional[Path]

Path to RasProcess.exe if found, None otherwise.

Optional[Path]

On Linux, returns the Linux filesystem path (under drive_c/).

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def find_rasprocess(ras_version: Optional[Union[str, Path]] = None) -> Optional[Path]:
    """
    Find RasProcess.exe beside an explicit executable or discovered runtime.

    On Windows, resolves the requested release before searching Program Files.
    On Linux, searches within the Wine prefix drive_c/ directory.

    Args:
        ras_version: Release (e.g., "7.0.2"), executable path, or install directory.
                    If None, searches all known paths.

    Returns:
        Path to RasProcess.exe if found, None otherwise.
        On Linux, returns the Linux filesystem path (under drive_c/).
    """
    if ras_version:
        requested = Path(ras_version)
        if requested.is_dir():
            candidate = requested / "RasProcess.exe"
            return candidate if candidate.is_file() else None
        if requested.is_file():
            candidate = requested.parent / "RasProcess.exe"
            return candidate if candidate.is_file() else None

    if IS_WINDOWS:
        if ras_version:
            from .RasPrj import get_ras_exe

            executable = get_ras_exe(ras_version)
            if executable != "Ras.exe":
                candidate = Path(executable).parent / "RasProcess.exe"
                # Never substitute another installation when discovery found
                # the requested engine but its companion is missing.
                return candidate if candidate.is_file() else None
        # Original Windows behavior
        if ras_version:
            paths = [
                Path(
                    f"C:/Program Files (x86)/HEC/HEC-RAS/{ras_version}/RasProcess.exe"
                ),
                Path(f"C:/Program Files/HEC/HEC-RAS/{ras_version}/RasProcess.exe"),
            ]
        else:
            paths = [
                Path(p) / "RasProcess.exe" for p in RasProcess.RAS_INSTALL_PATHS
            ]

        for path in paths:
            if path.exists():
                logger.debug(f"Found RasProcess.exe at: {path}")
                return path

    elif IS_LINUX:
        config = RasProcess._get_wine_config()
        if config is None:
            logger.warning("No Wine prefix found on Linux")
            return None

        drive_c = config.wine_prefix / "drive_c"

        # Check explicitly configured ras_install_dir first
        if config.ras_install_dir:
            exe = Path(config.ras_install_dir) / "RasProcess.exe"
            if exe.exists():
                logger.debug(f"Found RasProcess.exe at configured path: {exe}")
                return exe

        # Search common locations under drive_c
        search_dirs = []

        if ras_version:
            search_dirs.extend(
                [
                    drive_c
                    / "Program Files (x86)"
                    / "HEC"
                    / "HEC-RAS"
                    / ras_version,
                    drive_c / "Program Files" / "HEC" / "HEC-RAS" / ras_version,
                    drive_c / "HEC-RAS" / ras_version,
                    drive_c / "HEC-RAS",
                ]
            )
        else:
            # Search all known version paths
            for win_path in RasProcess.RAS_INSTALL_PATHS:
                # Convert Windows path to Linux path under drive_c
                relative = win_path.replace("C:\\", "").replace("\\", "/")
                search_dirs.append(drive_c / relative)

            # Also search common custom locations
            search_dirs.extend(
                [
                    drive_c / "HEC-RAS",
                    drive_c / "hecras",
                ]
            )

        for search_dir in search_dirs:
            exe = search_dir / "RasProcess.exe"
            if exe.exists():
                logger.debug(f"Found RasProcess.exe at: {exe}")
                return exe

        # Last resort: recursive search under drive_c (slow but thorough)
        logger.debug("Searching drive_c recursively for RasProcess.exe...")
        for exe in drive_c.rglob("RasProcess.exe"):
            logger.debug(f"Found RasProcess.exe at: {exe}")
            return exe

    logger.warning("RasProcess.exe not found in standard installation paths")
    return None

get_plan_timestamps staticmethod

Python
get_plan_timestamps(plan_number: str, ras_object=None) -> List[str]

Get available output timestamps for a plan in RASMapper format.

Parameters:

Name Type Description Default
plan_number str

Plan number (e.g., "01", "06")

required
ras_object RasPrj

Optional RAS object instance

None

Returns:

Type Description
List of timestamp strings in format "DDMMMYYYY HH

MM:SS" (e.g., "10SEP2018 02:30:00")

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def get_plan_timestamps(plan_number: str, ras_object=None) -> List[str]:
    """
    Get available output timestamps for a plan in RASMapper format.

    Args:
        plan_number: Plan number (e.g., "01", "06")
        ras_object (RasPrj, optional): Optional RAS object instance

    Returns:
        List of timestamp strings in format "DDMMMYYYY HH:MM:SS" (e.g., "10SEP2018 02:30:00")
    """
    from .hdf.HdfPlan import HdfPlan

    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Get HDF path for plan
    plan_num = RasUtils.normalize_ras_number(plan_number)
    hdf_path = ras_obj.project_folder / f"{ras_obj.project_name}.p{plan_num}.hdf"

    if not hdf_path.exists():
        logger.error(f"Plan HDF not found: {hdf_path}")
        return []

    try:
        timestamps = HdfPlan.get_plan_timestamps_list(hdf_path)
        # Convert to RASMapper format: "DDMMMYYYY HH:MM:SS"
        rasmap_timestamps = []
        for ts in timestamps:
            # Format: 10SEP2018 02:30:00
            formatted = ts.strftime("%d%b%Y %H:%M:%S").upper()
            rasmap_timestamps.append(formatted)
        return rasmap_timestamps
    except Exception as e:
        reraise_required(e)
        logger.error(f"Failed to get timestamps from {hdf_path}: {e}")
        return []

estimate_store_map_resources staticmethod

Python
estimate_store_map_resources(plan_number: str, map_types: Sequence[str] = ('wse', 'depth', 'velocity'), *, terrain_name: Optional[str] = None, performance: Optional[StoreMapPerformanceOptions] = None, ras_object=None) -> StoreMapResourceEstimate

Estimate StoreMap worker limits without modifying the project.

The estimate is deliberately conservative and reports its formula and limiters. It does not edit the .rasmap, create output directories, or launch HEC-RAS helpers. An explicit native job cap plans combined private commit plus the OS reserve and verifies the pinned runtime identity; the actual helper cap is probed only by store_maps.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def estimate_store_map_resources(
    plan_number: str,
    map_types: Sequence[str] = ("wse", "depth", "velocity"),
    *,
    terrain_name: Optional[str] = None,
    performance: Optional[StoreMapPerformanceOptions] = None,
    ras_object=None,
) -> StoreMapResourceEstimate:
    """Estimate StoreMap worker limits without modifying the project.

    The estimate is deliberately conservative and reports its formula and
    limiters. It does not edit the `.rasmap`, create output directories, or
    launch HEC-RAS helpers. An explicit native job cap plans combined
    private commit plus the OS reserve and verifies the pinned runtime
    identity; the actual helper cap is probed only by ``store_maps``.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()
    options = performance or StoreMapPerformanceOptions()
    if not isinstance(options, StoreMapPerformanceOptions):
        raise TypeError("performance must be a StoreMapPerformanceOptions")

    normalized_plan = RasUtils.normalize_ras_number(plan_number)
    plan_hdf = (
        ras_obj.project_folder / f"{ras_obj.project_name}.p{normalized_plan}.hdf"
    )
    if not plan_hdf.exists():
        raise FileNotFoundError(f"Plan HDF not found: {plan_hdf}")
    rasmap_path = RasMap.get_rasmap_path(ras_obj)
    if rasmap_path is None:
        raise FileNotFoundError("No .rasmap file found in project folder")

    normalized_maps = tuple(
        dict.fromkeys(str(item).strip().casefold() for item in map_types)
    )
    if not normalized_maps or any(not item for item in normalized_maps):
        raise ValueError("map_types must contain at least one non-empty value")
    _validate_native_job_cap_route(options, normalized_maps)
    cap_terrain = None
    cap_runtime = None
    if options.native_job_memory_limit_mb is not None:
        from ._native_helper import validate_native_job_memory_runtime
        cap_runtime = validate_native_job_memory_runtime(Path(str(ras_obj.ras_exe_path)).parent)
        layers = RasMap.list_terrain_layers(ras_obj.project_folder, ras_object=ras_obj)
        selected = layers if terrain_name is None else layers.loc[layers["name"] == terrain_name]
        if len(selected) != 1:
            raise ValueError("native job cap requires exactly one selected registered terrain")
        cap_terrain = {"name": str(selected.iloc[0]["name"]),
                       "terrain_hdf": str(Path(selected.iloc[0]["resolved_path"]).resolve(strict=True))}
    supported_maps = {"wse", "depth", "velocity"}
    fallback_reasons = []
    unsupported = sorted(set(normalized_maps) - supported_maps)
    if unsupported:
        fallback_reasons.append(
            "parallel helper is unavailable for map types " + ", ".join(unsupported)
        )
    if terrain_name is not None:
        fallback_reasons.append(
            "parallel helper is unavailable with explicit terrain selection"
        )
    if len(normalized_maps) < 2:
        fallback_reasons.append("fewer than two independent map jobs")

    projection = RasProcess._get_projection_info(Path(rasmap_path))
    terrain_paths = projection.terrain_paths
    if not terrain_paths and projection.terrain_path is not None:
        terrain_paths = (projection.terrain_path,)
    terrain_estimates, estimate_warnings = _terrain_resource_estimates(
        terrain_paths
    )
    if (not terrain_estimates and options.worker_memory_override_mb is None
            and options.native_job_memory_limit_mb is None):
        fallback_reasons.append(
            "active terrain dimensions are unavailable for memory estimation"
        )

    raw_surface_mb = sum(item.float32_surface_mb for item in terrain_estimates)
    if options.native_job_memory_limit_mb is not None:
        base_worker_mb = options.native_job_memory_limit_mb
        estimate_source = "native_job_cap"
    elif options.worker_memory_override_mb is not None:
        base_worker_mb = options.worker_memory_override_mb
        estimate_source = "override"
    elif terrain_estimates:
        base_worker_mb = max(
            options.minimum_worker_memory_mb,
            int(raw_surface_mb * 4 + 512 + 0.999),
        )
        estimate_source = "heuristic"
    else:
        base_worker_mb = options.minimum_worker_memory_mb
        estimate_source = "floor"
    # GDAL_CACHEMAX is a per-helper cap. Conservatively include an explicit
    # cap in admission so large per-process caches cannot oversubscribe RAM.
    estimated_gdal_cache_mb = options.gdal_cachemax_mb or 0
    estimated_worker_mb = (base_worker_mb if options.native_job_memory_limit_mb is not None
                           else base_worker_mb + estimated_gdal_cache_mb)
    if options.native_job_memory_limit_mb is not None:
        warnings_list_cap = ("Windows job cap reserves combined helper/merge private commit; "
                             "GDAL is included, and this is not an RSS or output-size estimate")

    memory = get_system_memory_snapshot()
    effective_reserve_mb = max(
        options.reserve_memory_mb,
        int(memory.total_physical_mb * options.reserve_memory_fraction),
    )
    physical_budget_mb = max(
        0,
        memory.available_physical_mb - effective_reserve_mb,
    )
    usable_budget_mb = physical_budget_mb
    if memory.commit_headroom_mb is not None:
        usable_budget_mb = min(
            usable_budget_mb,
            max(0, memory.commit_headroom_mb - effective_reserve_mb),
        )
    raw_memory_limit = usable_budget_mb // estimated_worker_mb
    memory_limit = max(1, int(raw_memory_limit))
    cpu_limit = max(1, os.cpu_count() or 1)
    request_limit = (
        cpu_limit if options.max_workers is None else options.max_workers
    )
    job_limit = len(normalized_maps)
    parallel_eligible = not fallback_reasons
    warnings_list = list(estimate_warnings)
    if options.native_job_memory_limit_mb is not None:
        warnings_list.append(warnings_list_cap)
    if raw_memory_limit < 1:
        warnings_list.append(
            "current memory headroom is below one estimated worker plus reserve"
        )

    selection_limits = [job_limit, cpu_limit, request_limit]
    if options.memory_policy == "enforce":
        selection_limits.append(memory_limit)
    selected_workers = max(1, min(selection_limits))
    if not parallel_eligible:
        selected_workers = 1
    if options.memory_policy == "warn" and selected_workers > memory_limit:
        warnings_list.append(
            f"requested selection {selected_workers} exceeds memory limit "
            f"{memory_limit}; memory_policy='warn' permits launch"
        )
    if options.memory_policy == "ignore":
        warnings_list.append("memory limit ignored by explicit policy")

    estimate = StoreMapResourceEstimate(
        plan_number=normalized_plan,
        hecras_version=(
            getattr(ras_obj, "ras_version", None)
            or getattr(ras_obj, "ras_version_detected", None)
        ),
        map_types=normalized_maps,
        job_count=job_limit,
        terrain=terrain_estimates,
        formula_version=("native-job-private-commit-v1" if options.native_job_memory_limit_mb is not None
                         else "float32-surface-v1"),
        estimate_source=estimate_source,
        surface_multiplier=0.0 if options.native_job_memory_limit_mb is not None else 4.0,
        fixed_overhead_mb=0 if options.native_job_memory_limit_mb is not None else 512,
        estimated_gdal_cache_mb=estimated_gdal_cache_mb,
        estimated_worker_private_mb=int(estimated_worker_mb),
        total_physical_mb=memory.total_physical_mb,
        available_physical_mb=memory.available_physical_mb,
        commit_total_mb=memory.commit_total_mb,
        commit_limit_mb=memory.commit_limit_mb,
        commit_headroom_mb=memory.commit_headroom_mb,
        effective_reserve_mb=effective_reserve_mb,
        cpu_limit=cpu_limit,
        memory_limit=memory_limit,
        request_limit=request_limit,
        job_limit=job_limit,
        selected_workers=selected_workers,
        parallel_eligible=parallel_eligible,
        fallback_reasons=tuple(fallback_reasons),
        warnings=tuple(warnings_list),
    )
    if options.native_job_memory_limit_mb is not None:
        estimate = replace(estimate,
            estimate_method="windows-job-private-commit-cap/1",
            native_job_memory_limit_mb=options.native_job_memory_limit_mb,
            native_job_memory_limit_bytes=options.native_job_memory_limit_mb * 1024**2,
            memory_measure="combined helper and merge-descendant private committed bytes; not RSS",
            source_scope={"plan_hdf": str(plan_hdf.resolve()),
                "selected_terrain": cap_terrain,
                "native_runtime": cap_runtime,
                "geometry": "complete native model geometry; no AOI or hydraulic subsetting",
                "raster_header_inventory": [str(item.path) for item in terrain_estimates],
                "source_order": "original registered terrain HDF order; no planner reordering"})
    return estimate

profile_store_maps staticmethod

Python
profile_store_maps(plan_number: str, output_path: Union[str, Path], report_path: Optional[Union[str, Path]] = None, *, map_types: Sequence[str] = ('wse', 'depth', 'velocity'), performance: Optional[StoreMapPerformanceOptions] = None, profile: str = 'Max', render_mode: Optional[str] = None, fix_georef: bool = True, ras_object=None, ras_version: Optional[str] = None, timeout: int = 7200, sample_interval_seconds: float = 0.2, include_output_signatures: bool = True) -> StoreMapProfileResult

Profile one stored-map configuration and write a JSON report.

The process-tree sampler records CPU, physical/private memory, Windows commit headroom, I/O bytes and I/O operation counts by executable. The report also captures the pre-run resource estimate and blockwise raster signatures so configurations can be compared for output equivalence.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def profile_store_maps(
    plan_number: str,
    output_path: Union[str, Path],
    report_path: Optional[Union[str, Path]] = None,
    *,
    map_types: Sequence[str] = ("wse", "depth", "velocity"),
    performance: Optional[StoreMapPerformanceOptions] = None,
    profile: str = "Max",
    render_mode: Optional[str] = None,
    fix_georef: bool = True,
    ras_object=None,
    ras_version: Optional[str] = None,
    timeout: int = 7200,
    sample_interval_seconds: float = 0.2,
    include_output_signatures: bool = True,
) -> StoreMapProfileResult:
    """Profile one stored-map configuration and write a JSON report.

    The process-tree sampler records CPU, physical/private memory, Windows
    commit headroom, I/O bytes and I/O operation counts by executable. The
    report also captures the pre-run resource estimate and blockwise raster
    signatures so configurations can be compared for output equivalence.
    """
    options = performance or StoreMapPerformanceOptions()
    if not isinstance(options, StoreMapPerformanceOptions):
        raise TypeError("performance must be a StoreMapPerformanceOptions")

    normalized_maps = tuple(
        dict.fromkeys(str(item).strip().casefold() for item in map_types)
    )
    supported = {"wse", "depth", "velocity"}
    unsupported = sorted(set(normalized_maps) - supported)
    if not normalized_maps or unsupported:
        detail = f": {', '.join(unsupported)}" if unsupported else ""
        raise ValueError(
            "profile_store_maps supports wse, depth, and velocity" + detail
        )

    output_directory = Path(os.path.abspath(output_path))
    output_directory.mkdir(parents=True, exist_ok=True)
    resolved_report = (
        Path(os.path.abspath(report_path))
        if report_path is not None
        else output_directory / "store_map_profile.json"
    )
    estimate = RasProcess.estimate_store_map_resources(
        plan_number,
        map_types=normalized_maps,
        performance=options,
        ras_object=ras_object,
    )
    ras_obj = ras_object or ras
    profile_settings = {
        "project_folder": str(RasUtils.safe_resolve(Path(ras_obj.project_folder))),
        "output_path": str(output_directory),
        "plan_number": RasUtils.normalize_ras_number(plan_number),
        "map_types": list(normalized_maps),
        "performance": options.to_dict(),
        "profile": profile,
        "render_mode": render_mode,
        "fix_georef": fix_georef,
        "ras_version": ras_version,
        "timeout": timeout,
        "sample_interval_seconds": sample_interval_seconds,
        "include_output_signatures": include_output_signatures,
    }

    profiler = ProcessTreeProfiler(
        sample_interval_seconds,
        watch_paths=(output_directory,),
    )
    profiler.start()
    started = time.perf_counter()
    try:
        generated = RasProcess.store_maps(
            plan_number=plan_number,
            output_path=output_directory,
            profile=profile,
            render_mode=render_mode,
            wse="wse" in normalized_maps,
            depth="depth" in normalized_maps,
            velocity="velocity" in normalized_maps,
            clear_existing=True,
            fix_georef=fix_georef,
            ras_object=ras_object,
            ras_version=ras_version,
            timeout=timeout,
            performance=options,
        )
    except Exception as exc:
        elapsed = time.perf_counter() - started
        profiler.stop()
        resolved_report.parent.mkdir(parents=True, exist_ok=True)
        failure_report = {
            "schema": "ras-commander.store-map-profile/1",
            "status": "failed",
            "error_type": type(exc).__name__,
            "error": str(exc),
            "elapsed_seconds": elapsed,
            "resource_estimate": estimate.to_dict(),
            "settings": profile_settings,
            "samples": [sample.to_dict() for sample in profiler.samples],
            "performance_summary": profiler.performance_summary(),
            "phase_summary": profiler.phase_summary(),
        }
        resolved_report.write_text(
            json.dumps(failure_report, indent=2, default=str),
            encoding="utf-8",
        )
        raise
    elapsed = time.perf_counter() - started
    profiler.stop()

    normalized_generated = {
        key: tuple(Path(path) for path in paths) for key, paths in generated.items()
    }
    signatures: Dict[str, Dict[str, Any]] = {}
    if include_output_signatures:
        for paths in normalized_generated.values():
            for raster_path in paths:
                if raster_path.suffix.casefold() in {".tif", ".tiff"}:
                    signatures[str(raster_path)] = (
                        RasProcess._stored_map_raster_signature(raster_path)
                    )

    counters = profiler.grouped_counters()
    result = StoreMapProfileResult(
        resource_estimate=estimate,
        settings=profile_settings,
        generated_files=normalized_generated,
        elapsed_seconds=round(elapsed, 3),
        peak_tree_rss_mb=round(profiler.peak_tree_rss_mb, 3),
        peak_tree_private_mb=(
            round(profiler.peak_tree_private_mb, 3)
            if profiler.peak_tree_private_mb is not None
            else None
        ),
        minimum_available_memory_mb=profiler.minimum_available_memory_mb,
        minimum_commit_headroom_mb=profiler.minimum_commit_headroom_mb,
        cpu_seconds_by_process={
            name: float(values["cpu_seconds"]) for name, values in counters.items()
        },
        read_bytes_by_process={
            name: int(values["read_bytes"]) for name, values in counters.items()
        },
        write_bytes_by_process={
            name: int(values["write_bytes"]) for name, values in counters.items()
        },
        read_operations_by_process={
            name: int(values["read_operations"])
            for name, values in counters.items()
        },
        write_operations_by_process={
            name: int(values["write_operations"])
            for name, values in counters.items()
        },
        maximum_simultaneous_helpers=profiler.maximum_simultaneous_helpers,
        samples=tuple(profiler.samples),
        performance_summary=profiler.performance_summary(),
        phase_summary=profiler.phase_summary(),
        output_signatures=signatures,
        report_path=resolved_report,
    )
    result.write_report()
    return result

store_benefit_area staticmethod

Python
store_benefit_area(post_plan_number: str, config: BenefitAreaConfig, *, output_path: Union[str, Path] = None, profile: str = 'Max', render_mode: str = None, terrain_name: Optional[str] = None, include_wse: Optional[bool] = None, post_depth: bool = True, post_velocity: bool = False, post_froude: bool = False, post_shear_stress: bool = False, post_depth_x_velocity: bool = False, post_depth_x_velocity_sq: bool = False, post_inundation_boundary: bool = False, post_arrival_time: bool = False, post_duration: bool = False, post_percent_inundated: bool = False, arrival_depth: float = 0.0, clear_existing: bool = True, fix_georef: bool = True, ras_object=None, ras_version: str = None, timeout: int = 600, _log_summary: bool = True) -> Dict[str, List[Path]]

Generate paired Depth maps and derive one BenefitArea product.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@_serialize_store_maps
@log_call
def store_benefit_area(
    post_plan_number: str,
    config: BenefitAreaConfig,
    *,
    output_path: Union[str, Path] = None,
    profile: str = "Max",
    render_mode: str = None,
    terrain_name: Optional[str] = None,
    include_wse: Optional[bool] = None,
    post_depth: bool = True,
    post_velocity: bool = False,
    post_froude: bool = False,
    post_shear_stress: bool = False,
    post_depth_x_velocity: bool = False,
    post_depth_x_velocity_sq: bool = False,
    post_inundation_boundary: bool = False,
    post_arrival_time: bool = False,
    post_duration: bool = False,
    post_percent_inundated: bool = False,
    arrival_depth: float = 0.0,
    clear_existing: bool = True,
    fix_georef: bool = True,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 600,
    _log_summary: bool = True,
) -> Dict[str, List[Path]]:
    """Generate paired Depth maps and derive one BenefitArea product."""

    if not isinstance(config, BenefitAreaConfig):
        raise TypeError("config must be a BenefitAreaConfig")
    if not post_depth:
        raise ValueError("Depth generation cannot be disabled for BenefitArea")

    ras_obj = ras_object or ras
    ras_obj.check_initialized()
    pre_plan = RasUtils.normalize_ras_number(config.pre_plan_number)
    post_plan = RasUtils.normalize_ras_number(post_plan_number)
    if pre_plan == post_plan:
        raise ValueError(
            "BenefitArea pre- and post-project plans must be different"
        )

    terrain_path = Path(config.terrain_tif)
    if (
        terrain_name
        and config.terrain_name
        and (terrain_name.casefold() != config.terrain_name.casefold())
    ):
        raise ValueError(
            "terrain_name conflicts with BenefitAreaConfig.terrain_name"
        )
    selected_terrain = RasProcess._resolve_benefit_terrain_name(
        ras_obj,
        terrain_path,
        terrain_name or config.terrain_name,
    )
    RasProcess._require_common_benefit_terrain_association(
        ras_obj,
        (pre_plan, post_plan),
        selected_terrain,
    )
    terrain_path = terrain_path.resolve()
    effective_wse = config.include_wse if include_wse is None else bool(include_wse)

    if output_path is None:
        root_output = (
            Path(ras_obj.project_folder)
            / "BenefitArea"
            / f"p{pre_plan}-to-p{post_plan}"
        )
    else:
        root_output = Path(output_path)
        if not root_output.is_absolute():
            root_output = Path(ras_obj.project_folder) / root_output
    root_output.mkdir(parents=True, exist_ok=True)
    pre_output = root_output / f"p{pre_plan}"
    post_output = root_output / f"p{post_plan}"

    def map_plan(
        plan_number: str,
        plan_output: Path,
        *,
        include_post_maps: bool,
    ) -> Dict[str, List[Path]]:
        project_name = getattr(ras_obj, "project_name", "")
        plan_hdf = (
            Path(ras_obj.project_folder) / f"{project_name}.p{plan_number}.hdf"
        )
        last_reason = "stored map was not produced"
        last_result: Dict[str, List[Path]] = {}
        for attempt in range(1, 4):
            result = RasProcess.store_maps(
                plan_number=plan_number,
                output_path=plan_output,
                profile=profile,
                render_mode=render_mode,
                wse=effective_wse,
                depth=True,
                velocity=post_velocity if include_post_maps else False,
                froude=post_froude if include_post_maps else False,
                shear_stress=(post_shear_stress if include_post_maps else False),
                depth_x_velocity=(
                    post_depth_x_velocity if include_post_maps else False
                ),
                depth_x_velocity_sq=(
                    post_depth_x_velocity_sq if include_post_maps else False
                ),
                inundation_boundary=(
                    post_inundation_boundary if include_post_maps else False
                ),
                arrival_time=(post_arrival_time if include_post_maps else False),
                duration=post_duration if include_post_maps else False,
                percent_inundated=(
                    post_percent_inundated if include_post_maps else False
                ),
                arrival_depth=arrival_depth,
                clear_existing=clear_existing,
                terrain_name=selected_terrain,
                benefit_area=None,
                fix_georef=fix_georef,
                ras_object=ras_obj,
                ras_version=ras_version,
                timeout=timeout,
                _log_summary=False,
            )
            last_result = result

            depth_paths = [Path(path) for path in result.get("depth", [])]
            wse_paths = [Path(path) for path in result.get("wse", [])]
            if len(depth_paths) != 1:
                last_reason = f"found {len(depth_paths)} readable Depth TIFFs"
            elif effective_wse and len(wse_paths) != 1:
                last_reason = f"found {len(wse_paths)} readable WSE TIFFs"
            elif not RasProcess._tif_has_data(
                depth_paths[0]
            ) and RasProcess._hdf_has_wet_maximum_depth(plan_hdf):
                last_reason = (
                    "Depth TIFF is all NoData while the plan HDF contains wet cells"
                )
            else:
                return result

            if attempt < 3:
                logger.warning(
                    "Retrying BenefitArea source maps for plan p%s "
                    "(attempt %d of 3): %s",
                    plan_number,
                    attempt + 1,
                    last_reason,
                )

        if "all NoData" in last_reason:
            raise RuntimeError(
                f"BenefitArea source-map generation failed for plan p{plan_number} "
                f"after 3 attempts: {last_reason}. Confirm the selected terrain "
                "is a registered single-TIFF terrain."
            )
        # Preserve the established exact-count validation and error text
        # below after giving transient mapper failures a chance to recover.
        return last_result

    pre_results = map_plan(
        pre_plan,
        pre_output,
        include_post_maps=False,
    )
    post_results = map_plan(
        post_plan,
        post_output,
        include_post_maps=True,
    )

    def require_one(
        result: Dict[str, List[Path]],
        key: str,
        plan: str,
    ) -> Path:
        paths = [Path(item) for item in result.get(key, [])]
        if len(paths) != 1:
            raise RuntimeError(
                f"BenefitArea requires exactly one {key.replace('_', ' ').title()} "
                f"GeoTIFF for plan p{plan}; found {len(paths)}. Confirm the "
                "selected terrain is a registered single-TIFF terrain."
            )
        return paths[0]

    pre_depth_path = require_one(pre_results, "depth", pre_plan)
    post_depth_path = require_one(post_results, "depth", post_plan)
    pre_wse_path: Optional[Path] = None
    post_wse_path: Optional[Path] = None
    if effective_wse:
        # Validate every requested source map before publishing the derived
        # product so a partial WSE run cannot leave a successful-looking
        # BenefitArea raster behind.
        pre_wse_path = require_one(pre_results, "wse", pre_plan)
        post_wse_path = require_one(post_results, "wse", post_plan)
    safe_profile = profile.replace(":", " ").replace("/", "_")
    benefit_path = root_output / (
        f"Benefit Area ({safe_profile}).p{pre_plan}-to-p{post_plan}.tif"
    )

    polygon_output = config.polygon_output
    if polygon_output is True:
        polygon_output = benefit_path.with_suffix(".gpkg")
    elif polygon_output:
        polygon_output = Path(polygon_output)
        if not polygon_output.is_absolute():
            polygon_output = root_output / polygon_output

    benefit_result = RasBenefits.create_benefit_area(
        pre_depth_path,
        post_depth_path,
        terrain_path,
        benefit_path,
        flood_min_depth=config.flood_min_depth,
        benefit_min_depth=config.benefit_min_depth,
        minimum_region_pixels=config.minimum_region_pixels,
        analysis_boundary=config.analysis_boundary,
        improvement_boundary=config.improvement_boundary,
        polygon_output=polygon_output,
        polygon_simplify_tolerance=config.polygon_simplify_tolerance,
    )

    generated: Dict[str, List[Path]] = {
        key: [Path(path) for path in paths] for key, paths in post_results.items()
    }
    generated["benefit_source_pre_depth"] = [pre_depth_path]
    generated["benefit_source_post_depth"] = [post_depth_path]
    if effective_wse:
        generated["benefit_source_pre_wse"] = [pre_wse_path]
        generated["benefit_source_post_wse"] = [post_wse_path]
    generated["benefit_area"] = [benefit_result.raster_path]
    if benefit_result.polygon_path is not None:
        generated["benefit_area_polygon"] = [benefit_result.polygon_path]

    if _log_summary:
        logger.info(
            "BenefitArea stored-map workflow complete: pre=p%s; post=p%s; "
            "wse=%s; filter=%s; polygon=%s",
            pre_plan,
            post_plan,
            effective_wse,
            config.minimum_region_pixels,
            benefit_result.polygon_path is not None,
        )
    return generated

store_maps staticmethod

Python
store_maps(plan_number: str, output_folder: str = None, output_path: Union[str, Path] = None, profile: str = 'Max', render_mode: str = None, wse: Optional[bool] = None, depth: Optional[bool] = None, velocity: Optional[bool] = None, froude: bool = False, shear_stress: bool = False, depth_x_velocity: bool = False, depth_x_velocity_sq: bool = False, inundation_boundary: bool = False, arrival_time: bool = False, duration: bool = False, percent_inundated: bool = False, arrival_depth: float = 0.0, clear_existing: bool = True, fix_georef: bool = True, ras_object=None, ras_version: str = None, timeout: int = 600, _log_summary: bool = True, terrain_name: Optional[str] = None, benefit_area: Optional[BenefitAreaConfig] = None, *, performance: Optional[StoreMapPerformanceOptions] = None, max_workers: Any = _PERFORMANCE_UNSET, memory_per_worker_mb: Any = _PERFORMANCE_UNSET, reserve_memory_mb: Any = _PERFORMANCE_UNSET) -> Dict[str, List[Path]]

Generate stored maps for a plan using RasStoreMapHelper.exe.

This method: 1. Configures stored maps in the .rasmap file 2. Runs the packaged mapper helper and HEC-RAS mapping libraries 3. Optionally fixes georeferencing on output TIFs

Works on both Windows (native) and Linux (via Wine, auto-detected).

Output Path Behavior

The compatible single-worker path runs StoreAllMaps in <project_folder>/<Plan ShortID>/. The parallel path uses the packaged helper's headless StoreMap implementation with unique output bases in that same folder. When output_path is supplied, this method moves only files created or changed by the current call to the requested directory. The helper initializes terrain SRS state explicitly, avoiding the raw RasProcess.exe StoreMap SetProjectionInfo() failure on multi-terrain projects.

Parameters:

Name Type Description Default
plan_number str

Plan number (e.g., "01", "06")

required
output_folder str

Output folder name used in .rasmap StoredFilename paths (default: plan name from rasmap). This does NOT control where the HEC-RAS mapping command writes files — see output_path.

None
output_path Union[str, Path]

Custom output directory for generated rasters (str or Path). If provided, StoreAllMaps runs to the default Plan ShortID folder, then files are moved to this directory. Accepts relative or absolute paths — relative paths are resolved against the project folder. If None (default), files remain in <project_folder>/<Plan ShortID>/.

None
profile str

Profile to map - "Max", "Min", or specific timestamp string

'Max'
render_mode str

Water surface rendering mode to set before generating maps. Options: "horizontal", "sloping", "slopingPretty". For slopingPretty, flags can be given as "slopingPretty::" (for example "slopingPretty:true:true" for depth-weighted faces) or as a dict with mode, reduce_shallow_to_horizontal and use_depth_weighted_faces. The flags are written to the .rasmap. If None (default), uses whatever mode is already in the .rasmap.

None
wse Optional[bool]

Generate Water Surface Elevation map. Defaults to True for ordinary stored-map generation and False for BenefitArea unless BenefitAreaConfig.include_wse is True.

None
depth Optional[bool]

Generate Depth map (default: True). BenefitArea always requires Depth and rejects False.

None
velocity Optional[bool]

Generate Velocity map. Defaults to True for ordinary stored-map generation and False for BenefitArea.

None
froude bool

Generate Froude number map (default: False)

False
shear_stress bool

Generate Shear Stress map (default: False)

False
depth_x_velocity bool

Generate D*V hazard map (default: False)

False
depth_x_velocity_sq bool

Generate D*V² impact map (default: False)

False
inundation_boundary bool

Generate RAS Mapper's native Inundation Boundary stored polygon at the zero-depth contour (default: False). Uses MapType="depth", OutputMode="Stored Polygon Specified Depth" and ContourPolygonValue=0, not a raster polygonization step. Returned under inundation_boundary as SHP paths; companion SHX/DBF/PRJ files are moved with them when output_path is given. Missing, empty or incomplete boundaries are omitted with a warning. Boundary-only calls can request native_polygon_serial=True in performance to verify the native serial polygon loop. This is separate from CPU affinity and does not assert parity.

False
arrival_time bool

Generate flood Arrival Time map in hours (default: False). Whole-simulation product; ignores the profile argument.

False
duration bool

Generate inundation Duration map in hours (default: False). Whole-simulation product; ignores the profile argument.

False
percent_inundated bool

Generate Percent Time Inundated map (default: False). Whole-simulation product; ignores the profile argument.

False
arrival_depth float

Wet/dry depth threshold (model vertical units) for arrival_time / duration / percent_inundated maps (default: 0.0). Appears in output filenames, e.g. "Arrival Time (0.1ft hrs)".

0.0
terrain_name Optional[str]

Registered RAS Mapper terrain to select exclusively while generating maps. BenefitArea requires this terrain to resolve to the single GeoTIFF in its configuration.

None
benefit_area Optional[BenefitAreaConfig]

Optional BenefitArea configuration. When provided, plan_number is the post-project plan and the configured pre-project plan is mapped separately before the categorical BenefitArea raster is calculated.

None
clear_existing bool

Clear existing stored maps before adding new ones (default: True)

True
fix_georef bool

Apply georeferencing fix to output TIFs (default: True)

True
ras_object RasPrj

Optional RAS object instance

None
ras_version str

Optional specific HEC-RAS mapping-runtime version

None
timeout int

Command timeout in seconds (default: 600)

600
performance Optional[StoreMapPerformanceOptions]

Keyword-only StoreMap execution and resource policy. The default preserves serial StoreAllMaps behavior. Use StoreMapPerformanceOptions(max_workers=None) for automatic memory- and CPU-bounded map-level parallelism. An explicit native_job_memory_limit_mb requires a serial boundary-only native Windows request and a verified runtime. It caps combined helper/merge private commit, with no unbounded retry.

None
max_workers Any

Deprecated keyword-only worker-count migration alias.

_PERFORMANCE_UNSET
memory_per_worker_mb Any

Deprecated keyword-only per-worker memory alias.

_PERFORMANCE_UNSET
reserve_memory_mb Any

Deprecated keyword-only reserved-memory alias. Do not combine them with performance.

_PERFORMANCE_UNSET

Returns:

Type Description
Dict[str, List[Path]]

Dict mapping map type names to lists of generated file paths.

Dict[str, List[Path]]

Paths point to output_path if specified (files are moved

Dict[str, List[Path]]

there after generation), otherwise to the default Plan ShortID

Dict[str, List[Path]]

folder.

Raises:

Type Description
FileNotFoundError

If the mapper helper or required files are not found

RuntimeError

If the HEC-RAS mapping command fails

Example

Default output (writes to ./PlanShortID/)

results = RasProcess.store_maps( ... plan_number="01", ... profile="Max", ... wse=True, ... depth=True ... )

Custom output path

results = RasProcess.store_maps( ... plan_number="01", ... output_path="C:/MyProject/CustomMaps", ... profile="Max", ... wse=True, ... depth=True, ... velocity=True ... ) print(results['wse']) [Path('C:/MyProject/CustomMaps/WSE (Max).Terrain.tif')]

Automatically use safe map-level process parallelism

results = RasProcess.store_maps( ... plan_number="01", ... performance=StoreMapPerformanceOptions(max_workers=None), ... )

Source code in ras_commander/RasProcess.py
Python
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
@staticmethod
@_serialize_store_maps
@log_call
def store_maps(
    plan_number: str,
    output_folder: str = None,
    output_path: Union[str, Path] = None,
    profile: str = "Max",
    render_mode: str = None,
    wse: Optional[bool] = None,
    depth: Optional[bool] = None,
    velocity: Optional[bool] = None,
    froude: bool = False,
    shear_stress: bool = False,
    depth_x_velocity: bool = False,
    depth_x_velocity_sq: bool = False,
    inundation_boundary: bool = False,
    arrival_time: bool = False,
    duration: bool = False,
    percent_inundated: bool = False,
    arrival_depth: float = 0.0,
    clear_existing: bool = True,
    fix_georef: bool = True,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 600,
    _log_summary: bool = True,
    terrain_name: Optional[str] = None,
    benefit_area: Optional[BenefitAreaConfig] = None,
    *,
    performance: Optional[StoreMapPerformanceOptions] = None,
    max_workers: Any = _PERFORMANCE_UNSET,
    memory_per_worker_mb: Any = _PERFORMANCE_UNSET,
    reserve_memory_mb: Any = _PERFORMANCE_UNSET,
) -> Dict[str, List[Path]]:
    """
    Generate stored maps for a plan using RasStoreMapHelper.exe.

    This method:
    1. Configures stored maps in the .rasmap file
    2. Runs the packaged mapper helper and HEC-RAS mapping libraries
    3. Optionally fixes georeferencing on output TIFs

    Works on both Windows (native) and Linux (via Wine, auto-detected).

    Output Path Behavior:
        The compatible single-worker path runs ``StoreAllMaps`` in
        ``<project_folder>/<Plan ShortID>/``. The parallel path uses the
        packaged helper's headless ``StoreMap`` implementation with unique
        output bases in that same folder. When ``output_path`` is supplied,
        this method moves only files created or changed by the current call
        to the requested directory. The helper initializes terrain SRS
        state explicitly, avoiding the raw RasProcess.exe ``StoreMap``
        ``SetProjectionInfo()`` failure on multi-terrain projects.

    Args:
        plan_number: Plan number (e.g., "01", "06")
        output_folder: Output folder name used in .rasmap StoredFilename
            paths (default: plan name from rasmap). This does NOT control
            where the HEC-RAS mapping command writes files — see output_path.
        output_path: Custom output directory for generated rasters (str
            or Path). If provided, ``StoreAllMaps`` runs to the default
            Plan ShortID folder, then files are moved to this directory.
            Accepts relative or absolute paths — relative paths are
            resolved against the project folder. If None (default),
            files remain in ``<project_folder>/<Plan ShortID>/``.
        profile: Profile to map - "Max", "Min", or specific timestamp string
        render_mode: Water surface rendering mode to set before generating
            maps. Options: "horizontal", "sloping", "slopingPretty".
            For slopingPretty, flags can be given as
            "slopingPretty:<reduce_shallow>:<depth_weighted>" (for example
            "slopingPretty:true:true" for depth-weighted faces) or as a dict
            with ``mode``, ``reduce_shallow_to_horizontal`` and
            ``use_depth_weighted_faces``. The flags are written to the
            .rasmap. If None (default), uses whatever mode is already in
            the .rasmap.
        wse: Generate Water Surface Elevation map. Defaults to True for
            ordinary stored-map generation and False for BenefitArea unless
            ``BenefitAreaConfig.include_wse`` is True.
        depth: Generate Depth map (default: True). BenefitArea always
            requires Depth and rejects False.
        velocity: Generate Velocity map. Defaults to True for ordinary
            stored-map generation and False for BenefitArea.
        froude: Generate Froude number map (default: False)
        shear_stress: Generate Shear Stress map (default: False)
        depth_x_velocity: Generate D*V hazard map (default: False)
        depth_x_velocity_sq: Generate D*V² impact map (default: False)
        inundation_boundary: Generate RAS Mapper's native Inundation Boundary
            stored polygon at the zero-depth contour (default: False).
            Uses MapType="depth", OutputMode="Stored Polygon Specified Depth"
            and ContourPolygonValue=0, not a raster polygonization step.
            Returned under ``inundation_boundary`` as SHP paths; companion
            SHX/DBF/PRJ files are moved with them when output_path is given.
            Missing, empty or incomplete boundaries are omitted with a warning.
            Boundary-only calls can request ``native_polygon_serial=True``
            in ``performance`` to verify the native serial polygon loop.
            This is separate from CPU affinity and does not assert parity.
        arrival_time: Generate flood Arrival Time map in hours (default: False).
            Whole-simulation product; ignores the ``profile`` argument.
        duration: Generate inundation Duration map in hours (default: False).
            Whole-simulation product; ignores the ``profile`` argument.
        percent_inundated: Generate Percent Time Inundated map (default: False).
            Whole-simulation product; ignores the ``profile`` argument.
        arrival_depth: Wet/dry depth threshold (model vertical units) for
            arrival_time / duration / percent_inundated maps (default: 0.0).
            Appears in output filenames, e.g. "Arrival Time (0.1ft hrs)".
        terrain_name: Registered RAS Mapper terrain to select exclusively
            while generating maps. BenefitArea requires this terrain to
            resolve to the single GeoTIFF in its configuration.
        benefit_area: Optional BenefitArea configuration. When provided,
            ``plan_number`` is the post-project plan and the configured
            pre-project plan is mapped separately before the categorical
            BenefitArea raster is calculated.
        clear_existing: Clear existing stored maps before adding new ones (default: True)
        fix_georef: Apply georeferencing fix to output TIFs (default: True)
        ras_object (RasPrj, optional): Optional RAS object instance
        ras_version: Optional specific HEC-RAS mapping-runtime version
        timeout: Command timeout in seconds (default: 600)
        performance: Keyword-only StoreMap execution and resource policy.
            The default preserves serial StoreAllMaps behavior. Use
            ``StoreMapPerformanceOptions(max_workers=None)`` for automatic
            memory- and CPU-bounded map-level parallelism.
            An explicit ``native_job_memory_limit_mb`` requires a serial
            boundary-only native Windows request and a verified runtime.
            It caps combined helper/merge private commit, with no unbounded retry.
        max_workers: Deprecated keyword-only worker-count migration alias.
        memory_per_worker_mb: Deprecated keyword-only per-worker memory alias.
        reserve_memory_mb: Deprecated keyword-only reserved-memory alias. Do not combine them with
            ``performance``.

    Returns:
        Dict mapping map type names to lists of generated file paths.
        Paths point to ``output_path`` if specified (files are moved
        there after generation), otherwise to the default Plan ShortID
        folder.

    Raises:
        FileNotFoundError: If the mapper helper or required files are not found
        RuntimeError: If the HEC-RAS mapping command fails

    Example:
        >>> # Default output (writes to ./PlanShortID/)
        >>> results = RasProcess.store_maps(
        ...     plan_number="01",
        ...     profile="Max",
        ...     wse=True,
        ...     depth=True
        ... )

        >>> # Custom output path
        >>> results = RasProcess.store_maps(
        ...     plan_number="01",
        ...     output_path="C:/MyProject/CustomMaps",
        ...     profile="Max",
        ...     wse=True,
        ...     depth=True,
        ...     velocity=True
        ... )
        >>> print(results['wse'])
        [Path('C:/MyProject/CustomMaps/WSE (Max).Terrain.tif')]

        >>> # Automatically use safe map-level process parallelism
        >>> results = RasProcess.store_maps(
        ...     plan_number="01",
        ...     performance=StoreMapPerformanceOptions(max_workers=None),
        ... )
    """
    # HISTORY: Prior to 2026-03-24, this used RasProcess.exe StoreAllMaps
    # which ignores RenderMode in HEC-RAS 6.x. Now uses RasStoreMapHelper.exe
    # which sets SharedData render mode via .NET reflection before executing
    # StoreAllMapsCommand, producing pixel-perfect output.

    performance_options, performance_was_explicit = (
        _coerce_store_map_performance_options(
            performance,
            max_workers=max_workers,
            memory_per_worker_mb=memory_per_worker_mb,
            reserve_memory_mb=reserve_memory_mb,
        )
    )
    max_workers = performance_options.max_workers
    memory_per_worker_mb = performance_options.minimum_worker_memory_mb
    reserve_memory_mb = performance_options.reserve_memory_mb

    if benefit_area is not None:
        if not isinstance(benefit_area, BenefitAreaConfig):
            raise TypeError("benefit_area must be a BenefitAreaConfig")
        if depth is False:
            raise ValueError("Depth generation cannot be disabled for BenefitArea")
        if output_folder is not None:
            raise ValueError(
                "output_folder is not supported for BenefitArea because two plans "
                "are mapped separately; use output_path for the comparison root"
            )
        if (
            performance_was_explicit
            and performance_options != StoreMapPerformanceOptions()
        ):
            raise ValueError(
                "Non-default StoreMap performance options are not supported "
                "for BenefitArea mapping"
            )

        effective_wse = benefit_area.include_wse if wse is None else bool(wse)
        return RasProcess.store_benefit_area(
            post_plan_number=plan_number,
            config=benefit_area,
            output_path=output_path,
            profile=profile,
            render_mode=render_mode,
            terrain_name=terrain_name,
            include_wse=effective_wse,
            post_depth=True,
            post_velocity=False if velocity is None else bool(velocity),
            post_froude=froude,
            post_shear_stress=shear_stress,
            post_depth_x_velocity=depth_x_velocity,
            post_depth_x_velocity_sq=depth_x_velocity_sq,
            post_inundation_boundary=inundation_boundary,
            post_arrival_time=arrival_time,
            post_duration=duration,
            post_percent_inundated=percent_inundated,
            arrival_depth=arrival_depth,
            clear_existing=clear_existing,
            fix_georef=fix_georef,
            ras_object=ras_object,
            ras_version=ras_version,
            timeout=timeout,
            _log_summary=_log_summary,
        )

    # RasMapperLib's stored-map commands are not reliable when multiple
    # Wine-hosted CLR helpers execute concurrently.  The helper launcher
    # also constrains each child to one CPU, which removes a second Wine
    # scheduling failure mode observed even for a single helper.  Preserve
    # process parallelism on native Windows, but make Wine explicitly and
    # predictably serial until that runtime is qualified for concurrency.
    wine_serial_runtime = _is_wine_helper_runtime()
    if wine_serial_runtime and max_workers != 1:
        warnings.warn(
            "Stored-map processing under Wine is serialized because "
            "concurrent RasMapperLib helper processes are not qualified; "
            "the requested max_workers setting has been capped at 1.",
            RuntimeWarning,
            stacklevel=2,
        )
        logger.warning(
            "Capping Wine stored-map processing from max_workers=%s to 1",
            "auto" if max_workers is None else max_workers,
        )
        performance_options = replace(performance_options, max_workers=1)
        max_workers = 1
    if wine_serial_runtime and performance_was_explicit:
        logger.info(
            "Wine aggregate StoreAllMaps does not use the independent-helper "
            "memory admission model"
        )

    # Preserve the long-standing ordinary StoreMaps defaults while allowing
    # BenefitArea to use a cheaper Depth-only default above.
    wse = True if wse is None else bool(wse)
    depth = True if depth is None else bool(depth)
    velocity = True if velocity is None else bool(velocity)

    serial_polygon = performance_options.native_polygon_serial
    if serial_polygon:
        if not inundation_boundary or any((wse, depth, velocity, froude,
                shear_stress, depth_x_velocity, depth_x_velocity_sq,
                arrival_time, duration, percent_inundated)):
            raise ValueError(
                "native_polygon_serial requires an inundation-boundary-only "
                "request; disable all raster and whole-simulation products"
            )
        if max_workers != 1:
            raise ValueError("native_polygon_serial requires max_workers=1")
        if wine_serial_runtime:
            raise ValueError("native_polygon_serial is not qualified under Wine")
    _validate_native_job_cap_route(performance_options, ("inundation_boundary",),
                                   wine_runtime=wine_serial_runtime)

    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    serial_polygon_terrain = None
    if serial_polygon:
        layers = RasMap.list_terrain_layers(ras_obj.project_folder, ras_object=ras_obj)
        selected = layers if terrain_name is None else layers.loc[layers["name"] == terrain_name]
        if len(selected) != 1:
            raise ValueError("native_polygon_serial requires exactly one selected registered terrain")
        serial_polygon_terrain = Path(selected.iloc[0]["resolved_path"]).resolve(strict=True)

    # Locate HEC-RAS directory
    hecras_dir = Path(str(ras_obj.ras_exe_path)).parent
    if not hecras_dir.exists():
        raise FileNotFoundError(f"HEC-RAS directory not found: {hecras_dir}")

    # Get paths
    plan_num = RasUtils.normalize_ras_number(plan_number)
    rasmap_path = RasMap.get_rasmap_path(ras_obj)
    if rasmap_path is None:
        raise FileNotFoundError("No .rasmap file found in project folder")

    plan_hdf = f"{ras_obj.project_name}.p{plan_num}.hdf"
    plan_hdf_path = ras_obj.project_folder / plan_hdf

    if not plan_hdf_path.exists():
        raise FileNotFoundError(f"Plan HDF not found: {plan_hdf_path}")

    serial_steady_profiles = None
    if serial_polygon:
        from .hdf.HdfResultsPlan import HdfResultsPlan
        if HdfResultsPlan.is_steady_plan(plan_hdf_path):
            serial_steady_profiles = HdfResultsPlan.get_steady_profile_names(plan_hdf_path)
            if serial_steady_profiles.count(profile) != 1:
                raise ValueError("Serial steady boundaries require an exact, unambiguous stored profile name")

    job_cap_preflight = None
    if performance_options.native_job_memory_limit_mb is not None:
        from ._native_helper import validate_native_job_memory_runtime
        cap_runtime = validate_native_job_memory_runtime(hecras_dir)
        job_cap_preflight = _preflight_native_job_cap(performance_options.native_job_memory_limit_mb)
        job_cap_preflight = dict(job_cap_preflight, native_runtime=cap_runtime)
        logger.debug("Native boundary job-cap preflight: %s", json.dumps(job_cap_preflight))

    # RasProcess.exe uses the Plan ShortID from HDF to determine output folder name
    # This is the authoritative source - rasmap Layer Name should match but isn't used by RasProcess
    plan_short_id = RasProcess._get_plan_short_id(plan_hdf_path)

    # Get the output folder from rasmap Layer Name (should match Plan ShortID)
    tree = ET.parse(_windows_extended_length_path(rasmap_path))
    root = tree.getroot()
    output_folder_from_rasmap = None
    plan_basename = Path(plan_hdf).name.lower()
    for layer in root.findall(".//Results/Layer"):
        filename = layer.get("Filename", "")
        if Path(filename).name.lower() == plan_basename:
            output_folder_from_rasmap = layer.get("Name")
            break

    # Determine output folder - priority: Plan ShortID > rasmap Layer Name > user-provided > default
    if plan_short_id:
        actual_output_folder = plan_short_id
    elif output_folder_from_rasmap:
        actual_output_folder = output_folder_from_rasmap
    elif output_folder:
        actual_output_folder = output_folder
    else:
        actual_output_folder = f"Plan_{plan_num}"

    # Use actual output folder for the StoredFilename paths in rasmap
    if output_folder is None:
        output_folder = actual_output_folder

    output_dir = ras_obj.project_folder / actual_output_folder
    os.makedirs(_windows_extended_length_path(output_dir), exist_ok=True)

    logger.debug(f"Plan ShortID from HDF: {plan_short_id}")
    logger.debug(f"Output folder from rasmap: {output_folder_from_rasmap}")
    logger.debug(f"Actual output directory: {output_dir}")

    # Determine profile index
    if serial_steady_profiles is not None:
        profile_index = serial_steady_profiles.index(profile)
        profile_name = profile
    elif profile.upper() in ("MAX", "MIN"):
        profile_index = 2147483647 if profile.upper() == "MAX" else -2147483648
        profile_name = profile.title()  # "Max" or "Min"
    else:
        # Specific timestamp - need to find index
        timestamps = RasProcess.get_plan_timestamps(plan_num, ras_obj)
        try:
            profile_index = timestamps.index(profile)
            profile_name = profile
        except ValueError:
            if serial_polygon:
                raise ValueError(f"Serial boundary timestamp is not a stored profile: {profile!r}") from None
            logger.warning(
                f"Timestamp '{profile}' not found. Available: {timestamps[:5]}..."
            )
            profile_index = 2147483647
            profile_name = "Max"

    # Backup rasmap
    rasmap_backup = rasmap_path.with_name(
        f"{rasmap_path.name}.{os.getpid()}.{uuid.uuid4().hex}.bak"
    )
    shutil.copy2(
        _windows_extended_length_path(rasmap_path),
        _windows_extended_length_path(rasmap_backup),
    )

    try:
        if terrain_name is not None:
            RasProcess._select_terrain_for_mapping(
                rasmap_path,
                terrain_name,
                ras_object=ras_obj,
            )

        # Set render mode if requested (before modifying stored maps)
        if render_mode is not None:
            RasProcess._set_rasmap_render_mode(render_mode, ras_obj)
            logger.debug(f"Set render mode to '{render_mode}' before StoreAllMaps")

        # Clear existing stored maps if requested
        if clear_existing:
            RasProcess._remove_stored_maps_from_rasmap(rasmap_path, plan_hdf)

        # Build list of maps to generate
        maps_to_add = []
        if wse:
            maps_to_add.append(("elevation", "wse"))
        if depth:
            maps_to_add.append(("depth", "depth"))
        if velocity:
            maps_to_add.append(("velocity", "velocity"))
        if froude:
            maps_to_add.append(("froude", "froude"))
        if shear_stress:
            maps_to_add.append(("Shear", "shear_stress"))
        if depth_x_velocity:
            maps_to_add.append(("depth and velocity", "depth_x_velocity"))
        if depth_x_velocity_sq:
            maps_to_add.append(
                ("depth and velocity squared", "depth_x_velocity_sq")
            )

        # Whole-simulation map types: always Max profile, labeled by the
        # ArrivalDepth threshold (e.g. "Arrival Time (0.1ft hrs)") rather
        # than the profile name. XML names come from MAP_TYPES — the
        # single source of truth for RasMapperLib name strings.
        adr_flags = {
            "arrival_time": arrival_time,
            "duration": duration,
            "percent_inundated": percent_inundated,
        }
        adr_maps_to_add = [
            (RasProcess.MAP_TYPES[key][0], key)
            for key, enabled in adr_flags.items()
            if enabled
        ]

        # Add stored maps to rasmap
        for map_type, _ in maps_to_add:
            RasProcess._add_stored_map_to_rasmap(
                rasmap_path,
                plan_hdf,
                map_type,
                profile_name,
                output_folder,
                profile_index,
            )

        for map_type, _ in adr_maps_to_add:
            RasProcess._add_stored_map_to_rasmap(
                rasmap_path,
                plan_hdf,
                map_type,
                "Max",
                output_folder,
                2147483647,
                extra_attrs={"ArrivalDepth": str(arrival_depth)},
            )

        # Add inundation boundary if requested (shapefile polygon output)
        if inundation_boundary:
            configured = RasProcess._add_stored_map_to_rasmap(
                rasmap_path,
                plan_hdf,
                "depth",
                profile_name,
                output_folder,
                profile_index,
                output_mode="Stored Polygon Specified Depth",
                extra_attrs={"ContourPolygonValue": "0"},
                display_name="Inundation Boundary",
            )
            if not configured:
                raise RuntimeError("Could not configure native inundation boundary")

        # Resolve output_path to absolute if provided
        resolved_output_path = None
        if output_path is not None:
            resolved_output_path = Path(output_path)
            if not resolved_output_path.is_absolute():
                resolved_output_path = RasUtils.safe_resolve(
                    ras_obj.project_folder / resolved_output_path
                )
            os.makedirs(
                _windows_extended_length_path(resolved_output_path),
                exist_ok=True,
            )

        # Snapshot pre-existing files in output_dir so we only move files
        # that were created or changed by this StoreAllMaps call when
        # output_path is specified. This preserves unrelated benchmark or
        # manually curated files while still relocating regenerated rasters
        # that overwrite the same filenames on reruns.
        pre_existing_files = {}
        if os.path.isdir(_windows_extended_length_path(output_dir)):
            for item in _iterdir_paths(output_dir):
                try:
                    stat = os.stat(_windows_extended_length_path(item))
                except FileNotFoundError:
                    continue
                pre_existing_files[item.name] = (
                    stat.st_mtime_ns,
                    stat.st_size,
                )

        # Use RasStoreMapHelper.exe instead of RasProcess.exe.
        # RasStoreMapHelper sets SharedData render mode via .NET reflection
        # before calling StoreAllMapsCommand.Execute(), fixing the 6.x bug
        # where RasProcess.exe ignores the RenderMode from the .rasmap.

        current_mode = render_mode
        if current_mode is None:
            current_mode = RasMap.get_water_surface_render_mode(
                ras_object=ras_obj,
            )

        helper_mode = normalize_store_map_render_mode(current_mode)

        effective_ras_version = ras_version or getattr(
            ras_obj,
            "ras_version",
            None,
        )

        parallel_requested = max_workers is None or max_workers > 1
        unsupported_parallel_features = []
        if adr_maps_to_add:
            unsupported_parallel_features.append("arrival/duration products")
        if inundation_boundary:
            unsupported_parallel_features.append("inundation boundary")
        if terrain_name is not None:
            unsupported_parallel_features.append("explicit terrain selection")
        unsupported_map_types = [
            map_type
            for map_type, _ in maps_to_add
            if map_type not in _STORE_MAP_HELPER_TYPES
        ]
        if unsupported_map_types:
            unsupported_parallel_features.append(
                "map types " + ", ".join(unsupported_map_types)
            )

        if parallel_requested and unsupported_parallel_features:
            if max_workers is None:
                logger.info(
                    "StoreMap auto parallelism selected the ordered serial path "
                    "because this request includes: %s",
                    ", ".join(unsupported_parallel_features),
                )
                parallel_requested = False
            else:
                raise ValueError(
                    "StoreMap process parallelism is unavailable for: "
                    + ", ".join(unsupported_parallel_features)
                    + ". Use max_workers=1 or remove the incompatible products."
                )

        worker_count = 1
        resource_estimate = None
        # This terrain-sized estimate describes each independent StoreMap
        # helper.  Wine uses the aggregate StoreAllMaps command, so applying
        # that parallel-helper model to its serial path creates false
        # admission failures on otherwise qualified hosts.
        if performance_was_explicit and not wine_serial_runtime:
            resource_map_types = [map_key for _, map_key in maps_to_add]
            resource_map_types.extend(
                map_key for _, map_key in adr_maps_to_add
            )
            if inundation_boundary:
                resource_map_types.append("inundation_boundary")
            resource_estimate = RasProcess.estimate_store_map_resources(
                plan_num,
                map_types=resource_map_types,
                terrain_name=terrain_name,
                performance=performance_options,
                ras_object=ras_obj,
            )
            if job_cap_preflight is not None:
                resource_estimate = replace(resource_estimate, native_job_preflight=job_cap_preflight)
                logger.debug("Native boundary job-cap admission plan: %s",
                             json.dumps(resource_estimate.to_dict(), default=str))

        if parallel_requested and len(maps_to_add) > 1:
            if resource_estimate is None:
                raise RuntimeError(
                    "StoreMap parallelism requires a resource estimate"
                )
            worker_count = resource_estimate.selected_workers
            logger.debug(
                "StoreMap worker selection: requested=%s; selected=%d; "
                "jobs=%d; memory_floor_mb=%d; estimated_memory_mb=%d; "
                "reserve_memory_mb=%d; memory_limit=%d; policy=%s",
                "auto" if max_workers is None else max_workers,
                worker_count,
                len(maps_to_add),
                memory_per_worker_mb,
                resource_estimate.estimated_worker_private_mb,
                resource_estimate.effective_reserve_mb,
                resource_estimate.memory_limit,
                performance_options.memory_policy,
            )

        with RasProcess._mapper_compatible_result_hdf(
            plan_hdf_path,
            effective_ras_version,
        ) as mapper_hdf_path:
            if worker_count > 1:
                logger.info(
                    "Generating %d stored-map types with %d helper processes",
                    len(maps_to_add),
                    worker_count,
                )
                safe_profile = profile_name.replace(":", " ").replace("/", "_")
                jobs = []
                for map_type, map_key in maps_to_add:
                    display_name = RasProcess.MAP_TYPES[map_key][1]
                    jobs.append(
                        (
                            map_key,
                            _STORE_MAP_HELPER_TYPES[map_type],
                            output_dir / f"{display_name} ({safe_profile})",
                        )
                    )

                def run_job(map_key, helper_map_type, output_base):
                    return run_store_map_helper(
                        hecras_dir=hecras_dir,
                        render_mode=helper_mode,
                        map_type=helper_map_type,
                        result_hdf_path=mapper_hdf_path,
                        profile_name=profile_name,
                        output_base_path=output_base,
                        timeout=timeout,
                        working_dir=ras_obj.project_folder,
                        gdal_num_threads=(
                            performance_options.gdal_num_threads_per_helper
                        ),
                        gdal_cachemax_mb=performance_options.gdal_cachemax_mb,
                        native_cpu_limit=performance_options.native_cpu_limit,
                    )

                helper_results = _run_memory_admitted_store_map_jobs(
                    jobs=jobs,
                    worker_count=worker_count,
                    performance=performance_options,
                    estimate=resource_estimate,
                    runner=run_job,
                )

                failures = []
                for map_key, result in helper_results.items():
                    logger.debug(
                        "StoreMap %s stdout: %s",
                        map_key,
                        result.stdout,
                    )
                    if result.stderr:
                        stderr_lines = result.stderr.splitlines()
                        stderr_preview = (
                            stderr_lines[0] if stderr_lines else result.stderr[:200]
                        )
                        logger.warning(
                            "StoreMap %s reported stderr: %s",
                            map_key,
                            stderr_preview,
                        )
                        logger.debug(
                            "StoreMap %s full stderr: %s",
                            map_key,
                            result.stderr,
                        )
                    if result.returncode != 0:
                        stderr_detail = next(
                            (
                                line.strip()
                                for line in result.stderr.splitlines()
                                if line.strip()
                            ),
                            "",
                        )
                        failures.append(
                            (
                                map_key,
                                result.returncode,
                                stderr_detail[:500],
                            )
                        )

                if failures:
                    failure_text = "; ".join(
                        f"{map_key} exit {returncode}"
                        + (f": {detail}" if detail else "")
                        for map_key, returncode, detail in failures
                    )
                    raise RuntimeError(
                        f"Parallel StoreMap failed for plan {plan_num}: "
                        f"{failure_text}"
                    )
            else:
                if resource_estimate is not None:
                    _wait_for_store_map_admission(
                        resource_estimate,
                        performance_options,
                    )
                logger.debug(
                    "Running StoreAllMaps for plan %s (mode=%s)",
                    plan_num,
                    helper_mode,
                )
                if serial_polygon:
                    safe_profile = profile_name.replace(":", " ").replace("/", "_")
                    result = run_store_map_helper(
                        hecras_dir=hecras_dir,
                        render_mode=helper_mode,
                        map_type="ProfileMap:depth",
                        result_hdf_path=mapper_hdf_path,
                        profile_name=profile_name,
                        output_base_path=output_dir / f"Inundation Boundary ({safe_profile})",
                        terrain_hdf_path=serial_polygon_terrain,
                        native_polygon_serial=True,
                        timeout=timeout,
                        working_dir=ras_obj.project_folder,
                        gdal_num_threads=performance_options.gdal_num_threads_per_helper,
                        gdal_cachemax_mb=performance_options.gdal_cachemax_mb,
                        native_cpu_limit=performance_options.native_cpu_limit,
                        **({"native_job_memory_limit_mb": performance_options.native_job_memory_limit_mb}
                           if performance_options.native_job_memory_limit_mb is not None else {}),
                    )
                    if result.returncode == 0 and "NATIVE_POLYGON_SERIAL_EFFECTIVE=True" not in result.stdout.splitlines():
                        raise RuntimeError("Native helper did not verify serial polygon execution")
                    if (result.returncode == 0 and performance_options.native_job_memory_limit_mb is not None
                            and f"NATIVE_JOB_MEMORY_LIMIT_EFFECTIVE_MIB={performance_options.native_job_memory_limit_mb}"
                            not in result.stdout.splitlines()):
                        raise RuntimeError("Native helper did not verify the requested job memory limit")
                else:
                    result = run_store_all_maps_helper(
                        hecras_dir=hecras_dir,
                        render_mode=helper_mode,
                        rasmap_path=rasmap_path,
                        result_hdf_path=mapper_hdf_path,
                        timeout=timeout,
                        working_dir=ras_obj.project_folder,
                        gdal_num_threads=(
                            performance_options.gdal_num_threads_per_helper
                        ),
                        gdal_cachemax_mb=performance_options.gdal_cachemax_mb,
                        native_cpu_limit=performance_options.native_cpu_limit,
                    )

                operation = "StoreMap polygon" if serial_polygon else "StoreAllMaps"
                logger.debug("%s stdout: %s", operation, result.stdout)
                if result.stderr:
                    stderr_lines = result.stderr.splitlines()
                    stderr_preview = (
                        stderr_lines[0] if stderr_lines else result.stderr[:200]
                    )
                    logger.warning(
                        "%s reported stderr: %s", operation,
                        stderr_preview,
                    )
                    logger.debug("%s full stderr: %s", operation, result.stderr)
                if result.returncode != 0:
                    stderr_detail = next(
                        (
                            line.strip()
                            for line in result.stderr.splitlines()
                            if line.strip()
                        ),
                        "",
                    )
                    detail_suffix = (
                        f": {stderr_detail[:500]}" if stderr_detail else ""
                    )
                    raise RuntimeError(
                        f"{operation} failed for plan "
                        f"{plan_num} (exit code {result.returncode})"
                        f"{detail_suffix}"
                    )

                for line in result.stdout.splitlines():
                    if "Maps generated" in line:
                        logger.debug(line.strip())

        # Identify this invocation's outputs before looking up requested
        # map names.  Filtering every return value through this set keeps
        # an old TIFF from being reported as fresh output when the helper
        # succeeds without producing a requested map.
        fresh_source_files = []
        for item in _iterdir_paths(output_dir):
            try:
                stat = os.stat(_windows_extended_length_path(item))
            except FileNotFoundError:
                continue
            if not os.path.isfile(_windows_extended_length_path(item)):
                continue
            previous_signature = pre_existing_files.get(item.name)
            current_signature = (stat.st_mtime_ns, stat.st_size)
            if previous_signature != current_signature:
                fresh_source_files.append(item)

        search_dir = output_dir
        produced_paths = list(fresh_source_files)

        # If output_path was requested, move files from default dir to output_path
        if resolved_output_path is not None and os.path.normcase(
            os.path.abspath(resolved_output_path)
        ) != os.path.normcase(os.path.abspath(output_dir)):
            logger.debug(
                "Moving generated files from %s to %s",
                output_dir,
                resolved_output_path,
            )
            moved_count = 0
            moved_paths = []
            # Move files that were created or modified by this call.
            for item in fresh_source_files:
                # PostProcessing.hdf is RasMapperLib's derived-map cache
                # (can exceed the plan HDF in size): leave it beside the
                # plan so reruns reuse it instead of paying a potentially
                # cross-volume move of a multi-GB scratch file.
                if item.name == "PostProcessing.hdf":
                    continue
                dest = resolved_output_path / item.name
                dest_move_path = _windows_extended_length_path(dest)
                if os.path.exists(dest_move_path):
                    os.remove(dest_move_path)
                shutil.move(
                    _windows_extended_length_path(item),
                    dest_move_path,
                )
                moved_paths.append(dest)
                moved_count += 1
            logger.debug(
                "Moved %d generated file(s) to %s",
                moved_count,
                resolved_output_path,
            )

            search_dir = resolved_output_path
            produced_paths = moved_paths

        def fresh_glob(pattern):
            """Return matching files only when produced by this call."""
            produced_keys = {
                os.path.normcase(os.path.abspath(path)) for path in produced_paths
            }
            return [
                path
                for path in _glob_paths(search_dir, pattern)
                if os.path.normcase(os.path.abspath(path)) in produced_keys
            ]

        # Find generated files in the appropriate directory
        generated_files = {}
        for map_type, map_key in maps_to_add:
            for key, (xml_name, display_name, _) in RasProcess.MAP_TYPES.items():
                if xml_name == map_type:
                    display_name_used = display_name
                    break
            else:
                display_name_used = map_type.title()

            safe_profile = profile_name.replace(":", " ").replace("/", "_")
            pattern = f"{display_name_used} ({safe_profile})*.tif"
            tif_files = fresh_glob(pattern)

            if not tif_files:
                pattern_alt = (
                    f"{display_name_used.replace(' ', '_')} ({safe_profile})*.tif"
                )
                tif_files = fresh_glob(pattern_alt)

            if tif_files:
                generated_files[map_key] = tif_files
                logger.debug("Generated %d %s TIF(s)", len(tif_files), map_key)
            else:
                logger.debug(
                    f"No TIF files found for {map_key} with pattern: {pattern}"
                )

        # Whole-simulation types label outputs by threshold, not profile
        # (e.g. "Arrival Time (0.1ft hrs).Terrain.tile.tif") — glob by
        # display-name prefix, restricted to files produced by this run so
        # a rerun at a different arrival_depth never collects the previous
        # threshold's rasters.
        for map_type, map_key in adr_maps_to_add:
            display_name_used = RasProcess.MAP_TYPES[map_key][1]

            pattern = f"{display_name_used} (*.tif"
            tif_files = fresh_glob(pattern)
            if tif_files:
                generated_files[map_key] = tif_files
                logger.info(f"Generated {len(tif_files)} {map_key} TIF(s)")
            else:
                logger.debug(
                    f"No TIF files found for {map_key} with pattern: {pattern}"
                )

        # Collect inundation boundary shapefile if requested
        if inundation_boundary:
            safe_profile = profile_name.replace(":", " ").replace("/", "_")
            # Native RAS Mapper inserts the contour value INSIDE the
            # parentheses: "Inundation Boundary (Max Value_0).shp".
            # Match the entire profile to avoid accepting a prefix match.
            boundary_pattern = re.compile(
                r"Inundation[ _]Boundary \("
                + re.escape(safe_profile)
                + r"(?: Value_0(?:\.0+)?)?\)\.shp$",
                re.IGNORECASE,
            )
            fresh_keys = {
                os.path.normcase(os.path.abspath(path)) for path in produced_paths
            }
            shp_files = [
                path for path in produced_paths
                if boundary_pattern.fullmatch(path.name)
                and all(
                    os.path.normcase(os.path.abspath(path.with_suffix(ext))) in fresh_keys
                    for ext in (".shp", ".shx", ".dbf")
                )
                and RasProcess._stored_boundary_has_features(path)
            ]
            if shp_files:
                generated_files["inundation_boundary"] = shp_files
                logger.debug(
                    "Generated %d inundation boundary shapefile(s)",
                    len(shp_files),
                )
            else:
                logger.warning(
                    "No fresh nonempty native inundation boundary SHP/SHX/DBF "
                    "product for plan %s, profile %r; inspect the mapping "
                    "output in %s",
                    plan_num, profile_name, search_dir,
                )

        # Fix georeferencing if requested
        if fix_georef and generated_files:
            proj_info = RasProcess._get_projection_info(rasmap_path)
            terrain_paths = proj_info.terrain_paths
            if not terrain_paths and proj_info.terrain_path is not None:
                terrain_paths = (proj_info.terrain_path,)
            if terrain_paths:
                if proj_info.prj_path is None:
                    logger.debug(
                        "Projection file referenced by %s was not found; "
                        "using terrain CRS for georef fix instead.",
                        rasmap_path.name,
                    )
                for tif_list in generated_files.values():
                    for tif_path in tif_list:
                        if Path(tif_path).suffix.lower() not in {".tif", ".tiff"}:
                            continue
                        terrain_path = RasProcess._terrain_for_stored_map(
                            tif_path,
                            terrain_paths,
                        )
                        if terrain_path is None:
                            logger.warning(
                                "Could not match stored-map TIFF to one of %d "
                                "terrain rasters; georeferencing was not changed: %s",
                                len(terrain_paths),
                                tif_path,
                            )
                            continue
                        RasProcess._fix_georeferencing(
                            tif_path,
                            proj_info.prj_path,
                            terrain_path,
                        )
            else:
                logger.warning("Could not find terrain for georef fix")
            RasProcess._drop_unreadable_tifs(generated_files)

        generated_file_count = sum(len(paths) for paths in generated_files.values())
        if _log_summary:
            operation_name = (
                "Parallel StoreMap" if worker_count > 1 else "StoreAllMaps"
            )
            logger.info(
                "%s complete: plan=%s; mode=%s; map_types=%d; files=%d",
                operation_name,
                plan_num,
                helper_mode,
                len(generated_files),
                generated_file_count,
            )
        return generated_files

    finally:
        # Restore rasmap backup
        rasmap_backup_path = _windows_extended_length_path(rasmap_backup)
        if os.path.exists(rasmap_backup_path):
            shutil.copy2(
                rasmap_backup_path,
                _windows_extended_length_path(rasmap_path),
            )
            os.remove(rasmap_backup_path)

store_maps_at_steady_profiles staticmethod

Python
store_maps_at_steady_profiles(plan_number: str, profiles: Optional[Union[str, int, Sequence[Union[str, int]]]] = None, output_path: Union[str, Path] = None, map_types: Union[str, Sequence[str]] = ('depth',), render_mode: str = None, clear_existing: bool = True, fix_georef: bool = True, ras_object=None, ras_version: str = None, timeout: int = 1800, *, terrain_name: Optional[str] = None, inundation_boundary: bool = True, raise_on_missing: bool = True, performance: Optional[StoreMapPerformanceOptions] = None) -> pd.DataFrame

Generate all selected steady-profile maps with one helper launch.

Profiles are resolved from the result HDF in exact HDF order. None selects every profile; exact names and zero-based indexes may be mixed in a sequence. The request order is preserved and no selector falls back to Max.

Every profile/product layer is configured in one .rasmap XML transaction, then aggregate StoreAllMaps is invoked exactly once. By default, one inundation boundary is also generated for the final selected profile. This means the highest profile for ras2fim's ascending ladders, but no hydraulic ordering is inferred here.

Parameters:

Name Type Description Default
plan_number str

Steady plan number.

required
profiles Optional[Union[str, int, Sequence[Union[str, int]]]]

None, an exact profile name, zero-based index, or a sequence mixing names and indexes.

None
output_path Union[str, Path]

Optional destination for all newly generated files.

None
map_types Union[str, Sequence[str]]

Profile-dependent product key(s). Defaults to Depth.

('depth',)
render_mode str

Optional water-surface render-mode override.

None
clear_existing bool

Remove existing stored-map layers for this plan in the temporary configuration.

True
fix_georef bool

Apply the existing terrain georeferencing repair to generated TIFF tiles.

True
ras_object RasPrj

Optional initialized project object.

None
ras_version str

Optional installed HEC-RAS mapping-runtime version.

None
timeout int

Aggregate helper timeout in seconds.

1800
terrain_name Optional[str]

Optional registered RASMapper terrain to select.

None
inundation_boundary bool

Generate one polygon for the final selected profile. Defaults to True. RASMapper names the polygon Inundation Boundary (<profile> Value_<depth>).shp (the specified depth is appended); both that and the configured Inundation Boundary (<profile>).shp name are recognized.

True
raise_on_missing bool

When True (default), raise :class:StoredMapProductsIncompleteError if any requested product is missing after StoreAllMaps. Every product that was generated is moved to output_path and kept on disk first; the exception's frame carries the per-product status. When False, return the frame with status="missing" rows.

True
performance Optional[StoreMapPerformanceOptions]

Per-helper GDAL threads, GDAL cache and native CPU controls. Aggregate steady export uses one helper; scheduler and memory-admission fields must retain their defaults and are not applied by this aggregate route. Wine helpers inherit one CPU and accept native_cpu_limit of 1 or None.

None

Returns:

Type Description
DataFrame

DataFrame with one row per logical profile/product and stable

DataFrame

columns registered as steady_profile_stored_maps in

DataFrame

mod:ras_commander.schemas. status is "generated" or

DataFrame

"missing"; primary_path is None for missing products.

DataFrame

attrs["missing_product_count"] counts missing rows.

Raises:

Type Description
FileNotFoundError

If required project, HDF, mapper, runtime, or terrain files are missing.

ValueError

If the plan, selectors, products, or output filenames are invalid or ambiguous.

RuntimeError

If StoreAllMaps fails.

StoredMapProductsIncompleteError

If raise_on_missing is True and a requested product is missing from the fresh outputs (a RuntimeError subclass; generated outputs are preserved).

TimeoutExpired

If the aggregate StoreAllMaps helper exceeds timeout.

Source code in ras_commander/RasProcess.py
Python
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
@staticmethod
@_serialize_store_maps
@log_call
def store_maps_at_steady_profiles(
    plan_number: str,
    profiles: Optional[
        Union[str, int, Sequence[Union[str, int]]]
    ] = None,
    output_path: Union[str, Path] = None,
    map_types: Union[str, Sequence[str]] = ("depth",),
    render_mode: str = None,
    clear_existing: bool = True,
    fix_georef: bool = True,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 1800,
    *,
    terrain_name: Optional[str] = None,
    inundation_boundary: bool = True,
    raise_on_missing: bool = True,
    performance: Optional[StoreMapPerformanceOptions] = None,
) -> pd.DataFrame:
    """Generate all selected steady-profile maps with one helper launch.

    Profiles are resolved from the result HDF in exact HDF order. ``None``
    selects every profile; exact names and zero-based indexes may be mixed
    in a sequence. The request order is preserved and no selector falls
    back to ``Max``.

    Every profile/product layer is configured in one ``.rasmap`` XML
    transaction, then aggregate ``StoreAllMaps`` is invoked exactly once.
    By default, one inundation boundary is also generated for the final
    selected profile. This means the highest profile for ras2fim's
    ascending ladders, but no hydraulic ordering is inferred here.

    Args:
        plan_number: Steady plan number.
        profiles: ``None``, an exact profile name, zero-based index, or a
            sequence mixing names and indexes.
        output_path: Optional destination for all newly generated files.
        map_types: Profile-dependent product key(s). Defaults to Depth.
        render_mode: Optional water-surface render-mode override.
        clear_existing: Remove existing stored-map layers for this plan in
            the temporary configuration.
        fix_georef: Apply the existing terrain georeferencing repair to
            generated TIFF tiles.
        ras_object (RasPrj, optional): Optional initialized project object.
        ras_version: Optional installed HEC-RAS mapping-runtime version.
        timeout: Aggregate helper timeout in seconds.
        terrain_name: Optional registered RASMapper terrain to select.
        inundation_boundary: Generate one polygon for the final selected
            profile. Defaults to True. RASMapper names the polygon
            ``Inundation Boundary (<profile> Value_<depth>).shp`` (the
            specified depth is appended); both that and the configured
            ``Inundation Boundary (<profile>).shp`` name are recognized.
        raise_on_missing: When True (default), raise
            :class:`StoredMapProductsIncompleteError` if any requested
            product is missing after StoreAllMaps. Every product that was
            generated is moved to ``output_path`` and kept on disk first;
            the exception's ``frame`` carries the per-product status.
            When False, return the frame with ``status="missing"`` rows.
        performance: Per-helper GDAL threads, GDAL cache and native CPU
            controls. Aggregate steady export uses one helper; scheduler
            and memory-admission fields must retain their defaults and
            are not applied by this aggregate route. Wine helpers inherit
            one CPU and accept ``native_cpu_limit`` of 1 or None.

    Returns:
        DataFrame with one row per logical profile/product and stable
        columns registered as ``steady_profile_stored_maps`` in
        :mod:`ras_commander.schemas`. ``status`` is ``"generated"`` or
        ``"missing"``; ``primary_path`` is None for missing products.
        ``attrs["missing_product_count"]`` counts missing rows.

    Raises:
        FileNotFoundError: If required project, HDF, mapper, runtime, or
            terrain files are missing.
        ValueError: If the plan, selectors, products, or output filenames
            are invalid or ambiguous.
        RuntimeError: If StoreAllMaps fails.
        StoredMapProductsIncompleteError: If ``raise_on_missing`` is True
            and a requested product is missing from the fresh outputs
            (a ``RuntimeError`` subclass; generated outputs are preserved).
        subprocess.TimeoutExpired: If the aggregate StoreAllMaps helper
            exceeds ``timeout``.
    """
    from .hdf.HdfResultsPlan import HdfResultsPlan

    performance_options = (
        StoreMapPerformanceOptions() if performance is None else performance
    )
    if not isinstance(performance_options, StoreMapPerformanceOptions):
        raise TypeError("performance must be a StoreMapPerformanceOptions")
    if replace(
        performance_options,
        gdal_num_threads_per_helper=1,
        gdal_cachemax_mb=None,
        native_cpu_limit=None,
    ) != StoreMapPerformanceOptions():
        raise ValueError(
            "steady aggregate performance supports only GDAL threads/cache "
            "and native_cpu_limit; scheduler fields must retain defaults"
        )
    if (
        _is_wine_helper_runtime()
        and performance_options.native_cpu_limit is not None
        and performance_options.native_cpu_limit > 1
    ):
        raise ValueError(
            "Wine stored-map helpers inherit one CPU; "
            "native_cpu_limit must be 1 or None"
        )
    started = time.perf_counter()
    ras_obj = ras_object or ras
    ras_obj.check_initialized()
    plan_num = RasUtils.normalize_ras_number(plan_number)

    hecras_dir = Path(str(ras_obj.ras_exe_path)).parent
    if not hecras_dir.is_dir():
        raise FileNotFoundError(f"HEC-RAS directory not found: {hecras_dir}")
    rasmap_path = RasMap.get_rasmap_path(ras_obj)
    if rasmap_path is None or not Path(rasmap_path).is_file():
        raise FileNotFoundError("No .rasmap file found in project folder")
    rasmap_path = Path(rasmap_path)

    plan_hdf_name = f"{ras_obj.project_name}.p{plan_num}.hdf"
    plan_hdf_path = ras_obj.project_folder / plan_hdf_name
    if not plan_hdf_path.is_file():
        raise FileNotFoundError(f"Plan HDF not found: {plan_hdf_path}")
    if not HdfResultsPlan.is_steady_plan(plan_hdf_path):
        raise ValueError(
            f"Plan {plan_num} does not contain steady results: {plan_hdf_path}"
        )

    available_profiles = HdfResultsPlan.get_steady_profile_names(plan_hdf_path)
    selected_profiles = RasProcess._resolve_steady_profile_selectors(
        available_profiles,
        profiles,
    )
    selected_map_types = RasProcess._normalize_steady_map_types(map_types)

    plan_short_id = RasProcess._get_plan_short_id(plan_hdf_path)
    if not plan_short_id:
        plan_rows = ras_obj.plan_df[
            ras_obj.plan_df["plan_number"].astype(str).eq(plan_num)
        ]
        plan_short_id = (
            str(plan_rows.iloc[0].get("Short Identifier", "")).strip()
            if not plan_rows.empty
            else ""
        )
    output_folder = plan_short_id or f"Plan_{plan_num}"
    output_dir = ras_obj.project_folder / output_folder

    extra_attrs = {"Terrain": terrain_name} if terrain_name is not None else {}
    map_specs: List[Dict[str, Any]] = []
    for profile_index, profile_name in selected_profiles:
        for map_key in selected_map_types:
            xml_name, display_name, _ = RasProcess.MAP_TYPES[map_key]
            map_specs.append(
                {
                    "map_key": map_key,
                    "map_type": xml_name,
                    "display_name": display_name,
                    "profile_index": profile_index,
                    "profile_name": profile_name,
                    "output_mode": "Stored Current Terrain",
                    "extra_attrs": dict(extra_attrs),
                }
            )
    if inundation_boundary:
        boundary_index, boundary_name = selected_profiles[-1]
        boundary_attrs = {**extra_attrs, "ContourPolygonValue": "0"}
        map_specs.append(
            {
                "map_key": "inundation_boundary",
                "map_type": "depth",
                "display_name": "Inundation Boundary",
                "profile_index": boundary_index,
                "profile_name": boundary_name,
                "output_mode": "Stored Polygon Specified Depth",
                "extra_attrs": boundary_attrs,
            }
        )

    # Fail before mutating the rasmap when two selected labels normalize to
    # the same StoredFilename.
    requested_filenames = []
    for spec in map_specs:
        requested_filenames.append(
            RasProcess._stored_map_output_filename(
                output_folder=output_folder,
                display_name=spec["display_name"],
                profile_name=spec["profile_name"],
                output_mode=spec["output_mode"],
            )
        )
    collision_keys = [name.casefold() for name in requested_filenames]
    if len(set(collision_keys)) != len(collision_keys):
        duplicates = sorted(
            {
                name
                for name in requested_filenames
                if collision_keys.count(name.casefold()) > 1
            }
        )
        raise ValueError(
            "Steady stored-map output filename collision: "
            + ", ".join(duplicates)
        )

    resolved_output_path = None
    if output_path is not None:
        resolved_output_path = Path(output_path)
        if not resolved_output_path.is_absolute():
            resolved_output_path = RasUtils.safe_resolve(
                ras_obj.project_folder / resolved_output_path
            )

    rasmap_backup = rasmap_path.with_name(
        f"{rasmap_path.name}.{os.getpid()}.{uuid.uuid4().hex}.bak"
    )
    shutil.copy2(
        _windows_extended_length_path(rasmap_path),
        _windows_extended_length_path(rasmap_backup),
    )

    helper_elapsed = 0.0
    configuration_elapsed = 0.0
    try:
        configuration_started = time.perf_counter()
        configured_specs = RasProcess._add_stored_maps_to_rasmap(
            rasmap_path,
            plan_hdf_name,
            output_folder,
            map_specs,
            clear_existing=clear_existing,
        )
        configuration_elapsed = time.perf_counter() - configuration_started

        if terrain_name is not None:
            RasProcess._select_terrain_for_mapping(
                rasmap_path,
                terrain_name,
                ras_object=ras_obj,
            )
        if render_mode is not None:
            RasProcess._set_rasmap_render_mode(render_mode, ras_obj)

        os.makedirs(_windows_extended_length_path(output_dir), exist_ok=True)
        if resolved_output_path is not None:
            os.makedirs(
                _windows_extended_length_path(resolved_output_path),
                exist_ok=True,
            )

        before = {}
        for item in _iterdir_paths(output_dir):
            if not os.path.isfile(_windows_extended_length_path(item)):
                continue
            stat = os.stat(_windows_extended_length_path(item))
            before[item.name] = (stat.st_mtime_ns, stat.st_size)

        current_mode = render_mode or RasMap.get_water_surface_render_mode(
            ras_object=ras_obj
        )
        helper_mode = normalize_store_map_render_mode(current_mode)
        effective_ras_version = ras_version or getattr(
            ras_obj,
            "ras_version",
            None,
        )
        runtime_provenance = store_maps_runtime_provenance(hecras_dir)

        with RasProcess._mapper_compatible_result_hdf(
            plan_hdf_path,
            effective_ras_version,
        ) as mapper_hdf_path:
            helper_started = time.perf_counter()
            result = run_store_all_maps_helper(
                hecras_dir=hecras_dir,
                render_mode=helper_mode,
                rasmap_path=rasmap_path,
                result_hdf_path=mapper_hdf_path,
                timeout=timeout,
                working_dir=ras_obj.project_folder,
                gdal_num_threads=performance_options.gdal_num_threads_per_helper,
                gdal_cachemax_mb=performance_options.gdal_cachemax_mb,
                native_cpu_limit=performance_options.native_cpu_limit,
            )
            helper_elapsed = time.perf_counter() - helper_started

        logger.debug("Steady StoreAllMaps stdout: %s", result.stdout)
        if result.stderr:
            logger.debug("Steady StoreAllMaps stderr: %s", result.stderr)
        if result.returncode != 0:
            detail = next(
                (line.strip() for line in result.stderr.splitlines() if line.strip()),
                "",
            )
            raise RuntimeError(
                f"StoreAllMaps failed for steady plan {plan_num} "
                f"(exit code {result.returncode})"
                + (f": {detail[:500]}" if detail else "")
            )

        produced_paths = []
        for item in _iterdir_paths(output_dir):
            if not os.path.isfile(_windows_extended_length_path(item)):
                continue
            stat = os.stat(_windows_extended_length_path(item))
            signature = (stat.st_mtime_ns, stat.st_size)
            if before.get(item.name) != signature:
                produced_paths.append(item)

        if resolved_output_path is not None and os.path.normcase(
            os.path.abspath(resolved_output_path)
        ) != os.path.normcase(os.path.abspath(output_dir)):
            moved_paths = []
            for item in produced_paths:
                if item.name == "PostProcessing.hdf":
                    continue
                destination = resolved_output_path / item.name
                destination_io = _windows_extended_length_path(destination)
                if os.path.exists(destination_io):
                    os.remove(destination_io)
                shutil.move(
                    _windows_extended_length_path(item),
                    destination_io,
                )
                moved_paths.append(destination)
            produced_paths = moved_paths

        if fix_georef:
            tif_paths = [
                path
                for path in produced_paths
                if path.suffix.casefold() in {".tif", ".tiff"}
            ]
            if tif_paths:
                projection = RasProcess._get_projection_info(rasmap_path)
                terrain_paths = projection.terrain_paths
                if not terrain_paths and projection.terrain_path is not None:
                    terrain_paths = (projection.terrain_path,)
                for tif_path in tif_paths:
                    terrain_path = RasProcess._terrain_for_stored_map(
                        tif_path,
                        terrain_paths,
                    )
                    if terrain_path is None:
                        logger.warning(
                            "Could not match steady stored-map TIFF to a "
                            "terrain; georeferencing was not changed: %s",
                            tif_path,
                        )
                        continue
                    RasProcess._fix_georeferencing(
                        tif_path,
                        projection.prj_path,
                        terrain_path,
                    )
                readable = {"batch": list(tif_paths)}
                RasProcess._drop_unreadable_tifs(readable)
                readable_keys = {
                    os.path.normcase(os.path.abspath(path))
                    for path in readable["batch"]
                }
                produced_paths = [
                    path
                    for path in produced_paths
                    if path.suffix.casefold() not in {".tif", ".tiff"}
                    or os.path.normcase(os.path.abspath(path)) in readable_keys
                ]

        produced_paths = sorted(
            produced_paths,
            key=lambda path: path.name.casefold(),
        )
        rows = []
        missing_messages: List[str] = []
        for spec in configured_specs:
            safe_profile = RasProcess._safe_stored_map_profile(
                spec["profile_name"]
            )
            # RASMapper appends the specified depth to polygon names, e.g.
            # "Inundation Boundary (flow_075 Value_0).shp", even though
            # StoredFilename is "Inundation Boundary (flow_075).shp".
            filename_pattern = re.compile(
                re.escape(f"{spec['display_name']} ({safe_profile}")
                + r"(?: Value_[^)]*)?\)",
                re.IGNORECASE,
            )
            associated = [
                path
                for path in produced_paths
                if filename_pattern.match(path.name)
            ]
            is_polygon = "Polygon" in spec["output_mode"]
            primary_suffix = ".shp" if is_polygon else ".vrt"
            primary = next(
                (
                    path
                    for path in associated
                    if path.suffix.casefold() == primary_suffix
                ),
                None,
            )
            raster_tiles = [
                path
                for path in associated
                if path.suffix.casefold() in {".tif", ".tiff"}
            ]
            generated = primary is not None and (is_polygon or bool(raster_tiles))
            if not generated:
                expected = "SHP" if is_polygon else "VRT and TIFF tile(s)"
                missing_messages.append(
                    f"{expected} for {spec['map_key']} profile "
                    f"{spec['profile_name']!r}"
                )
            rows.append(
                {
                    "plan_number": plan_num,
                    "result_hdf_path": str(plan_hdf_path.resolve()),
                    "profile_index": int(spec["profile_index"]),
                    "profile_name": str(spec["profile_name"]),
                    "map_type": str(spec["map_key"]),
                    "output_mode": "polygon" if is_polygon else "raster",
                    "primary_path": (
                        str(primary.resolve()) if generated else None
                    ),
                    "files": [str(path.resolve()) for path in associated],
                    "file_count": len(associated),
                    "status": "generated" if generated else "missing",
                }
            )

        frame = pd.DataFrame(
            rows,
            columns=[
                "plan_number",
                "result_hdf_path",
                "profile_index",
                "profile_name",
                "map_type",
                "output_mode",
                "primary_path",
                "files",
                "file_count",
                "status",
            ],
        )
        frame.attrs["schema"] = (
            "ras_commander.steady_profile_stored_maps.v2"
        )
        frame.attrs["helper_launch_count"] = 1
        frame.attrs["elapsed_seconds"] = time.perf_counter() - started
        frame.attrs["configuration_elapsed_seconds"] = configuration_elapsed
        frame.attrs["helper_elapsed_seconds"] = helper_elapsed
        frame.attrs["profile_count"] = len(selected_profiles)
        frame.attrs["configured_map_count"] = len(configured_specs)
        frame.attrs["generated_file_count"] = len(produced_paths)
        frame.attrs["runtime_provenance"] = runtime_provenance
        frame.attrs["performance_requested"] = performance_options.to_dict()
        frame.attrs["performance_effective"] = {
            "helper_count": 1,
            "gdal_num_threads_per_helper": performance_options.gdal_num_threads_per_helper,
            "gdal_cachemax_mb": performance_options.gdal_cachemax_mb,
            "native_cpu_limit": (
                1 if _is_wine_helper_runtime()
                else performance_options.native_cpu_limit
            ),
        }
        frame.attrs["missing_product_count"] = len(missing_messages)
        if missing_messages:
            message = (
                f"StoreAllMaps did not produce {len(missing_messages)} of "
                f"{len(configured_specs)} requested product(s) for steady "
                f"plan {plan_num}: " + "; ".join(missing_messages[:10])
                + ("; ..." if len(missing_messages) > 10 else "")
                + f". {len(configured_specs) - len(missing_messages)} "
                "generated product(s) were preserved"
                + (
                    f" in {resolved_output_path}"
                    if resolved_output_path is not None
                    else f" in {output_dir}"
                )
            )
            logger.error(message)
            if raise_on_missing:
                raise StoredMapProductsIncompleteError(message, frame)
        logger.info(
            "Steady-profile StoreAllMaps complete: plan=%s; profiles=%d; "
            "configured_maps=%d; missing=%d; helper_launches=1; files=%d",
            plan_num,
            len(selected_profiles),
            len(configured_specs),
            len(missing_messages),
            len(produced_paths),
        )
        return frame
    finally:
        backup_io = _windows_extended_length_path(rasmap_backup)
        if os.path.exists(backup_io):
            shutil.copy2(
                backup_io,
                _windows_extended_length_path(rasmap_path),
            )
            os.remove(backup_io)

store_maps_at_timesteps staticmethod

Python
store_maps_at_timesteps(plan_number: str, output_path: Union[str, Path] = None, timesteps: Optional[Union[int, str, datetime, List[Union[int, str, datetime]]]] = None, max_timesteps: Optional[int] = None, wse: bool = False, depth: bool = True, velocity: bool = False, froude: bool = False, shear_stress: bool = False, depth_x_velocity: bool = False, depth_x_velocity_sq: bool = False, render_mode: str = None, clear_existing: bool = True, fix_georef: bool = True, ras_object=None, ras_version: str = None, timeout: int = 600, *, performance: Optional[StoreMapPerformanceOptions] = None, max_workers: Any = _PERFORMANCE_UNSET, memory_per_worker_mb: Any = _PERFORMANCE_UNSET, reserve_memory_mb: Any = _PERFORMANCE_UNSET) -> Dict[str, Dict[str, List[Path]]]

Generate stored maps for one or more output timesteps.

This convenience wrapper routes each selected timestep through store_maps(profile=<timestamp>) so callers can export a sequence of rasters suitable for animation.

Parameters:

Name Type Description Default
plan_number str

Plan number (e.g., "02").

required
output_path Union[str, Path]

Optional directory for generated rasters.

None
timesteps Optional[Union[int, str, datetime, List[Union[int, str, datetime]]]]

Optional timestep selector. Items may be zero-based integer indices, exact RASMapper timestamp strings, or datetimes. If omitted, all available output timesteps are used.

None
max_timesteps Optional[int]

Optional cap applied after timestep selection.

None
wse bool

Generate WSE maps (default: False).

False
depth bool

Generate Depth maps (default: True).

True
velocity bool

Generate Velocity maps (default: False).

False
froude bool

Generate Froude maps (default: False).

False
shear_stress bool

Generate Shear Stress maps (default: False).

False
depth_x_velocity bool

Generate depth-times-velocity maps (default: False).

False
depth_x_velocity_sq bool

Generate depth-times-velocity-squared maps (default: False).

False
render_mode str

Rendering mode passed through to store_maps.

None
clear_existing bool

Clear existing stored maps, passed to store_maps.

True
fix_georef bool

Georeferencing fix flag passed to store_maps.

True
ras_object RasPrj

Project object passed to store_maps.

None
ras_version str

Mapping-runtime version passed to store_maps.

None
timeout int

Per-call timeout in seconds passed to store_maps.

600
performance Optional[StoreMapPerformanceOptions]

StoreMap execution and memory policy for every timestep.

None
max_workers Any

Deprecated keyword-only worker-count migration alias.

_PERFORMANCE_UNSET
memory_per_worker_mb Any

Deprecated keyword-only per-worker memory alias.

_PERFORMANCE_UNSET
reserve_memory_mb Any

Deprecated keyword-only reserved-memory alias.

_PERFORMANCE_UNSET

Returns:

Type Description
Dict[str, Dict[str, List[Path]]]

Dict keyed by RASMapper timestamp string. Each value is the

Dict[str, Dict[str, List[Path]]]

store_maps result for that timestep.

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def store_maps_at_timesteps(
    plan_number: str,
    output_path: Union[str, Path] = None,
    timesteps: Optional[
        Union[int, str, datetime, List[Union[int, str, datetime]]]
    ] = None,
    max_timesteps: Optional[int] = None,
    wse: bool = False,
    depth: bool = True,
    velocity: bool = False,
    froude: bool = False,
    shear_stress: bool = False,
    depth_x_velocity: bool = False,
    depth_x_velocity_sq: bool = False,
    render_mode: str = None,
    clear_existing: bool = True,
    fix_georef: bool = True,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 600,
    *,
    performance: Optional[StoreMapPerformanceOptions] = None,
    max_workers: Any = _PERFORMANCE_UNSET,
    memory_per_worker_mb: Any = _PERFORMANCE_UNSET,
    reserve_memory_mb: Any = _PERFORMANCE_UNSET,
) -> Dict[str, Dict[str, List[Path]]]:
    """
    Generate stored maps for one or more output timesteps.

    This convenience wrapper routes each selected timestep through
    ``store_maps(profile=<timestamp>)`` so callers can export a sequence of
    rasters suitable for animation.

    Args:
        plan_number: Plan number (e.g., "02").
        output_path: Optional directory for generated rasters.
        timesteps: Optional timestep selector. Items may be zero-based
            integer indices, exact RASMapper timestamp strings, or datetimes.
            If omitted, all available output timesteps are used.
        max_timesteps: Optional cap applied after timestep selection.
        wse: Generate WSE maps (default: False).
        depth: Generate Depth maps (default: True).
        velocity: Generate Velocity maps (default: False).
        froude: Generate Froude maps (default: False).
        shear_stress: Generate Shear Stress maps (default: False).
        depth_x_velocity: Generate depth-times-velocity maps (default: False).
        depth_x_velocity_sq: Generate depth-times-velocity-squared maps (default: False).
        render_mode: Rendering mode passed through to ``store_maps``.
        clear_existing: Clear existing stored maps, passed to ``store_maps``.
        fix_georef: Georeferencing fix flag passed to ``store_maps``.
        ras_object (RasPrj, optional): Project object passed to ``store_maps``.
        ras_version: Mapping-runtime version passed to ``store_maps``.
        timeout: Per-call timeout in seconds passed to ``store_maps``.
        performance: StoreMap execution and memory policy for every
            timestep.
        max_workers: Deprecated keyword-only worker-count migration alias.
        memory_per_worker_mb: Deprecated keyword-only per-worker memory alias.
        reserve_memory_mb: Deprecated keyword-only reserved-memory alias.

    Returns:
        Dict keyed by RASMapper timestamp string. Each value is the
        ``store_maps`` result for that timestep.
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    available = RasProcess.get_plan_timestamps(plan_number, ras_obj)
    if not available:
        raise ValueError(f"No output timesteps found for plan {plan_number}")

    selected = RasProcess._select_store_map_timesteps(available, timesteps)
    if max_timesteps is not None:
        selected = selected[: int(max_timesteps)]
    if not selected:
        raise ValueError("No timesteps selected for stored map export")

    performance_options, performance_was_explicit = (
        _coerce_store_map_performance_options(
            performance,
            max_workers=max_workers,
            memory_per_worker_mb=memory_per_worker_mb,
            reserve_memory_mb=reserve_memory_mb,
        )
    )
    forwarded_performance = (
        performance_options if performance_was_explicit else None
    )

    results: Dict[str, Dict[str, List[Path]]] = {}
    for timestamp in selected:
        results[timestamp] = RasProcess.store_maps(
            plan_number=plan_number,
            output_path=output_path,
            profile=timestamp,
            render_mode=render_mode,
            wse=wse,
            depth=depth,
            velocity=velocity,
            froude=froude,
            shear_stress=shear_stress,
            depth_x_velocity=depth_x_velocity,
            depth_x_velocity_sq=depth_x_velocity_sq,
            clear_existing=clear_existing,
            fix_georef=fix_georef,
            ras_object=ras_obj,
            ras_version=ras_version,
            timeout=timeout,
            _log_summary=False,
            performance=forwarded_performance,
        )
        timestep_file_count = sum(
            len(paths) for paths in results[timestamp].values()
        )
        logger.debug(
            "StoreAllMaps timestep complete: plan=%s; timestep=%s; files=%d",
            plan_number,
            timestamp,
            timestep_file_count,
        )

    map_types = {
        map_type
        for timestep_results in results.values()
        for map_type, paths in timestep_results.items()
        if paths
    }
    total_files = sum(
        len(paths)
        for timestep_results in results.values()
        for paths in timestep_results.values()
    )
    logger.info(
        "StoreAllMaps timesteps complete: plan=%s; timesteps=%d; map_types=%d; files=%d",
        RasUtils.normalize_ras_number(plan_number),
        len(selected),
        len(map_types),
        total_files,
    )
    return results

store_all_maps staticmethod

Python
store_all_maps(output_folder: str = None, output_path: Union[str, Path] = None, profile: str = 'Max', wse: bool = True, depth: bool = True, velocity: bool = True, froude: bool = False, shear_stress: bool = False, depth_x_velocity: bool = False, depth_x_velocity_sq: bool = False, fix_georef: bool = True, ras_object=None, ras_version: str = None, timeout: int = 1800, *, performance: Optional[StoreMapPerformanceOptions] = None, max_workers: Any = _PERFORMANCE_UNSET, memory_per_worker_mb: Any = _PERFORMANCE_UNSET, reserve_memory_mb: Any = _PERFORMANCE_UNSET) -> Dict[str, Dict[str, List[Path]]]

Compatibility alias for RasMap.store_all_maps(mode="all_plans").

New code should use the canonical RasMap.store_all_maps() entry point, which exposes native, selected-map, timestep, and all-plan modes. This method preserves the historical RasProcess return shape.

Parameters:

Name Type Description Default
output_folder str

Base output folder (plan name appended). If None, uses plan titles.

None
output_path Union[str, Path]

Custom output directory. If provided, a subdirectory per plan is created (e.g., output_path/plan_01/). See store_maps() for details.

None
profile str

Profile to map - "Max", "Min", or specific timestamp

'Max'
wse bool

Generate WSE maps (default: True)

True
depth bool

Generate Depth maps (default: True)

True
velocity bool

Generate Velocity maps (default: True)

True
froude bool

Generate Froude maps (default: False)

False
shear_stress bool

Generate Shear Stress maps (default: False)

False
depth_x_velocity bool

Generate D*V maps (default: False)

False
depth_x_velocity_sq bool

Generate D*V² maps (default: False)

False
fix_georef bool

Apply georeferencing fix (default: True)

True
ras_object RasPrj

Optional RAS object instance

None
ras_version str

Optional specific HEC-RAS version

None
timeout int

Timeout per plan in seconds (default: 1800)

1800
performance Optional[StoreMapPerformanceOptions]

StoreMap execution and memory policy for every plan.

None
max_workers Any

Deprecated keyword-only worker-count migration alias.

_PERFORMANCE_UNSET
memory_per_worker_mb Any

Deprecated keyword-only per-worker memory alias.

_PERFORMANCE_UNSET
reserve_memory_mb Any

Deprecated keyword-only reserved-memory alias.

_PERFORMANCE_UNSET

Returns:

Type Description
Dict[str, Dict[str, List[Path]]]

Dict mapping plan numbers to their generated files dict.

Example

summary = RasMap.store_all_maps(mode="all_plans", profile="Max") for plan, plan_result in summary["plans"].items(): ... print(plan, plan_result["success"])

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def store_all_maps(
    output_folder: str = None,
    output_path: Union[str, Path] = None,
    profile: str = "Max",
    wse: bool = True,
    depth: bool = True,
    velocity: bool = True,
    froude: bool = False,
    shear_stress: bool = False,
    depth_x_velocity: bool = False,
    depth_x_velocity_sq: bool = False,
    fix_georef: bool = True,
    ras_object=None,
    ras_version: str = None,
    timeout: int = 1800,
    *,
    performance: Optional[StoreMapPerformanceOptions] = None,
    max_workers: Any = _PERFORMANCE_UNSET,
    memory_per_worker_mb: Any = _PERFORMANCE_UNSET,
    reserve_memory_mb: Any = _PERFORMANCE_UNSET,
) -> Dict[str, Dict[str, List[Path]]]:
    """
    Compatibility alias for ``RasMap.store_all_maps(mode="all_plans")``.

    New code should use the canonical ``RasMap.store_all_maps()`` entry
    point, which exposes native, selected-map, timestep, and all-plan
    modes. This method preserves the historical RasProcess return shape.

    Args:
        output_folder: Base output folder (plan name appended). If None, uses plan titles.
        output_path: Custom output directory. If provided, a subdirectory per plan
            is created (e.g., ``output_path/plan_01/``). See store_maps() for details.
        profile: Profile to map - "Max", "Min", or specific timestamp
        wse: Generate WSE maps (default: True)
        depth: Generate Depth maps (default: True)
        velocity: Generate Velocity maps (default: True)
        froude: Generate Froude maps (default: False)
        shear_stress: Generate Shear Stress maps (default: False)
        depth_x_velocity: Generate D*V maps (default: False)
        depth_x_velocity_sq: Generate D*V² maps (default: False)
        fix_georef: Apply georeferencing fix (default: True)
        ras_object (RasPrj, optional): Optional RAS object instance
        ras_version: Optional specific HEC-RAS version
        timeout: Timeout per plan in seconds (default: 1800)
        performance: StoreMap execution and memory policy for every plan.
        max_workers: Deprecated keyword-only worker-count migration alias.
        memory_per_worker_mb: Deprecated keyword-only per-worker memory alias.
        reserve_memory_mb: Deprecated keyword-only reserved-memory alias.

    Returns:
        Dict mapping plan numbers to their generated files dict.

    Example:
        >>> summary = RasMap.store_all_maps(mode="all_plans", profile="Max")
        >>> for plan, plan_result in summary["plans"].items():
        ...     print(plan, plan_result["success"])
    """
    performance_options, performance_was_explicit = (
        _coerce_store_map_performance_options(
            performance,
            max_workers=max_workers,
            memory_per_worker_mb=memory_per_worker_mb,
            reserve_memory_mb=reserve_memory_mb,
        )
    )
    forwarded_performance = (
        performance_options if performance_was_explicit else None
    )
    warnings.warn(
        "RasProcess.store_all_maps() is a compatibility alias; use "
        "RasMap.store_all_maps(mode='all_plans', ...) instead.",
        DeprecationWarning,
        stacklevel=3,
    )
    from .RasMap import RasMap

    summary = RasMap.store_all_maps(
        plan_number=None,
        ras_object=ras_object,
        timeout=timeout,
        mode="all_plans",
        output_folder=output_folder,
        output_path=output_path,
        profile=profile,
        wse=wse,
        depth=depth,
        velocity=velocity,
        froude=froude,
        shear_stress=shear_stress,
        depth_x_velocity=depth_x_velocity,
        depth_x_velocity_sq=depth_x_velocity_sq,
        fix_georef=fix_georef,
        ras_version=ras_version,
        performance=forwarded_performance,
    )
    return {
        plan_num: (
            {
                map_type: [Path(path) for path in paths]
                for map_type, paths in plan_result.get("files_by_type", {}).items()
            }
            if plan_result.get("success")
            else {"error": plan_result.get("error", "stored map failure")}
        )
        for plan_num, plan_result in summary["plans"].items()
    }

run_command staticmethod

Python
run_command(command_xml: str, ras_version: str = None, timeout: int = 600) -> subprocess.CompletedProcess

Run a raw RasProcess.exe command from XML string.

This is a low-level method for running arbitrary RasProcess commands. See rasmapper_docs/16_rasprocess_cli_reference.md for available commands.

Works on both Windows (native) and Linux (via Wine).

Warning

StoreAllMaps commands always write to <project>/<Plan ShortID>/ and cannot be redirected. To control the output directory, use store_maps(output_path=...) which runs StoreAllMaps then moves files to the requested path. Individual StoreMap commands with absolute OutputBaseFilename crash on multi-terrain projects (NullReferenceException in SetProjectionInfo). store_maps(max_workers=...) uses the packaged mapper helper's separate headless implementation, which initializes SRS state explicitly instead of using this raw command.

Parameters:

Name Type Description Default
command_xml str

XML command string

required
ras_version str

Optional specific HEC-RAS version

None
timeout int

Command timeout in seconds

600

Returns:

Type Description
CompletedProcess

subprocess.CompletedProcess with stdout/stderr

Example

xml = ''' ... ... depth ... C:/project/plan.p01.hdf ... Max ... C:/project/Maps/depth_max ... ''' result = RasProcess.run_command(xml)

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def run_command(
    command_xml: str, ras_version: str = None, timeout: int = 600
) -> subprocess.CompletedProcess:
    """
    Run a raw RasProcess.exe command from XML string.

    This is a low-level method for running arbitrary RasProcess commands.
    See rasmapper_docs/16_rasprocess_cli_reference.md for available commands.

    Works on both Windows (native) and Linux (via Wine).

    Warning:
        ``StoreAllMaps`` commands always write to
        ``<project>/<Plan ShortID>/`` and cannot be redirected.
        To control the output directory, use ``store_maps(output_path=...)``
        which runs ``StoreAllMaps`` then moves files to the requested path.
        Individual ``StoreMap`` commands with absolute ``OutputBaseFilename``
        crash on multi-terrain projects (NullReferenceException in
        ``SetProjectionInfo``). ``store_maps(max_workers=...)`` uses the
        packaged mapper helper's separate headless implementation, which
        initializes SRS state explicitly instead of using this raw command.

    Args:
        command_xml: XML command string
        ras_version: Optional specific HEC-RAS version
        timeout: Command timeout in seconds

    Returns:
        subprocess.CompletedProcess with stdout/stderr

    Example:
        >>> xml = '''<?xml version="1.0" encoding="utf-8"?>
        ... <Command Type="StoreMap">
        ...   <MapType>depth</MapType>
        ...   <Result>C:/project/plan.p01.hdf</Result>
        ...   <ProfileName>Max</ProfileName>
        ...   <OutputBaseFilename>C:/project/Maps/depth_max</OutputBaseFilename>
        ... </Command>'''
        >>> result = RasProcess.run_command(xml)
    """
    rasprocess = RasProcess.find_rasprocess(ras_version)
    if rasprocess is None:
        raise FileNotFoundError("RasProcess.exe not found")

    # Warn if StoreAllMaps is used — it cannot write to a custom output path
    if "StoreAllMaps" in command_xml:
        logger.warning(
            "StoreAllMaps always writes to <project>/<Plan ShortID>/. "
            "To write to a custom directory, use store_maps(output_path=...) "
            "which runs StoreAllMaps then moves files to the requested path."
        )

    # Write XML to temp file
    # On Linux, temp file must be within Wine's drive_c for accessibility
    if IS_LINUX:
        wine_config = RasProcess._get_wine_config()
        if wine_config:
            temp_dir = wine_config.wine_prefix / "drive_c" / "temp"
            temp_dir.mkdir(parents=True, exist_ok=True)
            xml_path = temp_dir / f"rasprocess_cmd_{os.getpid()}.xml"
            _write_ras_text(xml_path, command_xml, encoding="utf-8")
            xml_wine_path = RasProcess._linux_to_wine_path(xml_path)
        else:
            raise RuntimeError("Wine not configured on Linux")
    else:
        f = tempfile.NamedTemporaryFile(
            mode="w", suffix=".xml", delete=False, encoding="utf-8", newline=""
        )
        f.write(_normalize_ras_newlines(command_xml))
        f.close()
        xml_path = Path(f.name)
        xml_wine_path = str(xml_path)

    try:
        result = RasProcess._run_rasprocess(
            rasprocess,
            [f"-CommandFile={xml_wine_path}"],
            timeout=timeout,
        )

        logger.debug(f"Command output: {result.stdout}")
        if result.stderr:
            stderr_lines = result.stderr.splitlines()
            stderr_preview = (
                stderr_lines[0] if stderr_lines else result.stderr[:200]
            )
            logger.warning("Command reported stderr: %s", stderr_preview)
            logger.debug("Command full stderr: %s", result.stderr)

        return result

    finally:
        if xml_path.exists():
            xml_path.unlink()

apply_depth_threshold staticmethod

Python
apply_depth_threshold(input_tiff: Union[str, Path], output_tiff: Union[str, Path], min_depth: float = 0.0, reproject_wgs84: bool = False, ras_object=None) -> Dict[str, Any]

Apply depth threshold to a GeoTIFF and optionally reproject to WGS84.

Cells with values below min_depth are set to NoData. Optionally reprojects the raster to EPSG:4326 (WGS84).

Parameters

input_tiff : str or Path Path to input GeoTIFF output_tiff : str or Path Path for output GeoTIFF min_depth : float, default 0.0 Minimum depth threshold. Cells below this value become NoData. reproject_wgs84 : bool, default False If True, reproject output to EPSG:4326 (WGS84) ras_object : optional Custom RAS object (unused, for API consistency)

Returns

dict Report with keys: input, output, cells_total, cells_filtered, cells_remaining, reprojected

Example

result = RasProcess.apply_depth_threshold( ... 'depth_max.tif', 'depth_filtered.tif', min_depth=0.75 ... ) print(f"Filtered {result['cells_filtered']} cells below 0.75 ft")

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def apply_depth_threshold(
    input_tiff: Union[str, Path],
    output_tiff: Union[str, Path],
    min_depth: float = 0.0,
    reproject_wgs84: bool = False,
    ras_object=None,
) -> Dict[str, Any]:
    """
    Apply depth threshold to a GeoTIFF and optionally reproject to WGS84.

    Cells with values below min_depth are set to NoData. Optionally
    reprojects the raster to EPSG:4326 (WGS84).

    Parameters
    ----------
    input_tiff : str or Path
        Path to input GeoTIFF
    output_tiff : str or Path
        Path for output GeoTIFF
    min_depth : float, default 0.0
        Minimum depth threshold. Cells below this value become NoData.
    reproject_wgs84 : bool, default False
        If True, reproject output to EPSG:4326 (WGS84)
    ras_object : optional
        Custom RAS object (unused, for API consistency)

    Returns
    -------
    dict
        Report with keys: input, output, cells_total, cells_filtered,
        cells_remaining, reprojected

    Example
    -------
    >>> result = RasProcess.apply_depth_threshold(
    ...     'depth_max.tif', 'depth_filtered.tif', min_depth=0.75
    ... )
    >>> print(f"Filtered {result['cells_filtered']} cells below 0.75 ft")
    """
    if not HAS_RASTERIO:
        raise ImportError(
            "rasterio is required for apply_depth_threshold(). "
            "Install with: pip install rasterio"
        )

    input_path = Path(input_tiff)
    output_path = Path(output_tiff)

    if not input_path.exists():
        raise FileNotFoundError(f"Input TIFF not found: {input_path}")

    output_path.parent.mkdir(parents=True, exist_ok=True)

    with rasterio.open(input_path) as src:
        data = src.read(1)
        profile = src.profile.copy()
        nodata = src.nodata if src.nodata is not None else -9999.0

        # Apply threshold
        mask = (data < min_depth) | np.isnan(data)
        if src.nodata is not None:
            mask = mask | (data == src.nodata)

        cells_total = int(data.size)
        cells_filtered = int(mask.sum())
        data[mask] = nodata

        profile.update(nodata=nodata)

        if reproject_wgs84:
            from rasterio.warp import (
                calculate_default_transform,
                reproject as rio_reproject,
            )
            from rasterio.crs import CRS as RioCRS

            dst_crs = RioCRS.from_epsg(4326)
            transform, width, height = calculate_default_transform(
                src.crs, dst_crs, src.width, src.height, *src.bounds
            )
            profile.update(
                crs=dst_crs, transform=transform, width=width, height=height
            )

            dst_data = np.full((height, width), nodata, dtype=data.dtype)
            rio_reproject(
                source=data,
                destination=dst_data,
                src_transform=src.transform,
                src_crs=src.crs,
                dst_transform=transform,
                dst_crs=dst_crs,
                src_nodata=nodata,
                dst_nodata=nodata,
            )
            data = dst_data

        with rasterio.open(output_path, "w", **profile) as dst:
            dst.write(data, 1)

    logger.debug(
        f"Threshold applied: {cells_filtered}/{cells_total} cells filtered "
        f"(min_depth={min_depth}), output: {output_path.name}"
    )

    return {
        "input": str(input_path),
        "output": str(output_path),
        "cells_total": cells_total,
        "cells_filtered": cells_filtered,
        "cells_remaining": cells_total - cells_filtered,
        "reprojected": reproject_wgs84,
    }

batch_export_rasters staticmethod

Python
batch_export_rasters(plan_numbers: List[str], output_dir: Union[str, Path], min_depth: float = 0.0, reproject_wgs84: bool = False, naming_template: str = '{plan}_{map_type}', profile: str = 'Max', ras_object=None, ras_version: str = None, timeout: int = 600) -> pd.DataFrame

Batch export depth rasters for multiple plans with post-processing.

Wraps store_maps() for multiple plans, then applies depth threshold filtering and optional WGS84 reprojection.

Parameters

plan_numbers : list of str Plan numbers to export (e.g., ['01', '02', '03']) output_dir : str or Path Directory for processed output rasters min_depth : float, default 0.0 Minimum depth threshold. Cells below this become NoData. reproject_wgs84 : bool, default False If True, reproject outputs to EPSG:4326 naming_template : str, default '{plan}_{map_type}' Template for output file names. Supports {plan}, {map_type}. profile : str, default 'Max' Profile to export ('Max', 'Min', or timestamp) ras_object : optional Custom RAS object to use instead of the global one ras_version : str, optional HEC-RAS version for RasProcess.exe timeout : int, default 600 Timeout for each store_maps call

Returns

pd.DataFrame Report with columns: plan, map_type, source, output, cells_filtered, status

Example

report = RasProcess.batch_export_rasters( ... plan_numbers=['01', '02', '03'], ... output_dir='./exported_rasters', ... min_depth=0.75, ... reproject_wgs84=True ... ) print(report[['plan', 'cells_filtered', 'status']])

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def batch_export_rasters(
    plan_numbers: List[str],
    output_dir: Union[str, Path],
    min_depth: float = 0.0,
    reproject_wgs84: bool = False,
    naming_template: str = "{plan}_{map_type}",
    profile: str = "Max",
    ras_object=None,
    ras_version: str = None,
    timeout: int = 600,
) -> pd.DataFrame:
    """
    Batch export depth rasters for multiple plans with post-processing.

    Wraps store_maps() for multiple plans, then applies depth threshold
    filtering and optional WGS84 reprojection.

    Parameters
    ----------
    plan_numbers : list of str
        Plan numbers to export (e.g., ['01', '02', '03'])
    output_dir : str or Path
        Directory for processed output rasters
    min_depth : float, default 0.0
        Minimum depth threshold. Cells below this become NoData.
    reproject_wgs84 : bool, default False
        If True, reproject outputs to EPSG:4326
    naming_template : str, default '{plan}_{map_type}'
        Template for output file names. Supports {plan}, {map_type}.
    profile : str, default 'Max'
        Profile to export ('Max', 'Min', or timestamp)
    ras_object : optional
        Custom RAS object to use instead of the global one
    ras_version : str, optional
        HEC-RAS version for RasProcess.exe
    timeout : int, default 600
        Timeout for each store_maps call

    Returns
    -------
    pd.DataFrame
        Report with columns: plan, map_type, source, output,
        cells_filtered, status

    Example
    -------
    >>> report = RasProcess.batch_export_rasters(
    ...     plan_numbers=['01', '02', '03'],
    ...     output_dir='./exported_rasters',
    ...     min_depth=0.75,
    ...     reproject_wgs84=True
    ... )
    >>> print(report[['plan', 'cells_filtered', 'status']])
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

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

    report_rows = []

    for plan_num in plan_numbers:
        plan_num = RasUtils.normalize_ras_number(plan_num)

        # Generate raw TIFs via store_maps
        try:
            map_results = RasProcess.store_maps(
                plan_number=plan_num,
                profile=profile,
                depth=True,
                wse=True,
                velocity=False,
                ras_object=ras_obj,
                ras_version=ras_version,
                timeout=timeout,
            )
        except Exception as e:
            logger.error(f"store_maps failed for plan {plan_num}: {e}")
            report_rows.append(
                {
                    "plan": plan_num,
                    "map_type": "all",
                    "source": None,
                    "output": None,
                    "cells_filtered": 0,
                    "status": f"error: {e}",
                }
            )
            continue

        # Post-process each generated TIF
        for map_type, tif_list in map_results.items():
            for tif_path in tif_list:
                tif_path = Path(tif_path)
                if not tif_path.exists():
                    continue

                out_name = (
                    naming_template.format(plan=plan_num, map_type=map_type)
                    + ".tif"
                )
                out_path = output_path / out_name

                try:
                    if HAS_RASTERIO and (min_depth > 0 or reproject_wgs84):
                        result = RasProcess.apply_depth_threshold(
                            tif_path,
                            out_path,
                            min_depth=min_depth,
                            reproject_wgs84=reproject_wgs84,
                        )
                        cells_filtered = result["cells_filtered"]
                    else:
                        # Just copy the file
                        import shutil

                        shutil.copy2(tif_path, out_path)
                        cells_filtered = 0

                    report_rows.append(
                        {
                            "plan": plan_num,
                            "map_type": map_type,
                            "source": str(tif_path),
                            "output": str(out_path),
                            "cells_filtered": cells_filtered,
                            "status": "exported",
                        }
                    )
                except Exception as e:
                    logger.error(f"Post-processing failed for {tif_path.name}: {e}")
                    report_rows.append(
                        {
                            "plan": plan_num,
                            "map_type": map_type,
                            "source": str(tif_path),
                            "output": None,
                            "cells_filtered": 0,
                            "status": f"error: {e}",
                        }
                    )

    report = pd.DataFrame(report_rows)
    n_exported = (
        len(report[report["status"] == "exported"]) if not report.empty else 0
    )
    logger.info(
        f"Batch export: {n_exported} rasters exported for {len(plan_numbers)} plans"
    )
    return report

composite_rasters staticmethod

Python
composite_rasters(input_tiffs: List[Union[str, Path]], output_path: Union[str, Path], method: str = 'max', extent_mode: str = 'intersection', ras_object=None) -> Path

Composite multiple rasters using max, min, or mean method.

Parameters

input_tiffs : list of str or Path Paths to input GeoTIFF files output_path : str or Path Path for output composite raster method : str, default 'max' Compositing method: 'max', 'min', or 'mean' extent_mode : str, default 'intersection' How to handle differing extents: 'intersection' or 'union' ras_object : optional Custom RAS object (unused, for API consistency)

Returns

Path Path to the composite raster

Example

composite = RasProcess.composite_rasters( ... ['plan01_depth.tif', 'plan02_depth.tif', 'plan03_depth.tif'], ... 'composite_max_depth.tif', ... method='max' ... )

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def composite_rasters(
    input_tiffs: List[Union[str, Path]],
    output_path: Union[str, Path],
    method: str = "max",
    extent_mode: str = "intersection",
    ras_object=None,
) -> Path:
    """
    Composite multiple rasters using max, min, or mean method.

    Parameters
    ----------
    input_tiffs : list of str or Path
        Paths to input GeoTIFF files
    output_path : str or Path
        Path for output composite raster
    method : str, default 'max'
        Compositing method: 'max', 'min', or 'mean'
    extent_mode : str, default 'intersection'
        How to handle differing extents: 'intersection' or 'union'
    ras_object : optional
        Custom RAS object (unused, for API consistency)

    Returns
    -------
    Path
        Path to the composite raster

    Example
    -------
    >>> composite = RasProcess.composite_rasters(
    ...     ['plan01_depth.tif', 'plan02_depth.tif', 'plan03_depth.tif'],
    ...     'composite_max_depth.tif',
    ...     method='max'
    ... )
    """
    if not HAS_RASTERIO:
        raise ImportError(
            "rasterio is required for composite_rasters(). "
            "Install with: pip install rasterio"
        )
    from rasterio.merge import merge

    input_paths = [Path(p) for p in input_tiffs]
    out_path = Path(output_path)

    # Validate inputs exist
    for p in input_paths:
        if not p.exists():
            raise FileNotFoundError(f"Input TIFF not found: {p}")

    if len(input_paths) < 2:
        raise ValueError("At least 2 input rasters are required for compositing")

    # Validate CRS consistency
    datasets = [rasterio.open(p) for p in input_paths]
    try:
        crs_set = {str(ds.crs) for ds in datasets if ds.crs is not None}
        if len(crs_set) > 1:
            logger.warning(
                f"CRS mismatch across inputs: {crs_set}. "
                f"Results may be unreliable."
            )

        # Map method name to rasterio merge method
        if method == "max":
            merge_method = "max"
        elif method == "min":
            merge_method = "min"
        elif method == "mean":
            # rasterio doesn't have built-in mean, use manual approach
            merge_method = "max"  # placeholder, we'll handle mean separately
        else:
            raise ValueError(
                f"Unknown method '{method}'. Use 'max', 'min', or 'mean'."
            )

        if method == "mean":
            # Manual mean compositing
            # Read first raster for reference
            ref = datasets[0]
            bounds_list = [ds.bounds for ds in datasets]

            if extent_mode == "intersection":
                from rasterio.transform import from_bounds

                min_left = max(b.left for b in bounds_list)
                min_bottom = max(b.bottom for b in bounds_list)
                max_right = min(b.right for b in bounds_list)
                max_top = min(b.top for b in bounds_list)
            else:
                min_left = min(b.left for b in bounds_list)
                min_bottom = min(b.bottom for b in bounds_list)
                max_right = max(b.right for b in bounds_list)
                max_top = max(b.top for b in bounds_list)

            # Use first dataset's resolution
            res_x = ref.res[0]
            res_y = ref.res[1]
            width = int((max_right - min_left) / res_x)
            height = int((max_top - min_bottom) / res_y)

            from rasterio.transform import from_bounds as fb

            transform = fb(min_left, min_bottom, max_right, max_top, width, height)

            sum_data = np.zeros((height, width), dtype=np.float64)
            count_data = np.zeros((height, width), dtype=np.int32)

            from rasterio.warp import reproject as rio_reproject

            for ds in datasets:
                temp = np.full((height, width), np.nan, dtype=np.float64)
                rio_reproject(
                    source=rasterio.band(ds, 1),
                    destination=temp,
                    dst_transform=transform,
                    dst_crs=ref.crs,
                    dst_nodata=np.nan,
                )
                valid = ~np.isnan(temp)
                if ds.nodata is not None:
                    valid = valid & (temp != ds.nodata)
                sum_data[valid] += temp[valid]
                count_data[valid] += 1

            mean_data = np.where(
                count_data > 0, sum_data / count_data, ref.nodata or -9999.0
            )

            profile = ref.profile.copy()
            profile.update(
                transform=transform,
                width=width,
                height=height,
                dtype="float64",
                count=1,
            )
            out_path.parent.mkdir(parents=True, exist_ok=True)
            with rasterio.open(out_path, "w", **profile) as dst:
                dst.write(mean_data, 1)
        else:
            # Use rasterio merge for max/min
            bounds_mode = (
                "intersection" if extent_mode == "intersection" else "union"
            )
            merged, transform = merge(datasets, method=merge_method, bounds=None)

            profile = datasets[0].profile.copy()
            profile.update(
                transform=transform,
                width=merged.shape[2],
                height=merged.shape[1],
                count=1,
            )
            out_path.parent.mkdir(parents=True, exist_ok=True)
            with rasterio.open(out_path, "w", **profile) as dst:
                dst.write(merged[0], 1)

    finally:
        for ds in datasets:
            ds.close()

    logger.info(
        f"Composite raster ({method}): {len(input_paths)} inputs → {out_path.name}"
    )
    return out_path

composite_rasters_from_plans staticmethod

Python
composite_rasters_from_plans(plan_numbers: List[str], map_type: str = 'depth', output_path: Union[str, Path] = None, method: str = 'max', ras_object=None) -> Path

Composite stored map TIFs from multiple plans.

Finds stored map GeoTIFFs for each plan in the project folder, then delegates to composite_rasters().

Parameters

plan_numbers : list of str Plan numbers to composite (e.g., ['01', '02', '03']) map_type : str, default 'depth' Map type to composite (e.g., 'depth', 'wse', 'velocity') output_path : str or Path, optional Path for output composite. If None, auto-generated in project folder. method : str, default 'max' Compositing method: 'max', 'min', or 'mean' ras_object : optional Custom RAS object to use instead of the global one

Returns

Path Path to the composite raster

Example

composite = RasProcess.composite_rasters_from_plans( ... plan_numbers=['01', '02', '03'], ... map_type='depth', ... method='max' ... ) print(f"Composite saved to: {composite}")

Source code in ras_commander/RasProcess.py
Python
@staticmethod
@log_call
def composite_rasters_from_plans(
    plan_numbers: List[str],
    map_type: str = "depth",
    output_path: Union[str, Path] = None,
    method: str = "max",
    ras_object=None,
) -> Path:
    """
    Composite stored map TIFs from multiple plans.

    Finds stored map GeoTIFFs for each plan in the project folder,
    then delegates to composite_rasters().

    Parameters
    ----------
    plan_numbers : list of str
        Plan numbers to composite (e.g., ['01', '02', '03'])
    map_type : str, default 'depth'
        Map type to composite (e.g., 'depth', 'wse', 'velocity')
    output_path : str or Path, optional
        Path for output composite. If None, auto-generated in project folder.
    method : str, default 'max'
        Compositing method: 'max', 'min', or 'mean'
    ras_object : optional
        Custom RAS object to use instead of the global one

    Returns
    -------
    Path
        Path to the composite raster

    Example
    -------
    >>> composite = RasProcess.composite_rasters_from_plans(
    ...     plan_numbers=['01', '02', '03'],
    ...     map_type='depth',
    ...     method='max'
    ... )
    >>> print(f"Composite saved to: {composite}")
    """
    ras_obj = ras_object or ras
    ras_obj.check_initialized()

    # Search for TIFs matching map_type for each plan
    input_tiffs = []
    for plan_num in plan_numbers:
        plan_num = RasUtils.normalize_ras_number(plan_num)

        # Search in project folder and subdirectories
        search_patterns = [
            f"*{map_type}*{plan_num}*.tif",
            f"*p{plan_num}*{map_type}*.tif",
            f"*{map_type.capitalize()}*Max*.tif",
        ]

        found = False
        for pattern in search_patterns:
            matches = list(ras_obj.project_folder.rglob(pattern))
            if matches:
                # Use the most recently modified match
                best = max(matches, key=lambda p: p.stat().st_mtime)
                input_tiffs.append(best)
                logger.debug(f"Plan {plan_num}: found {best.name}")
                found = True
                break

        if not found:
            logger.warning(f"No {map_type} TIF found for plan {plan_num}")

    if len(input_tiffs) < 2:
        raise ValueError(
            f"Need at least 2 TIFs for compositing, found {len(input_tiffs)}. "
            f"Run store_maps() for each plan first."
        )

    if output_path is None:
        output_path = ras_obj.project_folder / f"composite_{map_type}_{method}.tif"

    return RasProcess.composite_rasters(
        input_tiffs=input_tiffs, output_path=output_path, method=method
    )