Skip to content

Fixit Module

Automated geometry repair for HEC-RAS models.

Overview

The fixit module provides automated fix capabilities for common HEC-RAS geometry issues. It complements the check module by providing repair functionality for detected issues.

Engineering Review Required

All fixes should be reviewed by a licensed professional engineer before accepting changes to production models. The visualization outputs provide an audit trail showing original and fixed configurations.

Supported Fixes

Fix Type Method Description
Blocked obstruction overlaps fix_blocked_obstructions() / detect_obstruction_overlaps() Elevation-envelope rewrite and spacing
HTAB starting elevations fix_htab_starting_elevations() / detect_htab_issues() Raise a starting elevation below the invert by the requested margin
Bank stations fix_bank_stations() / detect_bank_station_issues() Normalize station/elevation formatting and insert or snap bank points
Ineffective flow areas fix_ineffective_flow() / detect_ineffective_flow_issues() Repair the documented legacy right-station-zero sentinel case
Manning's n fix_mannings_n() / detect_mannings_n_issues() Reconstruct missing legacy values or align breakpoints with current banks

All five families operate on plain-text geometry. Writers default to backup=True and accept dry_run=True; detection wrappers use the corresponding dry-run path. Bank/ineffective/Manning writers also accept rs_list. The ineffective-area and Manning repairs target documented legacy upgrade patterns, not arbitrary geometry or roughness calibration. HTAB margin uses the source elevation units. Review the operation-specific messages before writing to a copy.

Dry-run total_xs_fixed counts proposed/targeted changes, not saved edits. Bank normalization can target every selected Type 1 cross section even when its values already appear correct. FixResults.get_fixed_count() counts non-NO_ACTION messages, which need not equal unique cross sections. to_dataframe() returns no columns when there are no messages.

For 2D mesh diagnostics and repair, use Meshing.

Quick Start

Python
from ras_commander import RasFixit

# Detect overlaps (non-destructive)
results = RasFixit.detect_obstruction_overlaps("model.g04")
print(f"Found {results.total_xs_fixed} cross sections with overlaps")

# Fix with visualization for engineering review
results = RasFixit.fix_blocked_obstructions(
    "model.g04",
    backup=True,      # Create timestamped backup
    visualize=True    # Generate before/after PNGs
)
print(f"Fixed {results.total_xs_fixed} cross sections")
print(f"Visualizations: {results.visualization_folder}")

RasFixit

RasFixit

Automated geometry repair for HEC-RAS models.

All methods are static and designed for geometry file path input. This follows the ras-commander convention of static classes.

Integration with RasCheck

RasCheck.check_xs() detects obstruction issues (XS_BO_01, XS_BO_02) RasFixit.fix_blocked_obstructions() repairs those issues

RasCheck.check_htab_params() detects HTAB issues (HTAB_SE_01) RasFixit.fix_htab_starting_elevations() repairs those issues

Example

from ras_commander import RasFixit, RasCheck

First detect issues

check_results = RasCheck.check_xs(geom_hdf) obstruction_issues = [m for m in check_results.messages ... if m.message_id.startswith('XS_BO')]

if obstruction_issues: ... # Then fix them ... fix_results = RasFixit.fix_blocked_obstructions( ... "model.g01", visualize=True ... ) ... print(f"Fixed {fix_results.total_xs_fixed} cross sections")

Source code in ras_commander/fixit/RasFixit.py
Python
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
class RasFixit:
    """
    Automated geometry repair for HEC-RAS models.

    All methods are static and designed for geometry file path input.
    This follows the ras-commander convention of static classes.

    Integration with RasCheck:
        RasCheck.check_xs() detects obstruction issues (XS_BO_01, XS_BO_02)
        RasFixit.fix_blocked_obstructions() repairs those issues

        RasCheck.check_htab_params() detects HTAB issues (HTAB_SE_01)
        RasFixit.fix_htab_starting_elevations() repairs those issues

    Example:
        >>> from ras_commander import RasFixit, RasCheck
        >>>
        >>> # First detect issues
        >>> check_results = RasCheck.check_xs(geom_hdf)
        >>> obstruction_issues = [m for m in check_results.messages
        ...                       if m.message_id.startswith('XS_BO')]
        >>>
        >>> if obstruction_issues:
        ...     # Then fix them
        ...     fix_results = RasFixit.fix_blocked_obstructions(
        ...         "model.g01", visualize=True
        ...     )
        ...     print(f"Fixed {fix_results.total_xs_fixed} cross sections")
    """

    @staticmethod
    @log_call
    def fix_blocked_obstructions(
        geom_path: Union[str, Path],
        backup: bool = True,
        visualize: bool = False,
        dry_run: bool = False
    ) -> FixResults:
        """
        Fix overlapping blocked obstructions in a geometry file.

        Uses max-elevation envelope algorithm to resolve overlaps while
        preserving conservative hydraulic behavior. Creates verification
        outputs for engineering review.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)
            backup: Create timestamped backup before modification (default True)
            visualize: Generate before/after PNG comparisons (default False)
            dry_run: Detect issues without modifying file (default False)

        Returns:
            FixResults with messages for each fixed cross section.
            Use results.to_dataframe() for pandas DataFrame output.

        Raises:
            FileNotFoundError: If geometry file doesn't exist.

        Example:
            >>> results = RasFixit.fix_blocked_obstructions(
            ...     "BaldEagle.g01",
            ...     backup=True,
            ...     visualize=True
            ... )
            >>> for msg in results.messages:
            ...     print(f"RS {msg.station}: {msg.action.value}")

        Note:
            The algorithm uses maximum elevations in overlap zones, which is
            hydraulically conservative (preserves flow restrictions).
            All changes should be reviewed by a licensed professional engineer.
        """
        geom_path = Path(geom_path)
        if not geom_path.exists():
            raise FileNotFoundError(f"Geometry file not found: {geom_path}")

        results = FixResults()

        # Create backup if requested and not dry run
        if backup and not dry_run:
            backup_path = RasFixit._create_backup(geom_path)
            results.backup_path = backup_path
            logger.info(f"Created backup: {backup_path}")

        from ..geom.GeomCrossSection import GeomCrossSection

        xs_df = GeomCrossSection.get_cross_sections(geom_path)
        results.total_xs_checked = len(xs_df)

        # Setup visualization folder if needed
        viz_folder = None
        if visualize and not dry_run:
            viz_folder = RasFixit._create_viz_folder(geom_path)
            results.visualization_folder = viz_folder
            logger.info(f"Saving visualizations to: {viz_folder}")

        obs_df = GeomCrossSection.get_blocked_obstructions(geom_path)
        if obs_df.empty:
            return results

        for xs_id, group in obs_df.groupby("xs_id", sort=False):
            original = [
                BlockedObstruction(row.start_sta, row.end_sta, row.elevation)
                for row in group.itertuples()
            ]

            if len(original) < 2 or not has_overlaps(original):
                continue

            fixed = create_elevation_envelope(original)
            first = group.iloc[0]
            river = str(first["River"])
            reach = str(first["Reach"])
            rs_id = str(first["RS"])

            msg = FixMessage(
                message_id="FX_BO_01",
                fix_type="OBSTRUCTION",
                river=river,
                reach=reach,
                station=rs_id,
                action=FixAction.OVERLAP_RESOLVED,
                message=(
                    f"Resolved {len(original)} overlapping obstructions to "
                    f"{len(fixed)} non-overlapping"
                ),
                original_count=len(original),
                fixed_count=len(fixed),
                original_data=[o.to_tuple() for o in original],
                fixed_data=[o.to_tuple() for o in fixed],
            )

            logger.debug(f"RS {rs_id}: {len(original)} -> {len(fixed)} obstructions")

            if viz_folder and not dry_run:
                viz_path = viz_folder / f"RS_{rs_id.replace('.', '_')}.png"
                msg.visualization_path = viz_path
                RasFixit._visualize(original, fixed, rs_id, viz_path)

            results.messages.append(msg)
            results.total_xs_fixed += 1

            if not dry_run:
                GeomCrossSection.set_blocked_obstructions(
                    geom_path,
                    xs_id,
                    fixed,
                    create_backup=False,
                )

        if not dry_run and results.total_xs_fixed > 0:
            logger.info(
                f"Fixed {results.total_xs_fixed} cross sections in {geom_path.name}"
            )

        return results

    @staticmethod
    @log_call
    def detect_obstruction_overlaps(geom_path: Union[str, Path]) -> FixResults:
        """
        Detect overlapping blocked obstructions without modifying the file.

        This is equivalent to fix_blocked_obstructions(dry_run=True).
        Useful for pre-flight checks before applying fixes.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)

        Returns:
            FixResults with detection messages (no modifications made).

        Example:
            >>> results = RasFixit.detect_obstruction_overlaps("model.g04")
            >>> print(f"Found {results.total_xs_fixed} cross sections with overlaps")
        """
        return RasFixit.fix_blocked_obstructions(
            geom_path, backup=False, visualize=False, dry_run=True
        )

    @staticmethod
    def _create_backup(geom_path: Path) -> Path:
        """Create timestamped backup of geometry file."""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        backup_path = geom_path.parent / f"{geom_path.name}.backup_{timestamp}"
        shutil.copy2(geom_path, backup_path)
        return backup_path

    @staticmethod
    def _create_viz_folder(geom_path: Path) -> Path:
        """Create visualization output folder."""
        # Extract geometry number
        g_match = re.search(r'\.g(\d+)(?:\.|$)', geom_path.name, re.IGNORECASE)
        g_num = g_match.group(1) if g_match else "XX"

        # Extract project name (everything before .g##)
        project_name = re.sub(r'\.g\d+.*', '', geom_path.name)

        # Create folder name: ProjectName_g##_Obstructions_Fixed
        dir_name = f"{project_name}_g{g_num}_Obstructions_Fixed"

        viz_folder = geom_path.parent / dir_name
        viz_folder.mkdir(exist_ok=True)

        return viz_folder

    @staticmethod
    def _visualize(
        original: List[BlockedObstruction],
        fixed: List[BlockedObstruction],
        rs_id: str,
        save_path: Path
    ) -> bool:
        """
        Generate before/after visualization PNG.

        Lazy loads matplotlib to avoid import overhead when visualization
        is not requested.

        Args:
            original: Original overlapping obstructions.
            fixed: Fixed non-overlapping obstructions.
            rs_id: River station identifier.
            save_path: Output PNG path.

        Returns:
            True if visualization was created, False otherwise.
        """
        from .visualization import visualize_obstruction_fix
        return visualize_obstruction_fix(original, fixed, rs_id, save_path)

    # =========================================================================
    # HTAB (Hydraulic Table) Fixes
    # =========================================================================

    @staticmethod
    @log_call
    def fix_htab_starting_elevations(
        geom_path: Union[str, Path],
        backup: bool = True,
        dry_run: bool = False,
        margin: float = 0.0
    ) -> FixResults:
        """
        Fix HTAB starting elevation issues in a geometry file.

        HTAB (Hydraulic Table) starting elevation must be >= cross section invert.
        This is a hard HEC-RAS requirement - models with starting_el < invert will
        fail during preprocessing (common issue when upgrading from older HEC-RAS versions).

        This method identifies all cross sections where starting_el < invert and
        automatically corrects them by setting starting_el = invert + margin.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)
            backup: Create timestamped backup before modification (default True)
            dry_run: Detect issues without modifying file (default False)
            margin: Additional margin above invert for starting elevation (default 0.0 ft)
                   Use small positive value (e.g., 0.1) for extra safety margin.

        Returns:
            FixResults with messages for each fixed cross section.
            - total_xs_checked: Number of XS with HTAB parameters examined
            - total_xs_fixed: Number of XS with starting_el corrected
            - messages: List of FixMessage objects with before/after values
            Use results.to_dataframe() for pandas DataFrame output.

        Raises:
            FileNotFoundError: If geometry file doesn't exist.

        Example:
            >>> from ras_commander import RasFixit
            >>>
            >>> # Fix all HTAB starting elevation issues
            >>> results = RasFixit.fix_htab_starting_elevations("model.g01")
            >>> print(f"Fixed {results.total_xs_fixed} cross sections")
            >>>
            >>> # Detection only (no modifications)
            >>> results = RasFixit.fix_htab_starting_elevations(
            ...     "model.g01", dry_run=True
            ... )
            >>> print(f"Found {results.total_xs_fixed} cross sections with issues")
            >>>
            >>> # View details
            >>> df = results.to_dataframe()
            >>> print(df[['river', 'reach', 'station', 'message']])

        Note:
            This fix is required after HEC-RAS version upgrades or when importing
            geometry from external sources. HEC-RAS will fail with an error during
            geometry preprocessing if starting_el < invert.

        Integration with RasCheck:
            RasCheck.check_htab_params() detects HTAB_SE_01 errors (starting_el < invert)
            RasFixit.fix_htab_starting_elevations() repairs those issues

        See Also:
            - GeomCrossSection.get_xs_htab_params(): Read HTAB parameters
            - GeomCrossSection.set_xs_htab_params(): Write HTAB parameters
            - RasCheck.check_htab_params(): Validate HTAB parameters
        """
        from ..geom.GeomCrossSection import GeomCrossSection

        geom_path = Path(geom_path)
        if not geom_path.exists():
            raise FileNotFoundError(f"Geometry file not found: {geom_path}")

        results = FixResults()

        # Create backup if requested and not dry run
        if backup and not dry_run:
            backup_path = RasFixit._create_backup(geom_path)
            results.backup_path = backup_path
            logger.info(f"Created backup: {backup_path}")

        try:
            # Get all cross sections from geometry file
            xs_df = GeomCrossSection.get_cross_sections(geom_path)
            # Filter to Type 1 (real cross sections) only - excludes lateral
            # structures (Type 6), bridges, culverts, etc. which lack #Sta/Elev data
            if 'Type' in xs_df.columns:
                xs_df = xs_df[xs_df['Type'] == 1].reset_index(drop=True)

            if xs_df.empty:
                logger.info(f"No cross sections found in {geom_path.name}")
                return results

            logger.info(f"Checking HTAB starting elevations for {len(xs_df)} cross sections")

            xs_to_fix = []  # List of dicts with fix info

            for _, row in xs_df.iterrows():
                river = row['River']
                reach = row['Reach']
                rs = row['RS']

                try:
                    # Get HTAB parameters for this XS
                    htab_params = GeomCrossSection.get_xs_htab_params(
                        geom_path, river, reach, rs
                    )

                    starting_el = htab_params.get('starting_el')
                    invert = htab_params.get('invert')

                    # Skip if no HTAB params or no starting elevation defined
                    if starting_el is None or invert is None:
                        continue

                    results.total_xs_checked += 1

                    # Check if starting_el < invert (ERROR condition)
                    if starting_el < invert:
                        corrected_starting_el = invert + margin
                        xs_to_fix.append({
                            'river': river,
                            'reach': reach,
                            'rs': rs,
                            'original_starting_el': starting_el,
                            'invert': invert,
                            'corrected_starting_el': corrected_starting_el,
                            'increment': htab_params.get('increment'),
                            'num_points': htab_params.get('num_points')
                        })

                        # Create fix message
                        msg = FixMessage(
                            message_id="FX_HTAB_01",
                            fix_type="HTAB",
                            river=river,
                            reach=reach,
                            station=str(rs),
                            action=FixAction.HTAB_STARTING_EL_FIXED,
                            message=(
                                f"HTAB starting elevation corrected from {starting_el:.2f} "
                                f"to {corrected_starting_el:.2f} (invert={invert:.2f})"
                            ),
                            original_data=[(starting_el, invert, 0.0)],
                            fixed_data=[(corrected_starting_el, invert, 0.0)]
                        )
                        results.messages.append(msg)

                        logger.debug(
                            f"{river}/{reach}/RS {rs}: starting_el {starting_el:.2f} -> "
                            f"{corrected_starting_el:.2f} (invert={invert:.2f})"
                        )

                except Exception as e:
                    logger.warning(f"Error checking HTAB for {river}/{reach}/RS {rs}: {e}")
                    continue

            results.total_xs_fixed = len(xs_to_fix)

            # Apply fixes if not dry run
            if not dry_run and xs_to_fix:
                logger.info(f"Applying fixes to {len(xs_to_fix)} cross sections")

                for xs_info in xs_to_fix:
                    try:
                        GeomCrossSection.set_xs_htab_params(
                            geom_path,
                            xs_info['river'],
                            xs_info['reach'],
                            xs_info['rs'],
                            starting_el=xs_info['corrected_starting_el'],
                            increment=xs_info['increment'],
                            num_points=xs_info['num_points']
                        )
                    except Exception as e:
                        logger.error(
                            f"Failed to fix HTAB for {xs_info['river']}/{xs_info['reach']}/"
                            f"RS {xs_info['rs']}: {e}"
                        )

                logger.info(
                    f"Fixed HTAB starting elevations for {len(xs_to_fix)} cross sections "
                    f"in {geom_path.name}"
                )
            elif dry_run and xs_to_fix:
                logger.info(
                    f"Dry run: Found {len(xs_to_fix)} cross sections with HTAB starting_el < invert"
                )

            # Add statistics
            results.statistics = {
                'total_xs_in_file': len(xs_df),
                'xs_with_htab': results.total_xs_checked,
                'xs_with_issues': results.total_xs_fixed,
                'margin_used': margin
            }

        except Exception as e:
            logger.error(f"Failed to fix HTAB starting elevations: {e}")
            raise

        return results

    @staticmethod
    @log_call
    def detect_htab_issues(geom_path: Union[str, Path]) -> FixResults:
        """
        Detect HTAB starting elevation issues without modifying the file.

        This is equivalent to fix_htab_starting_elevations(dry_run=True).
        Useful for pre-flight checks before applying fixes.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)

        Returns:
            FixResults with detection messages (no modifications made).

        Example:
            >>> results = RasFixit.detect_htab_issues("model.g01")
            >>> print(f"Found {results.total_xs_fixed} cross sections with HTAB issues")
            >>> for msg in results.messages:
            ...     print(f"  {msg.river}/{msg.reach}/RS {msg.station}: {msg.message}")
        """
        return RasFixit.fix_htab_starting_elevations(
            geom_path, backup=False, dry_run=True
        )

    # ========== BANK STATION FIXES ==========

    @staticmethod
    @log_call
    def fix_bank_stations(
        geom_path: Union[str, Path],
        backup: bool = True,
        dry_run: bool = False,
        rs_list: Optional[List[str]] = None
    ) -> FixResults:
        """
        Fix bank station / station-elevation data for cross sections.

        **Version upgrade fix (HEC-RAS 4.x → 6.x).** Also safe as a general-purpose
        normalization pass on any model version.

        Re-writes station/elevation data through set_station_elevation() which
        normalizes fixed-width formatting (all values to {:8.2f}) and ensures
        bank stations appear as exact points via _interpolate_at_banks(). Existing
        points within 0.005 units of a bank station are snapped to the exact bank
        value rather than inserting a near-duplicate.

        HEC-RAS 6.x has stricter validation than 4.x for bank station matching.
        A round-trip rewrite normalizes the FORTRAN fixed-width format, resolving
        mismatches that are invisible to value-based comparisons.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)
            backup: Create timestamped backup before modification (default True)
            dry_run: Detect issues without modifying file (default False)
            rs_list: Optional list of RS values to fix. If None, fixes all
                     Type 1 cross sections (full normalization).

        Returns:
            FixResults with messages for each cross section targeted.

        Raises:
            FileNotFoundError: If geometry file doesn't exist.

        Example:
            >>> # Fix specific cross sections from RAS error report
            >>> results = RasFixit.fix_bank_stations(
            ...     "model.g01",
            ...     rs_list=["76202", "70462", "68673"]
            ... )
            >>> print(f"Fixed {results.total_xs_fixed} cross sections")

        Note:
            This fix targets models upgraded from HEC-RAS 4.x to 6.x, but the
            normalization is also safe for any model version. All changes should
            be reviewed by a licensed professional engineer.
        """
        from ..geom.GeomCrossSection import GeomCrossSection

        geom_path = Path(geom_path)
        if not geom_path.exists():
            raise FileNotFoundError(f"Geometry file not found: {geom_path}")

        results = FixResults()

        # Create backup if requested and not dry run
        if backup and not dry_run:
            backup_path = RasFixit._create_backup(geom_path)
            results.backup_path = backup_path
            logger.info(f"Created backup: {backup_path}")

        try:
            # Get all cross sections
            xs_df_all = GeomCrossSection.get_cross_sections(geom_path)

            # Filter to Type 1 (natural cross sections only)
            xs_df = xs_df_all[xs_df_all['Type'] == 1]

            # Filter to specific RS values if provided
            if rs_list is not None:
                rs_set = set(str(r).strip() for r in rs_list)
                xs_df = xs_df[xs_df['RS'].apply(
                    lambda x: str(x).strip() in rs_set
                )]

            results.total_xs_checked = len(xs_df)
            xs_to_fix = []

            for _, row in xs_df.iterrows():
                river = row['River']
                reach = row['Reach']
                rs = str(row['RS'])

                try:
                    banks = GeomCrossSection.get_bank_stations(
                        geom_path, river, reach, rs
                    )
                    if banks is None:
                        continue

                    bank_left, bank_right = banks

                    msg = FixMessage(
                        message_id="FX_BK_01",
                        fix_type="BANK_STATION",
                        river=river,
                        reach=reach,
                        station=rs,
                        action=FixAction.BANK_STATION_REWRITTEN,
                        message=(
                            f"Rewriting sta/elev with normalized formatting. "
                            f"Banks: L={bank_left}, R={bank_right}"
                        )
                    )
                    results.messages.append(msg)
                    xs_to_fix.append((river, reach, rs, bank_left, bank_right))

                except Exception as e:
                    logger.warning(f"Error reading {river}/{reach}/RS {rs}: {e}")
                    continue

            # Apply fixes if not dry run
            if not dry_run and xs_to_fix:
                for river, reach, rs, bank_left, bank_right in xs_to_fix:
                    try:
                        sta_elev = GeomCrossSection.get_station_elevation(
                            geom_path, river, reach, rs
                        )
                        GeomCrossSection.set_station_elevation(
                            geom_path, river, reach, rs, sta_elev,
                            bank_left=bank_left, bank_right=bank_right
                        )
                        results.total_xs_fixed += 1
                        logger.debug(
                            f"Normalized {river}/{reach}/RS {rs}"
                        )
                    except Exception as e:
                        logger.error(
                            f"Failed to fix {river}/{reach}/RS {rs}: {e}"
                        )
            elif dry_run:
                results.total_xs_fixed = len(xs_to_fix)
                logger.info(
                    f"Dry run: {len(xs_to_fix)} cross sections to normalize"
                )

            results.statistics = {
                'total_xs_in_file': len(xs_df_all),
                'xs_targeted': results.total_xs_checked,
                'xs_fixed': len(xs_to_fix)
            }

        except Exception as e:
            logger.error(f"Failed to fix bank stations: {e}")
            raise

        return results

    @staticmethod
    @log_call
    def detect_bank_station_issues(
        geom_path: Union[str, Path]
    ) -> FixResults:
        """
        Detect bank station formatting issues without modifying the file (dry run).

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)

        Returns:
            FixResults with messages for each cross section that would be normalized.
        """
        return RasFixit.fix_bank_stations(geom_path, backup=False, dry_run=True)

    # ========== INEFFECTIVE FLOW AREA FIXES ==========

    @staticmethod
    @log_call
    def fix_ineffective_flow(
        geom_path: Union[str, Path],
        backup: bool = True,
        dry_run: bool = False,
        rs_list: Optional[List[str]] = None
    ) -> FixResults:
        """
        Fix malformed ineffective flow area data in HEC-RAS geometry files.

        **Version upgrade fix (HEC-RAS 4.x → 6.x).** Not applicable to models
        originally created in HEC-RAS 6.x.

        HEC-RAS 4.x accepted ``0`` as a sentinel station value meaning "extend
        to the cross section boundary." HEC-RAS 6.x treats ``0`` literally,
        creating backwards pairs (left_station > right_station) that fail
        data check validation with misleading "Bank station not in sta/elev
        data" cascade errors.

        This method scans all Type 1 cross sections for ``#XS Ineff=`` blocks
        where any triplet has ``right_station == 0`` AND ``left_station > 0``.
        The fix replaces ``right_station = 0`` with the actual rightmost station
        from the cross section's sta/elev data.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)
            backup: Create timestamped backup before modification (default True)
            dry_run: Detect issues without modifying file (default False)
            rs_list: Optional list of RS values to check. If None, checks all
                     Type 1 cross sections.

        Returns:
            FixResults with messages for each modified cross section.

        Raises:
            FileNotFoundError: If geometry file doesn't exist.

        Example:
            >>> results = RasFixit.fix_ineffective_flow(
            ...     "model.g01",
            ...     backup=True
            ... )
            >>> print(f"Fixed {results.total_xs_fixed} cross sections")
            >>> for msg in results.messages:
            ...     print(f"  RS {msg.station}: {msg.message}")

        Note:
            This fix targets models upgraded from HEC-RAS 4.x to 6.x, or models
            converted from HEC-2. The right_station=0 sentinel pattern does not
            occur in models originally created in HEC-RAS 6.x. All changes should
            be reviewed by a licensed professional engineer.
        """
        from ..geom.GeomCrossSection import GeomCrossSection

        geom_path = Path(geom_path)
        if not geom_path.exists():
            raise FileNotFoundError(f"Geometry file not found: {geom_path}")

        results = FixResults()

        if backup and not dry_run:
            backup_path = RasFixit._create_backup(geom_path)
            results.backup_path = backup_path
            logger.info(f"Created backup: {backup_path}")

        try:
            xs_df_all = GeomCrossSection.get_cross_sections(geom_path)
            xs_df = xs_df_all[xs_df_all['Type'] == 1]

            if rs_list is not None:
                rs_set = set(str(r).strip() for r in rs_list)
                xs_df = xs_df[xs_df['RS'].apply(lambda x: str(x).strip() in rs_set)]

            results.total_xs_checked = len(xs_df)
            xs_to_fix = []

            for _, row in xs_df.iterrows():
                river = row['River']
                reach = row['Reach']
                rs = str(row['RS'])

                try:
                    ineff_df, fmt_flag, perm_flags = GeomCrossSection.get_ineffective_flow(
                        geom_path, river, reach, rs
                    )
                    if ineff_df is None:
                        continue

                    # Find pairs where right_station=0 and left_station > 0
                    # (backwards pair: 4.x sentinel -> 6.x takes 0 literally)
                    bad_mask = (ineff_df['right_station'] == 0) & (ineff_df['left_station'] > 0)
                    if not bad_mask.any():
                        continue

                    # Get rightmost station from sta/elev data
                    sta_elev = GeomCrossSection.get_station_elevation(
                        geom_path, river, reach, rs
                    )
                    rightmost = float(sta_elev['Station'].max())

                    bad_rows = ineff_df[bad_mask]
                    details = "; ".join(
                        f"pair({r['left_station']:.2f}->0) fixed to {rightmost:.2f}"
                        for _, r in bad_rows.iterrows()
                    )

                    msg = FixMessage(
                        message_id="FX_IF_01",
                        fix_type="INEFFECTIVE",
                        river=river,
                        reach=reach,
                        station=rs,
                        action=FixAction.INEFFECTIVE_FIXED,
                        message=(
                            f"right_station=0 replaced with rightmost sta {rightmost:.2f}. "
                            f"{details}"
                        ),
                        original_count=len(ineff_df),
                        fixed_count=len(ineff_df),
                        original_data=[
                            (r['left_station'], r['right_station'], r['elevation'])
                            for _, r in ineff_df.iterrows()
                        ]
                    )
                    results.messages.append(msg)
                    xs_to_fix.append(
                        (river, reach, rs, ineff_df.copy(), fmt_flag, perm_flags, rightmost)
                    )

                except Exception as e:
                    logger.warning(f"Error checking {river}/{reach}/RS {rs}: {e}")
                    continue

            if not dry_run and xs_to_fix:
                for river, reach, rs, ineff_df, fmt_flag, perm_flags, rightmost in xs_to_fix:
                    try:
                        fixed_df = ineff_df.copy()
                        bad_mask = (
                            (fixed_df['right_station'] == 0) & (fixed_df['left_station'] > 0)
                        )
                        fixed_df.loc[bad_mask, 'right_station'] = rightmost

                        GeomCrossSection.set_ineffective_flow(
                            geom_path, river, reach, rs,
                            fixed_df, fmt_flag, perm_flags
                        )
                        results.total_xs_fixed += 1
                        logger.debug(
                            f"Fixed ineffective flow for {river}/{reach}/RS {rs}: "
                            f"right_station=0 -> {rightmost:.2f}"
                        )

                        # Update message with fixed_data
                        for msg in results.messages:
                            if msg.station.strip() == rs.strip():
                                msg.fixed_data = [
                                    (r['left_station'], r['right_station'], r['elevation'])
                                    for _, r in fixed_df.iterrows()
                                ]
                                break

                    except Exception as e:
                        logger.error(f"Failed to fix {river}/{reach}/RS {rs}: {e}")

            elif dry_run:
                results.total_xs_fixed = len(xs_to_fix)
                logger.info(
                    f"Dry run: {len(xs_to_fix)} cross sections have right_station=0 "
                    "in ineffective flow areas"
                )

            results.statistics = {
                'total_xs_in_file': len(xs_df_all),
                'xs_with_ineff_checked': results.total_xs_checked,
                'xs_fixed': results.total_xs_fixed
            }

        except Exception as e:
            logger.error(f"Failed to fix ineffective flow: {e}")
            raise

        return results

    @staticmethod
    @log_call
    def detect_ineffective_flow_issues(
        geom_path: Union[str, Path]
    ) -> FixResults:
        """
        Detect cross sections with malformed ineffective flow area data (dry run).

        Args:
            geom_path: Path to HEC-RAS geometry file.

        Returns:
            FixResults with messages for each cross section that would be fixed.
        """
        return RasFixit.fix_ineffective_flow(geom_path, backup=False, dry_run=True)

    # ========== MANNING'S N FIXES ==========

    @staticmethod
    @log_call
    def fix_mannings_n(
        geom_path: Union[str, Path],
        backup: bool = True,
        dry_run: bool = False,
        rs_list: Optional[List[str]] = None
    ) -> FixResults:
        """
        Fix Manning's n data for cross sections with missing or misaligned breakpoints.

        **Version upgrade fix (HEC-RAS 4.x → 6.x).** Not applicable to models
        originally created in HEC-RAS 6.x.

        Handles two categories of Manning's n errors common after HEC-RAS version
        upgrades (4.x to 6.x):

        1. **Missing data** (``#Mann= 0``): Reconstructs 3-breakpoint (LOB/MC/ROB)
           Manning's n using distance-weighted linear interpolation from the nearest
           upstream and downstream Type 1 cross sections that have valid data.

        2. **Misaligned breakpoints**: When RAS 6.6's version upgrade moved bank
           stations but left Manning's breakpoints at the old positions, snaps the
           MC and ROB breakpoints to the current bank station values.

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)
            backup: Create timestamped backup before modification (default True)
            dry_run: Detect issues without modifying file (default False)
            rs_list: Optional list of RS values to check. If None, checks all
                     Type 1 cross sections.

        Returns:
            FixResults with messages for each modified cross section.

        Raises:
            FileNotFoundError: If geometry file doesn't exist.

        Example:
            >>> results = RasFixit.fix_mannings_n("model.g01")
            >>> print(f"Fixed {results.total_xs_fixed} cross sections")

        Note:
            This fix targets models upgraded from HEC-RAS 4.x to 6.x where the
            version upgrade zeroed out or misaligned Manning's n breakpoints.
            All changes should be reviewed by a licensed professional engineer.
        """
        from ..geom.GeomCrossSection import GeomCrossSection
        import numpy as np
        import pandas as pd

        geom_path = Path(geom_path)
        if not geom_path.exists():
            raise FileNotFoundError(f"Geometry file not found: {geom_path}")

        results = FixResults()

        if backup and not dry_run:
            backup_path = RasFixit._create_backup(geom_path)
            results.backup_path = backup_path
            logger.info(f"Created backup: {backup_path}")

        try:
            xs_df = GeomCrossSection.get_cross_sections(geom_path)
            xs_type1 = xs_df[xs_df['Type'] == 1].copy()
            xs_type1['RS_num'] = xs_type1['RS'].str.strip().astype(float)
            xs_type1 = xs_type1.sort_values('RS_num', ascending=False).reset_index(drop=True)

            if rs_list is not None:
                rs_set = set(str(r).strip() for r in rs_list)
                check_df = xs_type1[xs_type1['RS'].apply(lambda x: str(x).strip() in rs_set)]
            else:
                check_df = xs_type1

            results.total_xs_checked = len(check_df)
            xs_to_fix = []

            def _extract_lob_mc_rob(mann_df):
                """Extract LOB/MC/ROB n-values from a Manning's DataFrame."""
                if mann_df is None or len(mann_df) == 0:
                    return None
                if 'Subsection' in mann_df.columns:
                    lob = mann_df[mann_df['Subsection'] == 'LOB']
                    mc = mann_df[mann_df['Subsection'] == 'Channel']
                    rob = mann_df[mann_df['Subsection'] == 'ROB']
                    lob_n = lob['n_value'].iloc[0] if len(lob) > 0 else mann_df.iloc[0]['n_value']
                    mc_n = mc['n_value'].iloc[0] if len(mc) > 0 else mann_df.iloc[1]['n_value'] if len(mann_df) > 1 else lob_n
                    rob_n = rob['n_value'].iloc[0] if len(rob) > 0 else mann_df.iloc[-1]['n_value']
                else:
                    lob_n = mann_df.iloc[0]['n_value']
                    mc_n = mann_df.iloc[1]['n_value'] if len(mann_df) > 1 else lob_n
                    rob_n = mann_df.iloc[-1]['n_value']
                return lob_n, mc_n, rob_n

            def _find_neighbor_with_mann(idx, direction):
                """Find nearest Type 1 XS with valid Manning's data."""
                step = -1 if direction == 'upstream' else 1
                k = idx + step
                while 0 <= k < len(xs_type1):
                    row = xs_type1.iloc[k]
                    r, rch, rs_val = row['River'], row['Reach'], str(row['RS'])
                    try:
                        m = GeomCrossSection.get_mannings_n(
                            geom_path, r, rch, rs_val
                        )
                        if m is not None and len(m) > 0:
                            return row, m
                    except Exception:
                        pass
                    k += step
                return None, None

            for _, row in check_df.iterrows():
                river = row['River']
                reach = row['Reach']
                rs = str(row['RS'])
                rs_num = float(rs.strip())
                idx = xs_type1.index[xs_type1['RS_num'] == rs_num].tolist()
                if not idx:
                    continue
                idx = idx[0]

                try:
                    banks = GeomCrossSection.get_bank_stations(
                        geom_path, river, reach, rs
                    )
                    if banks is None:
                        continue
                    bank_left, bank_right = banks

                    mann = GeomCrossSection.get_mannings_n(
                        geom_path, river, reach, rs
                    )

                    if mann is None or len(mann) == 0:
                        # Category A: Missing data — reconstruct from neighbors
                        up_row, up_mann = _find_neighbor_with_mann(idx, 'upstream')
                        dn_row, dn_mann = _find_neighbor_with_mann(idx, 'downstream')

                        if up_mann is None or dn_mann is None:
                            logger.warning(
                                f"Cannot interpolate Mann for RS {rs}: "
                                f"missing {'upstream' if up_mann is None else 'downstream'} neighbor"
                            )
                            continue

                        up_vals = _extract_lob_mc_rob(up_mann)
                        dn_vals = _extract_lob_mc_rob(dn_mann)
                        if up_vals is None or dn_vals is None:
                            continue

                        up_rs = float(str(up_row['RS']).strip())
                        dn_rs = float(str(dn_row['RS']).strip())
                        dist_ue = up_rs - rs_num
                        dist_ed = rs_num - dn_rs

                        if dist_ue + dist_ed <= 0:
                            continue

                        w_u = dist_ed / (dist_ue + dist_ed)
                        w_d = dist_ue / (dist_ue + dist_ed)

                        lob_n = round(w_u * up_vals[0] + w_d * dn_vals[0], 4)
                        mc_n = round(w_u * up_vals[1] + w_d * dn_vals[1], 4)
                        rob_n = round(w_u * up_vals[2] + w_d * dn_vals[2], 4)

                        # LOB breakpoint = leftmost sta/elev station
                        sta_elev = GeomCrossSection.get_station_elevation(
                            geom_path, river, reach, rs
                        )
                        lob_sta = float(sta_elev['Station'].min())

                        new_mann = pd.DataFrame({
                            'Station': [lob_sta, bank_left, bank_right],
                            'n_value': [lob_n, mc_n, rob_n]
                        })

                        msg = FixMessage(
                            message_id="FX_MN_01",
                            fix_type="MANNINGS_N",
                            river=river,
                            reach=reach,
                            station=rs,
                            action=FixAction.MANNINGS_N_REWRITTEN,
                            message=(
                                f"Reconstructed from neighbors: "
                                f"LOB={lob_n:.3f} (U:{up_vals[0]:.3f}/D:{dn_vals[0]:.3f}), "
                                f"MC={mc_n:.3f} (U:{up_vals[1]:.3f}/D:{dn_vals[1]:.3f}), "
                                f"ROB={rob_n:.3f} (U:{up_vals[2]:.3f}/D:{dn_vals[2]:.3f}). "
                                f"Weights: U={w_u:.3f}, D={w_d:.3f}"
                            )
                        )
                        results.messages.append(msg)
                        xs_to_fix.append((river, reach, rs, new_mann))

                    elif len(mann) >= 3:
                        # Check if breakpoints match bank stations
                        mann_stations = mann['Station'].values
                        # MC breakpoint should be at left bank
                        mc_diff = abs(mann_stations[1] - bank_left)
                        # ROB breakpoint should be at right bank
                        rob_diff = abs(mann_stations[-1] - bank_right)

                        if mc_diff > 0.01 or rob_diff > 0.01:
                            # Category B: Misaligned — snap to banks
                            new_mann = pd.DataFrame({
                                'Station': [mann_stations[0], bank_left, bank_right],
                                'n_value': [
                                    mann.iloc[0]['n_value'],
                                    mann.iloc[1]['n_value'],
                                    mann.iloc[-1]['n_value']
                                ]
                            })

                            msg = FixMessage(
                                message_id="FX_MN_02",
                                fix_type="MANNINGS_N",
                                river=river,
                                reach=reach,
                                station=rs,
                                action=FixAction.MANNINGS_N_REWRITTEN,
                                message=(
                                    f"Snapped breakpoints to banks: "
                                    f"MC {mann_stations[1]:.2f}->{bank_left:.2f} "
                                    f"(diff={mc_diff:.2f}), "
                                    f"ROB {mann_stations[-1]:.2f}->{bank_right:.2f} "
                                    f"(diff={rob_diff:.2f})"
                                )
                            )
                            results.messages.append(msg)
                            xs_to_fix.append((river, reach, rs, new_mann))

                except Exception as e:
                    logger.warning(f"Error checking {river}/{reach}/RS {rs}: {e}")
                    continue

            if not dry_run and xs_to_fix:
                for river, reach, rs, new_mann in xs_to_fix:
                    try:
                        GeomCrossSection.set_mannings_n(
                            geom_path, river, reach, rs, new_mann,
                            format_flag=0, change_flag=0
                        )
                        results.total_xs_fixed += 1
                        logger.debug(f"Fixed Manning's n for {river}/{reach}/RS {rs}")
                    except Exception as e:
                        logger.error(f"Failed to fix {river}/{reach}/RS {rs}: {e}")

            elif dry_run:
                results.total_xs_fixed = len(xs_to_fix)
                logger.info(
                    f"Dry run: {len(xs_to_fix)} cross sections need Manning's n fixes"
                )

            results.statistics = {
                'xs_checked': results.total_xs_checked,
                'xs_fixed': results.total_xs_fixed,
                'reconstructed': len([m for m in results.messages if m.message_id == "FX_MN_01"]),
                'realigned': len([m for m in results.messages if m.message_id == "FX_MN_02"])
            }

        except Exception as e:
            logger.error(f"Failed to fix Manning's n: {e}")
            raise

        return results

    @staticmethod
    @log_call
    def detect_mannings_n_issues(
        geom_path: Union[str, Path]
    ) -> FixResults:
        """
        Detect Manning's n issues without modifying the file (dry run).

        Args:
            geom_path: Path to HEC-RAS geometry file (.g##)

        Returns:
            FixResults with messages for each cross section that would be fixed.
        """
        return RasFixit.fix_mannings_n(geom_path, backup=False, dry_run=True)

fix_blocked_obstructions staticmethod

Python
fix_blocked_obstructions(geom_path: Union[str, Path], backup: bool = True, visualize: bool = False, dry_run: bool = False) -> FixResults

Fix overlapping blocked obstructions in a geometry file.

Uses max-elevation envelope algorithm to resolve overlaps while preserving conservative hydraulic behavior. Creates verification outputs for engineering review.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required
backup bool

Create timestamped backup before modification (default True)

True
visualize bool

Generate before/after PNG comparisons (default False)

False
dry_run bool

Detect issues without modifying file (default False)

False

Returns:

Type Description
FixResults

FixResults with messages for each fixed cross section.

FixResults

Use results.to_dataframe() for pandas DataFrame output.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist.

Example

results = RasFixit.fix_blocked_obstructions( ... "BaldEagle.g01", ... backup=True, ... visualize=True ... ) for msg in results.messages: ... print(f"RS {msg.station}: {msg.action.value}")

Note

The algorithm uses maximum elevations in overlap zones, which is hydraulically conservative (preserves flow restrictions). All changes should be reviewed by a licensed professional engineer.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def fix_blocked_obstructions(
    geom_path: Union[str, Path],
    backup: bool = True,
    visualize: bool = False,
    dry_run: bool = False
) -> FixResults:
    """
    Fix overlapping blocked obstructions in a geometry file.

    Uses max-elevation envelope algorithm to resolve overlaps while
    preserving conservative hydraulic behavior. Creates verification
    outputs for engineering review.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)
        backup: Create timestamped backup before modification (default True)
        visualize: Generate before/after PNG comparisons (default False)
        dry_run: Detect issues without modifying file (default False)

    Returns:
        FixResults with messages for each fixed cross section.
        Use results.to_dataframe() for pandas DataFrame output.

    Raises:
        FileNotFoundError: If geometry file doesn't exist.

    Example:
        >>> results = RasFixit.fix_blocked_obstructions(
        ...     "BaldEagle.g01",
        ...     backup=True,
        ...     visualize=True
        ... )
        >>> for msg in results.messages:
        ...     print(f"RS {msg.station}: {msg.action.value}")

    Note:
        The algorithm uses maximum elevations in overlap zones, which is
        hydraulically conservative (preserves flow restrictions).
        All changes should be reviewed by a licensed professional engineer.
    """
    geom_path = Path(geom_path)
    if not geom_path.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_path}")

    results = FixResults()

    # Create backup if requested and not dry run
    if backup and not dry_run:
        backup_path = RasFixit._create_backup(geom_path)
        results.backup_path = backup_path
        logger.info(f"Created backup: {backup_path}")

    from ..geom.GeomCrossSection import GeomCrossSection

    xs_df = GeomCrossSection.get_cross_sections(geom_path)
    results.total_xs_checked = len(xs_df)

    # Setup visualization folder if needed
    viz_folder = None
    if visualize and not dry_run:
        viz_folder = RasFixit._create_viz_folder(geom_path)
        results.visualization_folder = viz_folder
        logger.info(f"Saving visualizations to: {viz_folder}")

    obs_df = GeomCrossSection.get_blocked_obstructions(geom_path)
    if obs_df.empty:
        return results

    for xs_id, group in obs_df.groupby("xs_id", sort=False):
        original = [
            BlockedObstruction(row.start_sta, row.end_sta, row.elevation)
            for row in group.itertuples()
        ]

        if len(original) < 2 or not has_overlaps(original):
            continue

        fixed = create_elevation_envelope(original)
        first = group.iloc[0]
        river = str(first["River"])
        reach = str(first["Reach"])
        rs_id = str(first["RS"])

        msg = FixMessage(
            message_id="FX_BO_01",
            fix_type="OBSTRUCTION",
            river=river,
            reach=reach,
            station=rs_id,
            action=FixAction.OVERLAP_RESOLVED,
            message=(
                f"Resolved {len(original)} overlapping obstructions to "
                f"{len(fixed)} non-overlapping"
            ),
            original_count=len(original),
            fixed_count=len(fixed),
            original_data=[o.to_tuple() for o in original],
            fixed_data=[o.to_tuple() for o in fixed],
        )

        logger.debug(f"RS {rs_id}: {len(original)} -> {len(fixed)} obstructions")

        if viz_folder and not dry_run:
            viz_path = viz_folder / f"RS_{rs_id.replace('.', '_')}.png"
            msg.visualization_path = viz_path
            RasFixit._visualize(original, fixed, rs_id, viz_path)

        results.messages.append(msg)
        results.total_xs_fixed += 1

        if not dry_run:
            GeomCrossSection.set_blocked_obstructions(
                geom_path,
                xs_id,
                fixed,
                create_backup=False,
            )

    if not dry_run and results.total_xs_fixed > 0:
        logger.info(
            f"Fixed {results.total_xs_fixed} cross sections in {geom_path.name}"
        )

    return results

detect_obstruction_overlaps staticmethod

Python
detect_obstruction_overlaps(geom_path: Union[str, Path]) -> FixResults

Detect overlapping blocked obstructions without modifying the file.

This is equivalent to fix_blocked_obstructions(dry_run=True). Useful for pre-flight checks before applying fixes.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required

Returns:

Type Description
FixResults

FixResults with detection messages (no modifications made).

Example

results = RasFixit.detect_obstruction_overlaps("model.g04") print(f"Found {results.total_xs_fixed} cross sections with overlaps")

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def detect_obstruction_overlaps(geom_path: Union[str, Path]) -> FixResults:
    """
    Detect overlapping blocked obstructions without modifying the file.

    This is equivalent to fix_blocked_obstructions(dry_run=True).
    Useful for pre-flight checks before applying fixes.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)

    Returns:
        FixResults with detection messages (no modifications made).

    Example:
        >>> results = RasFixit.detect_obstruction_overlaps("model.g04")
        >>> print(f"Found {results.total_xs_fixed} cross sections with overlaps")
    """
    return RasFixit.fix_blocked_obstructions(
        geom_path, backup=False, visualize=False, dry_run=True
    )

fix_htab_starting_elevations staticmethod

Python
fix_htab_starting_elevations(geom_path: Union[str, Path], backup: bool = True, dry_run: bool = False, margin: float = 0.0) -> FixResults

Fix HTAB starting elevation issues in a geometry file.

HTAB (Hydraulic Table) starting elevation must be >= cross section invert. This is a hard HEC-RAS requirement - models with starting_el < invert will fail during preprocessing (common issue when upgrading from older HEC-RAS versions).

This method identifies all cross sections where starting_el < invert and automatically corrects them by setting starting_el = invert + margin.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required
backup bool

Create timestamped backup before modification (default True)

True
dry_run bool

Detect issues without modifying file (default False)

False
margin float

Additional margin above invert for starting elevation (default 0.0 ft) Use small positive value (e.g., 0.1) for extra safety margin.

0.0

Returns:

Type Description
FixResults

FixResults with messages for each fixed cross section.

-total_xs_checked

Number of XS with HTAB parameters examined

-total_xs_fixed

Number of XS with starting_el corrected

-messages

List of FixMessage objects with before/after values

FixResults

Use results.to_dataframe() for pandas DataFrame output.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist.

Example

from ras_commander import RasFixit

Fix all HTAB starting elevation issues

results = RasFixit.fix_htab_starting_elevations("model.g01") print(f"Fixed {results.total_xs_fixed} cross sections")

Detection only (no modifications)

results = RasFixit.fix_htab_starting_elevations( ... "model.g01", dry_run=True ... ) print(f"Found {results.total_xs_fixed} cross sections with issues")

View details

df = results.to_dataframe() print(df[['river', 'reach', 'station', 'message']])

Note

This fix is required after HEC-RAS version upgrades or when importing geometry from external sources. HEC-RAS will fail with an error during geometry preprocessing if starting_el < invert.

Integration with RasCheck

RasCheck.check_htab_params() detects HTAB_SE_01 errors (starting_el < invert) RasFixit.fix_htab_starting_elevations() repairs those issues

See Also
  • GeomCrossSection.get_xs_htab_params(): Read HTAB parameters
  • GeomCrossSection.set_xs_htab_params(): Write HTAB parameters
  • RasCheck.check_htab_params(): Validate HTAB parameters
Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def fix_htab_starting_elevations(
    geom_path: Union[str, Path],
    backup: bool = True,
    dry_run: bool = False,
    margin: float = 0.0
) -> FixResults:
    """
    Fix HTAB starting elevation issues in a geometry file.

    HTAB (Hydraulic Table) starting elevation must be >= cross section invert.
    This is a hard HEC-RAS requirement - models with starting_el < invert will
    fail during preprocessing (common issue when upgrading from older HEC-RAS versions).

    This method identifies all cross sections where starting_el < invert and
    automatically corrects them by setting starting_el = invert + margin.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)
        backup: Create timestamped backup before modification (default True)
        dry_run: Detect issues without modifying file (default False)
        margin: Additional margin above invert for starting elevation (default 0.0 ft)
               Use small positive value (e.g., 0.1) for extra safety margin.

    Returns:
        FixResults with messages for each fixed cross section.
        - total_xs_checked: Number of XS with HTAB parameters examined
        - total_xs_fixed: Number of XS with starting_el corrected
        - messages: List of FixMessage objects with before/after values
        Use results.to_dataframe() for pandas DataFrame output.

    Raises:
        FileNotFoundError: If geometry file doesn't exist.

    Example:
        >>> from ras_commander import RasFixit
        >>>
        >>> # Fix all HTAB starting elevation issues
        >>> results = RasFixit.fix_htab_starting_elevations("model.g01")
        >>> print(f"Fixed {results.total_xs_fixed} cross sections")
        >>>
        >>> # Detection only (no modifications)
        >>> results = RasFixit.fix_htab_starting_elevations(
        ...     "model.g01", dry_run=True
        ... )
        >>> print(f"Found {results.total_xs_fixed} cross sections with issues")
        >>>
        >>> # View details
        >>> df = results.to_dataframe()
        >>> print(df[['river', 'reach', 'station', 'message']])

    Note:
        This fix is required after HEC-RAS version upgrades or when importing
        geometry from external sources. HEC-RAS will fail with an error during
        geometry preprocessing if starting_el < invert.

    Integration with RasCheck:
        RasCheck.check_htab_params() detects HTAB_SE_01 errors (starting_el < invert)
        RasFixit.fix_htab_starting_elevations() repairs those issues

    See Also:
        - GeomCrossSection.get_xs_htab_params(): Read HTAB parameters
        - GeomCrossSection.set_xs_htab_params(): Write HTAB parameters
        - RasCheck.check_htab_params(): Validate HTAB parameters
    """
    from ..geom.GeomCrossSection import GeomCrossSection

    geom_path = Path(geom_path)
    if not geom_path.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_path}")

    results = FixResults()

    # Create backup if requested and not dry run
    if backup and not dry_run:
        backup_path = RasFixit._create_backup(geom_path)
        results.backup_path = backup_path
        logger.info(f"Created backup: {backup_path}")

    try:
        # Get all cross sections from geometry file
        xs_df = GeomCrossSection.get_cross_sections(geom_path)
        # Filter to Type 1 (real cross sections) only - excludes lateral
        # structures (Type 6), bridges, culverts, etc. which lack #Sta/Elev data
        if 'Type' in xs_df.columns:
            xs_df = xs_df[xs_df['Type'] == 1].reset_index(drop=True)

        if xs_df.empty:
            logger.info(f"No cross sections found in {geom_path.name}")
            return results

        logger.info(f"Checking HTAB starting elevations for {len(xs_df)} cross sections")

        xs_to_fix = []  # List of dicts with fix info

        for _, row in xs_df.iterrows():
            river = row['River']
            reach = row['Reach']
            rs = row['RS']

            try:
                # Get HTAB parameters for this XS
                htab_params = GeomCrossSection.get_xs_htab_params(
                    geom_path, river, reach, rs
                )

                starting_el = htab_params.get('starting_el')
                invert = htab_params.get('invert')

                # Skip if no HTAB params or no starting elevation defined
                if starting_el is None or invert is None:
                    continue

                results.total_xs_checked += 1

                # Check if starting_el < invert (ERROR condition)
                if starting_el < invert:
                    corrected_starting_el = invert + margin
                    xs_to_fix.append({
                        'river': river,
                        'reach': reach,
                        'rs': rs,
                        'original_starting_el': starting_el,
                        'invert': invert,
                        'corrected_starting_el': corrected_starting_el,
                        'increment': htab_params.get('increment'),
                        'num_points': htab_params.get('num_points')
                    })

                    # Create fix message
                    msg = FixMessage(
                        message_id="FX_HTAB_01",
                        fix_type="HTAB",
                        river=river,
                        reach=reach,
                        station=str(rs),
                        action=FixAction.HTAB_STARTING_EL_FIXED,
                        message=(
                            f"HTAB starting elevation corrected from {starting_el:.2f} "
                            f"to {corrected_starting_el:.2f} (invert={invert:.2f})"
                        ),
                        original_data=[(starting_el, invert, 0.0)],
                        fixed_data=[(corrected_starting_el, invert, 0.0)]
                    )
                    results.messages.append(msg)

                    logger.debug(
                        f"{river}/{reach}/RS {rs}: starting_el {starting_el:.2f} -> "
                        f"{corrected_starting_el:.2f} (invert={invert:.2f})"
                    )

            except Exception as e:
                logger.warning(f"Error checking HTAB for {river}/{reach}/RS {rs}: {e}")
                continue

        results.total_xs_fixed = len(xs_to_fix)

        # Apply fixes if not dry run
        if not dry_run and xs_to_fix:
            logger.info(f"Applying fixes to {len(xs_to_fix)} cross sections")

            for xs_info in xs_to_fix:
                try:
                    GeomCrossSection.set_xs_htab_params(
                        geom_path,
                        xs_info['river'],
                        xs_info['reach'],
                        xs_info['rs'],
                        starting_el=xs_info['corrected_starting_el'],
                        increment=xs_info['increment'],
                        num_points=xs_info['num_points']
                    )
                except Exception as e:
                    logger.error(
                        f"Failed to fix HTAB for {xs_info['river']}/{xs_info['reach']}/"
                        f"RS {xs_info['rs']}: {e}"
                    )

            logger.info(
                f"Fixed HTAB starting elevations for {len(xs_to_fix)} cross sections "
                f"in {geom_path.name}"
            )
        elif dry_run and xs_to_fix:
            logger.info(
                f"Dry run: Found {len(xs_to_fix)} cross sections with HTAB starting_el < invert"
            )

        # Add statistics
        results.statistics = {
            'total_xs_in_file': len(xs_df),
            'xs_with_htab': results.total_xs_checked,
            'xs_with_issues': results.total_xs_fixed,
            'margin_used': margin
        }

    except Exception as e:
        logger.error(f"Failed to fix HTAB starting elevations: {e}")
        raise

    return results

detect_htab_issues staticmethod

Python
detect_htab_issues(geom_path: Union[str, Path]) -> FixResults

Detect HTAB starting elevation issues without modifying the file.

This is equivalent to fix_htab_starting_elevations(dry_run=True). Useful for pre-flight checks before applying fixes.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required

Returns:

Type Description
FixResults

FixResults with detection messages (no modifications made).

Example

results = RasFixit.detect_htab_issues("model.g01") print(f"Found {results.total_xs_fixed} cross sections with HTAB issues") for msg in results.messages: ... print(f" {msg.river}/{msg.reach}/RS {msg.station}: {msg.message}")

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def detect_htab_issues(geom_path: Union[str, Path]) -> FixResults:
    """
    Detect HTAB starting elevation issues without modifying the file.

    This is equivalent to fix_htab_starting_elevations(dry_run=True).
    Useful for pre-flight checks before applying fixes.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)

    Returns:
        FixResults with detection messages (no modifications made).

    Example:
        >>> results = RasFixit.detect_htab_issues("model.g01")
        >>> print(f"Found {results.total_xs_fixed} cross sections with HTAB issues")
        >>> for msg in results.messages:
        ...     print(f"  {msg.river}/{msg.reach}/RS {msg.station}: {msg.message}")
    """
    return RasFixit.fix_htab_starting_elevations(
        geom_path, backup=False, dry_run=True
    )

fix_bank_stations staticmethod

Python
fix_bank_stations(geom_path: Union[str, Path], backup: bool = True, dry_run: bool = False, rs_list: Optional[List[str]] = None) -> FixResults

Fix bank station / station-elevation data for cross sections.

Version upgrade fix (HEC-RAS 4.x → 6.x). Also safe as a general-purpose normalization pass on any model version.

Re-writes station/elevation data through set_station_elevation() which normalizes fixed-width formatting (all values to {:8.2f}) and ensures bank stations appear as exact points via _interpolate_at_banks(). Existing points within 0.005 units of a bank station are snapped to the exact bank value rather than inserting a near-duplicate.

HEC-RAS 6.x has stricter validation than 4.x for bank station matching. A round-trip rewrite normalizes the FORTRAN fixed-width format, resolving mismatches that are invisible to value-based comparisons.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required
backup bool

Create timestamped backup before modification (default True)

True
dry_run bool

Detect issues without modifying file (default False)

False
rs_list Optional[List[str]]

Optional list of RS values to fix. If None, fixes all Type 1 cross sections (full normalization).

None

Returns:

Type Description
FixResults

FixResults with messages for each cross section targeted.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist.

Example
Fix specific cross sections from RAS error report

results = RasFixit.fix_bank_stations( ... "model.g01", ... rs_list=["76202", "70462", "68673"] ... ) print(f"Fixed {results.total_xs_fixed} cross sections")

Note

This fix targets models upgraded from HEC-RAS 4.x to 6.x, but the normalization is also safe for any model version. All changes should be reviewed by a licensed professional engineer.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def fix_bank_stations(
    geom_path: Union[str, Path],
    backup: bool = True,
    dry_run: bool = False,
    rs_list: Optional[List[str]] = None
) -> FixResults:
    """
    Fix bank station / station-elevation data for cross sections.

    **Version upgrade fix (HEC-RAS 4.x → 6.x).** Also safe as a general-purpose
    normalization pass on any model version.

    Re-writes station/elevation data through set_station_elevation() which
    normalizes fixed-width formatting (all values to {:8.2f}) and ensures
    bank stations appear as exact points via _interpolate_at_banks(). Existing
    points within 0.005 units of a bank station are snapped to the exact bank
    value rather than inserting a near-duplicate.

    HEC-RAS 6.x has stricter validation than 4.x for bank station matching.
    A round-trip rewrite normalizes the FORTRAN fixed-width format, resolving
    mismatches that are invisible to value-based comparisons.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)
        backup: Create timestamped backup before modification (default True)
        dry_run: Detect issues without modifying file (default False)
        rs_list: Optional list of RS values to fix. If None, fixes all
                 Type 1 cross sections (full normalization).

    Returns:
        FixResults with messages for each cross section targeted.

    Raises:
        FileNotFoundError: If geometry file doesn't exist.

    Example:
        >>> # Fix specific cross sections from RAS error report
        >>> results = RasFixit.fix_bank_stations(
        ...     "model.g01",
        ...     rs_list=["76202", "70462", "68673"]
        ... )
        >>> print(f"Fixed {results.total_xs_fixed} cross sections")

    Note:
        This fix targets models upgraded from HEC-RAS 4.x to 6.x, but the
        normalization is also safe for any model version. All changes should
        be reviewed by a licensed professional engineer.
    """
    from ..geom.GeomCrossSection import GeomCrossSection

    geom_path = Path(geom_path)
    if not geom_path.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_path}")

    results = FixResults()

    # Create backup if requested and not dry run
    if backup and not dry_run:
        backup_path = RasFixit._create_backup(geom_path)
        results.backup_path = backup_path
        logger.info(f"Created backup: {backup_path}")

    try:
        # Get all cross sections
        xs_df_all = GeomCrossSection.get_cross_sections(geom_path)

        # Filter to Type 1 (natural cross sections only)
        xs_df = xs_df_all[xs_df_all['Type'] == 1]

        # Filter to specific RS values if provided
        if rs_list is not None:
            rs_set = set(str(r).strip() for r in rs_list)
            xs_df = xs_df[xs_df['RS'].apply(
                lambda x: str(x).strip() in rs_set
            )]

        results.total_xs_checked = len(xs_df)
        xs_to_fix = []

        for _, row in xs_df.iterrows():
            river = row['River']
            reach = row['Reach']
            rs = str(row['RS'])

            try:
                banks = GeomCrossSection.get_bank_stations(
                    geom_path, river, reach, rs
                )
                if banks is None:
                    continue

                bank_left, bank_right = banks

                msg = FixMessage(
                    message_id="FX_BK_01",
                    fix_type="BANK_STATION",
                    river=river,
                    reach=reach,
                    station=rs,
                    action=FixAction.BANK_STATION_REWRITTEN,
                    message=(
                        f"Rewriting sta/elev with normalized formatting. "
                        f"Banks: L={bank_left}, R={bank_right}"
                    )
                )
                results.messages.append(msg)
                xs_to_fix.append((river, reach, rs, bank_left, bank_right))

            except Exception as e:
                logger.warning(f"Error reading {river}/{reach}/RS {rs}: {e}")
                continue

        # Apply fixes if not dry run
        if not dry_run and xs_to_fix:
            for river, reach, rs, bank_left, bank_right in xs_to_fix:
                try:
                    sta_elev = GeomCrossSection.get_station_elevation(
                        geom_path, river, reach, rs
                    )
                    GeomCrossSection.set_station_elevation(
                        geom_path, river, reach, rs, sta_elev,
                        bank_left=bank_left, bank_right=bank_right
                    )
                    results.total_xs_fixed += 1
                    logger.debug(
                        f"Normalized {river}/{reach}/RS {rs}"
                    )
                except Exception as e:
                    logger.error(
                        f"Failed to fix {river}/{reach}/RS {rs}: {e}"
                    )
        elif dry_run:
            results.total_xs_fixed = len(xs_to_fix)
            logger.info(
                f"Dry run: {len(xs_to_fix)} cross sections to normalize"
            )

        results.statistics = {
            'total_xs_in_file': len(xs_df_all),
            'xs_targeted': results.total_xs_checked,
            'xs_fixed': len(xs_to_fix)
        }

    except Exception as e:
        logger.error(f"Failed to fix bank stations: {e}")
        raise

    return results

detect_bank_station_issues staticmethod

Python
detect_bank_station_issues(geom_path: Union[str, Path]) -> FixResults

Detect bank station formatting issues without modifying the file (dry run).

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required

Returns:

Type Description
FixResults

FixResults with messages for each cross section that would be normalized.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def detect_bank_station_issues(
    geom_path: Union[str, Path]
) -> FixResults:
    """
    Detect bank station formatting issues without modifying the file (dry run).

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)

    Returns:
        FixResults with messages for each cross section that would be normalized.
    """
    return RasFixit.fix_bank_stations(geom_path, backup=False, dry_run=True)

fix_ineffective_flow staticmethod

Python
fix_ineffective_flow(geom_path: Union[str, Path], backup: bool = True, dry_run: bool = False, rs_list: Optional[List[str]] = None) -> FixResults

Fix malformed ineffective flow area data in HEC-RAS geometry files.

Version upgrade fix (HEC-RAS 4.x → 6.x). Not applicable to models originally created in HEC-RAS 6.x.

HEC-RAS 4.x accepted 0 as a sentinel station value meaning "extend to the cross section boundary." HEC-RAS 6.x treats 0 literally, creating backwards pairs (left_station > right_station) that fail data check validation with misleading "Bank station not in sta/elev data" cascade errors.

This method scans all Type 1 cross sections for #XS Ineff= blocks where any triplet has right_station == 0 AND left_station > 0. The fix replaces right_station = 0 with the actual rightmost station from the cross section's sta/elev data.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required
backup bool

Create timestamped backup before modification (default True)

True
dry_run bool

Detect issues without modifying file (default False)

False
rs_list Optional[List[str]]

Optional list of RS values to check. If None, checks all Type 1 cross sections.

None

Returns:

Type Description
FixResults

FixResults with messages for each modified cross section.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist.

Example

results = RasFixit.fix_ineffective_flow( ... "model.g01", ... backup=True ... ) print(f"Fixed {results.total_xs_fixed} cross sections") for msg in results.messages: ... print(f" RS {msg.station}: {msg.message}")

Note

This fix targets models upgraded from HEC-RAS 4.x to 6.x, or models converted from HEC-2. The right_station=0 sentinel pattern does not occur in models originally created in HEC-RAS 6.x. All changes should be reviewed by a licensed professional engineer.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def fix_ineffective_flow(
    geom_path: Union[str, Path],
    backup: bool = True,
    dry_run: bool = False,
    rs_list: Optional[List[str]] = None
) -> FixResults:
    """
    Fix malformed ineffective flow area data in HEC-RAS geometry files.

    **Version upgrade fix (HEC-RAS 4.x → 6.x).** Not applicable to models
    originally created in HEC-RAS 6.x.

    HEC-RAS 4.x accepted ``0`` as a sentinel station value meaning "extend
    to the cross section boundary." HEC-RAS 6.x treats ``0`` literally,
    creating backwards pairs (left_station > right_station) that fail
    data check validation with misleading "Bank station not in sta/elev
    data" cascade errors.

    This method scans all Type 1 cross sections for ``#XS Ineff=`` blocks
    where any triplet has ``right_station == 0`` AND ``left_station > 0``.
    The fix replaces ``right_station = 0`` with the actual rightmost station
    from the cross section's sta/elev data.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)
        backup: Create timestamped backup before modification (default True)
        dry_run: Detect issues without modifying file (default False)
        rs_list: Optional list of RS values to check. If None, checks all
                 Type 1 cross sections.

    Returns:
        FixResults with messages for each modified cross section.

    Raises:
        FileNotFoundError: If geometry file doesn't exist.

    Example:
        >>> results = RasFixit.fix_ineffective_flow(
        ...     "model.g01",
        ...     backup=True
        ... )
        >>> print(f"Fixed {results.total_xs_fixed} cross sections")
        >>> for msg in results.messages:
        ...     print(f"  RS {msg.station}: {msg.message}")

    Note:
        This fix targets models upgraded from HEC-RAS 4.x to 6.x, or models
        converted from HEC-2. The right_station=0 sentinel pattern does not
        occur in models originally created in HEC-RAS 6.x. All changes should
        be reviewed by a licensed professional engineer.
    """
    from ..geom.GeomCrossSection import GeomCrossSection

    geom_path = Path(geom_path)
    if not geom_path.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_path}")

    results = FixResults()

    if backup and not dry_run:
        backup_path = RasFixit._create_backup(geom_path)
        results.backup_path = backup_path
        logger.info(f"Created backup: {backup_path}")

    try:
        xs_df_all = GeomCrossSection.get_cross_sections(geom_path)
        xs_df = xs_df_all[xs_df_all['Type'] == 1]

        if rs_list is not None:
            rs_set = set(str(r).strip() for r in rs_list)
            xs_df = xs_df[xs_df['RS'].apply(lambda x: str(x).strip() in rs_set)]

        results.total_xs_checked = len(xs_df)
        xs_to_fix = []

        for _, row in xs_df.iterrows():
            river = row['River']
            reach = row['Reach']
            rs = str(row['RS'])

            try:
                ineff_df, fmt_flag, perm_flags = GeomCrossSection.get_ineffective_flow(
                    geom_path, river, reach, rs
                )
                if ineff_df is None:
                    continue

                # Find pairs where right_station=0 and left_station > 0
                # (backwards pair: 4.x sentinel -> 6.x takes 0 literally)
                bad_mask = (ineff_df['right_station'] == 0) & (ineff_df['left_station'] > 0)
                if not bad_mask.any():
                    continue

                # Get rightmost station from sta/elev data
                sta_elev = GeomCrossSection.get_station_elevation(
                    geom_path, river, reach, rs
                )
                rightmost = float(sta_elev['Station'].max())

                bad_rows = ineff_df[bad_mask]
                details = "; ".join(
                    f"pair({r['left_station']:.2f}->0) fixed to {rightmost:.2f}"
                    for _, r in bad_rows.iterrows()
                )

                msg = FixMessage(
                    message_id="FX_IF_01",
                    fix_type="INEFFECTIVE",
                    river=river,
                    reach=reach,
                    station=rs,
                    action=FixAction.INEFFECTIVE_FIXED,
                    message=(
                        f"right_station=0 replaced with rightmost sta {rightmost:.2f}. "
                        f"{details}"
                    ),
                    original_count=len(ineff_df),
                    fixed_count=len(ineff_df),
                    original_data=[
                        (r['left_station'], r['right_station'], r['elevation'])
                        for _, r in ineff_df.iterrows()
                    ]
                )
                results.messages.append(msg)
                xs_to_fix.append(
                    (river, reach, rs, ineff_df.copy(), fmt_flag, perm_flags, rightmost)
                )

            except Exception as e:
                logger.warning(f"Error checking {river}/{reach}/RS {rs}: {e}")
                continue

        if not dry_run and xs_to_fix:
            for river, reach, rs, ineff_df, fmt_flag, perm_flags, rightmost in xs_to_fix:
                try:
                    fixed_df = ineff_df.copy()
                    bad_mask = (
                        (fixed_df['right_station'] == 0) & (fixed_df['left_station'] > 0)
                    )
                    fixed_df.loc[bad_mask, 'right_station'] = rightmost

                    GeomCrossSection.set_ineffective_flow(
                        geom_path, river, reach, rs,
                        fixed_df, fmt_flag, perm_flags
                    )
                    results.total_xs_fixed += 1
                    logger.debug(
                        f"Fixed ineffective flow for {river}/{reach}/RS {rs}: "
                        f"right_station=0 -> {rightmost:.2f}"
                    )

                    # Update message with fixed_data
                    for msg in results.messages:
                        if msg.station.strip() == rs.strip():
                            msg.fixed_data = [
                                (r['left_station'], r['right_station'], r['elevation'])
                                for _, r in fixed_df.iterrows()
                            ]
                            break

                except Exception as e:
                    logger.error(f"Failed to fix {river}/{reach}/RS {rs}: {e}")

        elif dry_run:
            results.total_xs_fixed = len(xs_to_fix)
            logger.info(
                f"Dry run: {len(xs_to_fix)} cross sections have right_station=0 "
                "in ineffective flow areas"
            )

        results.statistics = {
            'total_xs_in_file': len(xs_df_all),
            'xs_with_ineff_checked': results.total_xs_checked,
            'xs_fixed': results.total_xs_fixed
        }

    except Exception as e:
        logger.error(f"Failed to fix ineffective flow: {e}")
        raise

    return results

detect_ineffective_flow_issues staticmethod

Python
detect_ineffective_flow_issues(geom_path: Union[str, Path]) -> FixResults

Detect cross sections with malformed ineffective flow area data (dry run).

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file.

required

Returns:

Type Description
FixResults

FixResults with messages for each cross section that would be fixed.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def detect_ineffective_flow_issues(
    geom_path: Union[str, Path]
) -> FixResults:
    """
    Detect cross sections with malformed ineffective flow area data (dry run).

    Args:
        geom_path: Path to HEC-RAS geometry file.

    Returns:
        FixResults with messages for each cross section that would be fixed.
    """
    return RasFixit.fix_ineffective_flow(geom_path, backup=False, dry_run=True)

fix_mannings_n staticmethod

Python
fix_mannings_n(geom_path: Union[str, Path], backup: bool = True, dry_run: bool = False, rs_list: Optional[List[str]] = None) -> FixResults

Fix Manning's n data for cross sections with missing or misaligned breakpoints.

Version upgrade fix (HEC-RAS 4.x → 6.x). Not applicable to models originally created in HEC-RAS 6.x.

Handles two categories of Manning's n errors common after HEC-RAS version upgrades (4.x to 6.x):

  1. Missing data (#Mann= 0): Reconstructs 3-breakpoint (LOB/MC/ROB) Manning's n using distance-weighted linear interpolation from the nearest upstream and downstream Type 1 cross sections that have valid data.

  2. Misaligned breakpoints: When RAS 6.6's version upgrade moved bank stations but left Manning's breakpoints at the old positions, snaps the MC and ROB breakpoints to the current bank station values.

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required
backup bool

Create timestamped backup before modification (default True)

True
dry_run bool

Detect issues without modifying file (default False)

False
rs_list Optional[List[str]]

Optional list of RS values to check. If None, checks all Type 1 cross sections.

None

Returns:

Type Description
FixResults

FixResults with messages for each modified cross section.

Raises:

Type Description
FileNotFoundError

If geometry file doesn't exist.

Example

results = RasFixit.fix_mannings_n("model.g01") print(f"Fixed {results.total_xs_fixed} cross sections")

Note

This fix targets models upgraded from HEC-RAS 4.x to 6.x where the version upgrade zeroed out or misaligned Manning's n breakpoints. All changes should be reviewed by a licensed professional engineer.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def fix_mannings_n(
    geom_path: Union[str, Path],
    backup: bool = True,
    dry_run: bool = False,
    rs_list: Optional[List[str]] = None
) -> FixResults:
    """
    Fix Manning's n data for cross sections with missing or misaligned breakpoints.

    **Version upgrade fix (HEC-RAS 4.x → 6.x).** Not applicable to models
    originally created in HEC-RAS 6.x.

    Handles two categories of Manning's n errors common after HEC-RAS version
    upgrades (4.x to 6.x):

    1. **Missing data** (``#Mann= 0``): Reconstructs 3-breakpoint (LOB/MC/ROB)
       Manning's n using distance-weighted linear interpolation from the nearest
       upstream and downstream Type 1 cross sections that have valid data.

    2. **Misaligned breakpoints**: When RAS 6.6's version upgrade moved bank
       stations but left Manning's breakpoints at the old positions, snaps the
       MC and ROB breakpoints to the current bank station values.

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)
        backup: Create timestamped backup before modification (default True)
        dry_run: Detect issues without modifying file (default False)
        rs_list: Optional list of RS values to check. If None, checks all
                 Type 1 cross sections.

    Returns:
        FixResults with messages for each modified cross section.

    Raises:
        FileNotFoundError: If geometry file doesn't exist.

    Example:
        >>> results = RasFixit.fix_mannings_n("model.g01")
        >>> print(f"Fixed {results.total_xs_fixed} cross sections")

    Note:
        This fix targets models upgraded from HEC-RAS 4.x to 6.x where the
        version upgrade zeroed out or misaligned Manning's n breakpoints.
        All changes should be reviewed by a licensed professional engineer.
    """
    from ..geom.GeomCrossSection import GeomCrossSection
    import numpy as np
    import pandas as pd

    geom_path = Path(geom_path)
    if not geom_path.exists():
        raise FileNotFoundError(f"Geometry file not found: {geom_path}")

    results = FixResults()

    if backup and not dry_run:
        backup_path = RasFixit._create_backup(geom_path)
        results.backup_path = backup_path
        logger.info(f"Created backup: {backup_path}")

    try:
        xs_df = GeomCrossSection.get_cross_sections(geom_path)
        xs_type1 = xs_df[xs_df['Type'] == 1].copy()
        xs_type1['RS_num'] = xs_type1['RS'].str.strip().astype(float)
        xs_type1 = xs_type1.sort_values('RS_num', ascending=False).reset_index(drop=True)

        if rs_list is not None:
            rs_set = set(str(r).strip() for r in rs_list)
            check_df = xs_type1[xs_type1['RS'].apply(lambda x: str(x).strip() in rs_set)]
        else:
            check_df = xs_type1

        results.total_xs_checked = len(check_df)
        xs_to_fix = []

        def _extract_lob_mc_rob(mann_df):
            """Extract LOB/MC/ROB n-values from a Manning's DataFrame."""
            if mann_df is None or len(mann_df) == 0:
                return None
            if 'Subsection' in mann_df.columns:
                lob = mann_df[mann_df['Subsection'] == 'LOB']
                mc = mann_df[mann_df['Subsection'] == 'Channel']
                rob = mann_df[mann_df['Subsection'] == 'ROB']
                lob_n = lob['n_value'].iloc[0] if len(lob) > 0 else mann_df.iloc[0]['n_value']
                mc_n = mc['n_value'].iloc[0] if len(mc) > 0 else mann_df.iloc[1]['n_value'] if len(mann_df) > 1 else lob_n
                rob_n = rob['n_value'].iloc[0] if len(rob) > 0 else mann_df.iloc[-1]['n_value']
            else:
                lob_n = mann_df.iloc[0]['n_value']
                mc_n = mann_df.iloc[1]['n_value'] if len(mann_df) > 1 else lob_n
                rob_n = mann_df.iloc[-1]['n_value']
            return lob_n, mc_n, rob_n

        def _find_neighbor_with_mann(idx, direction):
            """Find nearest Type 1 XS with valid Manning's data."""
            step = -1 if direction == 'upstream' else 1
            k = idx + step
            while 0 <= k < len(xs_type1):
                row = xs_type1.iloc[k]
                r, rch, rs_val = row['River'], row['Reach'], str(row['RS'])
                try:
                    m = GeomCrossSection.get_mannings_n(
                        geom_path, r, rch, rs_val
                    )
                    if m is not None and len(m) > 0:
                        return row, m
                except Exception:
                    pass
                k += step
            return None, None

        for _, row in check_df.iterrows():
            river = row['River']
            reach = row['Reach']
            rs = str(row['RS'])
            rs_num = float(rs.strip())
            idx = xs_type1.index[xs_type1['RS_num'] == rs_num].tolist()
            if not idx:
                continue
            idx = idx[0]

            try:
                banks = GeomCrossSection.get_bank_stations(
                    geom_path, river, reach, rs
                )
                if banks is None:
                    continue
                bank_left, bank_right = banks

                mann = GeomCrossSection.get_mannings_n(
                    geom_path, river, reach, rs
                )

                if mann is None or len(mann) == 0:
                    # Category A: Missing data — reconstruct from neighbors
                    up_row, up_mann = _find_neighbor_with_mann(idx, 'upstream')
                    dn_row, dn_mann = _find_neighbor_with_mann(idx, 'downstream')

                    if up_mann is None or dn_mann is None:
                        logger.warning(
                            f"Cannot interpolate Mann for RS {rs}: "
                            f"missing {'upstream' if up_mann is None else 'downstream'} neighbor"
                        )
                        continue

                    up_vals = _extract_lob_mc_rob(up_mann)
                    dn_vals = _extract_lob_mc_rob(dn_mann)
                    if up_vals is None or dn_vals is None:
                        continue

                    up_rs = float(str(up_row['RS']).strip())
                    dn_rs = float(str(dn_row['RS']).strip())
                    dist_ue = up_rs - rs_num
                    dist_ed = rs_num - dn_rs

                    if dist_ue + dist_ed <= 0:
                        continue

                    w_u = dist_ed / (dist_ue + dist_ed)
                    w_d = dist_ue / (dist_ue + dist_ed)

                    lob_n = round(w_u * up_vals[0] + w_d * dn_vals[0], 4)
                    mc_n = round(w_u * up_vals[1] + w_d * dn_vals[1], 4)
                    rob_n = round(w_u * up_vals[2] + w_d * dn_vals[2], 4)

                    # LOB breakpoint = leftmost sta/elev station
                    sta_elev = GeomCrossSection.get_station_elevation(
                        geom_path, river, reach, rs
                    )
                    lob_sta = float(sta_elev['Station'].min())

                    new_mann = pd.DataFrame({
                        'Station': [lob_sta, bank_left, bank_right],
                        'n_value': [lob_n, mc_n, rob_n]
                    })

                    msg = FixMessage(
                        message_id="FX_MN_01",
                        fix_type="MANNINGS_N",
                        river=river,
                        reach=reach,
                        station=rs,
                        action=FixAction.MANNINGS_N_REWRITTEN,
                        message=(
                            f"Reconstructed from neighbors: "
                            f"LOB={lob_n:.3f} (U:{up_vals[0]:.3f}/D:{dn_vals[0]:.3f}), "
                            f"MC={mc_n:.3f} (U:{up_vals[1]:.3f}/D:{dn_vals[1]:.3f}), "
                            f"ROB={rob_n:.3f} (U:{up_vals[2]:.3f}/D:{dn_vals[2]:.3f}). "
                            f"Weights: U={w_u:.3f}, D={w_d:.3f}"
                        )
                    )
                    results.messages.append(msg)
                    xs_to_fix.append((river, reach, rs, new_mann))

                elif len(mann) >= 3:
                    # Check if breakpoints match bank stations
                    mann_stations = mann['Station'].values
                    # MC breakpoint should be at left bank
                    mc_diff = abs(mann_stations[1] - bank_left)
                    # ROB breakpoint should be at right bank
                    rob_diff = abs(mann_stations[-1] - bank_right)

                    if mc_diff > 0.01 or rob_diff > 0.01:
                        # Category B: Misaligned — snap to banks
                        new_mann = pd.DataFrame({
                            'Station': [mann_stations[0], bank_left, bank_right],
                            'n_value': [
                                mann.iloc[0]['n_value'],
                                mann.iloc[1]['n_value'],
                                mann.iloc[-1]['n_value']
                            ]
                        })

                        msg = FixMessage(
                            message_id="FX_MN_02",
                            fix_type="MANNINGS_N",
                            river=river,
                            reach=reach,
                            station=rs,
                            action=FixAction.MANNINGS_N_REWRITTEN,
                            message=(
                                f"Snapped breakpoints to banks: "
                                f"MC {mann_stations[1]:.2f}->{bank_left:.2f} "
                                f"(diff={mc_diff:.2f}), "
                                f"ROB {mann_stations[-1]:.2f}->{bank_right:.2f} "
                                f"(diff={rob_diff:.2f})"
                            )
                        )
                        results.messages.append(msg)
                        xs_to_fix.append((river, reach, rs, new_mann))

            except Exception as e:
                logger.warning(f"Error checking {river}/{reach}/RS {rs}: {e}")
                continue

        if not dry_run and xs_to_fix:
            for river, reach, rs, new_mann in xs_to_fix:
                try:
                    GeomCrossSection.set_mannings_n(
                        geom_path, river, reach, rs, new_mann,
                        format_flag=0, change_flag=0
                    )
                    results.total_xs_fixed += 1
                    logger.debug(f"Fixed Manning's n for {river}/{reach}/RS {rs}")
                except Exception as e:
                    logger.error(f"Failed to fix {river}/{reach}/RS {rs}: {e}")

        elif dry_run:
            results.total_xs_fixed = len(xs_to_fix)
            logger.info(
                f"Dry run: {len(xs_to_fix)} cross sections need Manning's n fixes"
            )

        results.statistics = {
            'xs_checked': results.total_xs_checked,
            'xs_fixed': results.total_xs_fixed,
            'reconstructed': len([m for m in results.messages if m.message_id == "FX_MN_01"]),
            'realigned': len([m for m in results.messages if m.message_id == "FX_MN_02"])
        }

    except Exception as e:
        logger.error(f"Failed to fix Manning's n: {e}")
        raise

    return results

detect_mannings_n_issues staticmethod

Python
detect_mannings_n_issues(geom_path: Union[str, Path]) -> FixResults

Detect Manning's n issues without modifying the file (dry run).

Parameters:

Name Type Description Default
geom_path Union[str, Path]

Path to HEC-RAS geometry file (.g##)

required

Returns:

Type Description
FixResults

FixResults with messages for each cross section that would be fixed.

Source code in ras_commander/fixit/RasFixit.py
Python
@staticmethod
@log_call
def detect_mannings_n_issues(
    geom_path: Union[str, Path]
) -> FixResults:
    """
    Detect Manning's n issues without modifying the file (dry run).

    Args:
        geom_path: Path to HEC-RAS geometry file (.g##)

    Returns:
        FixResults with messages for each cross section that would be fixed.
    """
    return RasFixit.fix_mannings_n(geom_path, backup=False, dry_run=True)

Method Details

fix_blocked_obstructions

Main method for fixing overlapping blocked obstructions.

Parameters:

Parameter Type Default Description
geom_path str, Path required Path to HEC-RAS geometry file (.g##)
backup bool True Create timestamped backup before modification
visualize bool False Generate before/after PNG comparisons
dry_run bool False Detect issues without modifying file

Returns: FixResults object containing:

  • total_xs_checked: Number of cross sections examined
  • total_xs_fixed: Number of cross sections modified
  • backup_path: Path to backup file (if created)
  • visualization_folder: Path to PNG visualizations (if generated)
  • messages: List of FixMessage objects with detailed fix information

Example:

Python
from ras_commander import RasFixit

# Fix with all options
results = RasFixit.fix_blocked_obstructions(
    "BaldEagle.g01",
    backup=True,
    visualize=True
)

# Examine results
for msg in results.messages:
    print(f"RS {msg.station}: {msg.original_count} -> {msg.fixed_count} obstructions")
    print(f"  Visualization: {msg.visualization_path}")

# Export to DataFrame
df = results.to_dataframe()
df.to_csv("fix_report.csv")

Result Classes

FixResults

FixResults dataclass

Container for all fix operation results.

Provides aggregate statistics and detailed messages for each fixed cross section.

Attributes:

Name Type Description
messages List[FixMessage]

List of FixMessage objects for each processed cross section

total_xs_checked int

Total number of cross sections examined

total_xs_fixed int

Number of cross sections that were modified

backup_path Optional[Path]

Path to backup file (if created)

visualization_folder Optional[Path]

Path to folder containing PNG visualizations

statistics Dict[str, Any]

Additional statistics dictionary

Example

results = RasFixit.fix_blocked_obstructions("model.g01") print(f"Fixed {results.total_xs_fixed} of {results.total_xs_checked} cross sections") df = results.to_dataframe()

Source code in ras_commander/fixit/results.py
Python
@dataclass
class FixResults:
    """
    Container for all fix operation results.

    Provides aggregate statistics and detailed messages for each fixed cross section.

    Attributes:
        messages: List of FixMessage objects for each processed cross section
        total_xs_checked: Total number of cross sections examined
        total_xs_fixed: Number of cross sections that were modified
        backup_path: Path to backup file (if created)
        visualization_folder: Path to folder containing PNG visualizations
        statistics: Additional statistics dictionary

    Example:
        >>> results = RasFixit.fix_blocked_obstructions("model.g01")
        >>> print(f"Fixed {results.total_xs_fixed} of {results.total_xs_checked} cross sections")
        >>> df = results.to_dataframe()
    """
    messages: List[FixMessage] = field(default_factory=list)
    total_xs_checked: int = 0
    total_xs_fixed: int = 0
    backup_path: Optional[Path] = None
    visualization_folder: Optional[Path] = None
    statistics: Dict[str, Any] = field(default_factory=dict)

    def to_dataframe(self) -> 'pd.DataFrame':
        """
        Convert all messages to a pandas DataFrame.

        Returns:
            DataFrame with one row per fix message.
        """
        import pandas as pd
        if not self.messages:
            return pd.DataFrame()
        return pd.DataFrame([m.to_dict() for m in self.messages])

    def get_fixed_count(self) -> int:
        """
        Count cross sections that were actually fixed.

        Returns:
            Number of messages with action other than NO_ACTION.
        """
        return len([m for m in self.messages if m.action != FixAction.NO_ACTION])

    def get_messages_by_action(self, action: FixAction) -> List[FixMessage]:
        """
        Filter messages by action type.

        Args:
            action: FixAction enum value to filter by.

        Returns:
            List of FixMessage objects matching the action.
        """
        return [m for m in self.messages if m.action == action]

    def __repr__(self) -> str:
        return (f"FixResults(checked={self.total_xs_checked}, "
                f"fixed={self.total_xs_fixed}, "
                f"messages={len(self.messages)})")

to_dataframe

Python
to_dataframe() -> pd.DataFrame

Convert all messages to a pandas DataFrame.

Returns:

Type Description
DataFrame

DataFrame with one row per fix message.

Source code in ras_commander/fixit/results.py
Python
def to_dataframe(self) -> 'pd.DataFrame':
    """
    Convert all messages to a pandas DataFrame.

    Returns:
        DataFrame with one row per fix message.
    """
    import pandas as pd
    if not self.messages:
        return pd.DataFrame()
    return pd.DataFrame([m.to_dict() for m in self.messages])

get_fixed_count

Python
get_fixed_count() -> int

Count cross sections that were actually fixed.

Returns:

Type Description
int

Number of messages with action other than NO_ACTION.

Source code in ras_commander/fixit/results.py
Python
def get_fixed_count(self) -> int:
    """
    Count cross sections that were actually fixed.

    Returns:
        Number of messages with action other than NO_ACTION.
    """
    return len([m for m in self.messages if m.action != FixAction.NO_ACTION])

get_messages_by_action

Python
get_messages_by_action(action: FixAction) -> List[FixMessage]

Filter messages by action type.

Parameters:

Name Type Description Default
action FixAction

FixAction enum value to filter by.

required

Returns:

Type Description
List[FixMessage]

List of FixMessage objects matching the action.

Source code in ras_commander/fixit/results.py
Python
def get_messages_by_action(self, action: FixAction) -> List[FixMessage]:
    """
    Filter messages by action type.

    Args:
        action: FixAction enum value to filter by.

    Returns:
        List of FixMessage objects matching the action.
    """
    return [m for m in self.messages if m.action == action]

FixMessage

FixMessage dataclass

A single fix action message for a cross section.

Attributes:

Name Type Description
message_id str

Unique identifier for the fix type (e.g., "FX_BO_01")

fix_type str

Category of fix (e.g., "OBSTRUCTION", "INEFFECTIVE", "BANK")

river str

River name (if available)

reach str

Reach name (if available)

station str

River station identifier

action FixAction

Type of fix action taken

message str

Human-readable description of the fix

original_count int

Number of obstructions before fix

fixed_count int

Number of obstructions after fix

original_data List[Tuple[float, float, float]]

List of (start_sta, end_sta, elevation) tuples before fix

fixed_data List[Tuple[float, float, float]]

List of (start_sta, end_sta, elevation) tuples after fix

visualization_path Optional[Path]

Path to before/after PNG visualization (if generated)

Source code in ras_commander/fixit/results.py
Python
@dataclass
class FixMessage:
    """
    A single fix action message for a cross section.

    Attributes:
        message_id: Unique identifier for the fix type (e.g., "FX_BO_01")
        fix_type: Category of fix (e.g., "OBSTRUCTION", "INEFFECTIVE", "BANK")
        river: River name (if available)
        reach: Reach name (if available)
        station: River station identifier
        action: Type of fix action taken
        message: Human-readable description of the fix
        original_count: Number of obstructions before fix
        fixed_count: Number of obstructions after fix
        original_data: List of (start_sta, end_sta, elevation) tuples before fix
        fixed_data: List of (start_sta, end_sta, elevation) tuples after fix
        visualization_path: Path to before/after PNG visualization (if generated)
    """
    message_id: str
    fix_type: str
    river: str = ""
    reach: str = ""
    station: str = ""
    action: FixAction = FixAction.NO_ACTION
    message: str = ""
    original_count: int = 0
    fixed_count: int = 0
    original_data: List[Tuple[float, float, float]] = field(default_factory=list)
    fixed_data: List[Tuple[float, float, float]] = field(default_factory=list)
    visualization_path: Optional[Path] = None

    def to_dict(self) -> Dict[str, Any]:
        """
        Convert to dictionary for DataFrame creation.

        Returns:
            Dictionary representation of the fix message.
        """
        return {
            'message_id': self.message_id,
            'fix_type': self.fix_type,
            'river': self.river,
            'reach': self.reach,
            'station': self.station,
            'action': self.action.value,
            'message': self.message,
            'original_count': self.original_count,
            'fixed_count': self.fixed_count,
            'visualization': str(self.visualization_path) if self.visualization_path else None
        }

to_dict

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

Convert to dictionary for DataFrame creation.

Returns:

Type Description
Dict[str, Any]

Dictionary representation of the fix message.

Source code in ras_commander/fixit/results.py
Python
def to_dict(self) -> Dict[str, Any]:
    """
    Convert to dictionary for DataFrame creation.

    Returns:
        Dictionary representation of the fix message.
    """
    return {
        'message_id': self.message_id,
        'fix_type': self.fix_type,
        'river': self.river,
        'reach': self.reach,
        'station': self.station,
        'action': self.action.value,
        'message': self.message,
        'original_count': self.original_count,
        'fixed_count': self.fixed_count,
        'visualization': str(self.visualization_path) if self.visualization_path else None
    }

FixAction

FixAction

Bases: Enum

Type of fix action taken.

Source code in ras_commander/fixit/results.py
Python
class FixAction(Enum):
    """Type of fix action taken."""
    OVERLAP_RESOLVED = "OVERLAP_RESOLVED"      # Overlapping obstructions merged via elevation envelope
    GAP_INSERTED = "GAP_INSERTED"              # 0.02-unit gap added for adjacency compliance
    SEGMENT_MERGED = "SEGMENT_MERGED"          # Same-elevation segments combined
    NO_ACTION = "NO_ACTION"                    # No fix needed (no issues detected)
    # HTAB (Hydraulic Table) fix actions
    HTAB_STARTING_EL_FIXED = "HTAB_STARTING_EL_FIXED"  # Starting elevation raised to >= invert
    HTAB_PARAMS_SET = "HTAB_PARAMS_SET"        # HTAB parameters written/updated
    # Bank station fix actions (version upgrade)
    BANK_STATION_REWRITTEN = "BANK_STATION_REWRITTEN"  # Sta/elev rewritten with bank interpolation
    # Manning's n fix actions (version upgrade)
    MANNINGS_N_REWRITTEN = "MANNINGS_N_REWRITTEN"      # Manning's n data renormalized
    # Ineffective flow area fix actions (version upgrade)
    INEFFECTIVE_FIXED = "INEFFECTIVE_FIXED"            # Malformed ineffective area corrected

Log Parser

The log_parser module provides utilities for detecting obstruction errors from HEC-RAS compute logs.

Python
from ras_commander.fixit import log_parser

# Parse log for errors
errors = log_parser.detect_obstruction_errors(log_content)

# Find geometry files
geom_files = log_parser.find_geometry_files_in_directory(project_dir)

# Generate report
print(log_parser.generate_error_report(errors))

Functions

Function Description
detect_obstruction_errors(log_content) Parse log text, return list of error dicts
extract_geometry_files(log_content, project_dir) Find geometry file references in log
find_geometry_files_in_directory(directory) Scan directory for .g## files
has_obstruction_errors(log_file_path) Quick boolean check for errors
generate_error_report(errors) Format errors for human review
extract_cross_section_ids(log_content) Get list of affected river stations

Automated Workflow Example

Python
from ras_commander import RasFixit
from ras_commander.fixit import log_parser

# Step 1: Check log for errors
if log_parser.has_obstruction_errors("compute.log"):

    # Step 2: Parse errors
    with open("compute.log", "r") as f:
        errors = log_parser.detect_obstruction_errors(f.read())

    print(f"Found {len(errors)} obstruction errors")

    # Step 3: Find and fix geometry files
    geom_files = log_parser.find_geometry_files_in_directory(project_dir)

    for geom_path in geom_files:
        results = RasFixit.fix_blocked_obstructions(
            geom_path,
            visualize=True
        )
        print(f"Fixed {results.total_xs_fixed} cross sections in {geom_path}")

Algorithm Details

Elevation Envelope

The core algorithm for fixing overlapping obstructions:

  1. Collect Critical Stations: Extract all start/end stations from obstructions
  2. Find Max Elevation: For each segment between stations, use the maximum elevation from all overlapping obstructions (preserves the higher blocked elevation)
  3. Merge Segments: Combine adjacent segments with identical elevations
  4. Insert Gaps: Apply the implementation’s 0.02-unit spacing where different elevations meet
Text Only
Original:  [100-120@elev5, 110-130@elev3]  (overlap 110-120)

Step 1 - Critical stations: [100, 110, 120, 130]

Step 2 - Max elevation per segment:
  100-110: elev 5 (only covered by first obstruction)
  110-120: elev 5 (max of 5 and 3)
  120-130: elev 3 (only covered by second obstruction)

Step 3 - Merge same-elevation:
  100-120: elev 5 (merged)
  120-130: elev 3

Step 4 - Insert gap:
  100-120: elev 5
  120.02-130: elev 3  (0.02 gap added)

Result: [100-120@elev5, 120.02-130@elev3]

Why Max Elevation?

The envelope retains the higher blocked elevation in overlapping intervals. That is an algorithmic choice, not proof of conservative flood levels for every model. Review the changed geometry and its hydraulic effects.

Gap Insertion

The implementation inserts 0.02 project station units between adjacent envelope segments with different elevations. This spacing is not a universal hydraulic tolerance or evidence that the rewrite preserves all model behavior.

Integration with Check Module

The fixit module complements the check module:

Python
from ras_commander import RasCheck, RasFixit

# Supply plan and geometry HDF paths plus the selected steady profiles
check_results = RasCheck.check_xs(plan_hdf, geom_hdf, profiles)
obstruction_issues = [m for m in check_results.messages
                      if m.message_id.startswith('XS_BO')]

if obstruction_issues:
    print(f"Found {len(obstruction_issues)} obstruction issues")

    # Fix with RasFixit (operates on plain text geometry files)
    fix_results = RasFixit.fix_blocked_obstructions(
        "model.g01",
        visualize=True
    )
    print(f"Fixed {fix_results.total_xs_fixed} cross sections")
Module Input Purpose
RasCheck.check_xs Plan and geometry HDFs plus selected profiles Detect cross-section issues during results review
RasFixit Geometry files (.g##) Repair issues in source geometry

Visualization Output

When visualize=True, the module generates PNG files showing:

  • Top Panel: Original obstructions (with overlaps) using 'viridis' colormap
  • Bottom Panel: Fixed obstructions (elevation envelope) using 'plasma' colormap

Files are saved to: {ProjectName}_g{##}_Obstructions_Fixed/RS_{station}.png

These visualizations are critical for engineering review - they show exactly what changes were made and why.

Example Project

The repository includes the HCFCD M3 Model A120-00-00 (Harris County Flood Control District) as a real-world example with blocked obstruction issues:

  • Location: examples/example_projects/A120-00-00/
  • Geometry files: A120_00_00.g01, A120_00_00.g02
  • Cross sections: 91 total, 15 with overlapping obstructions
  • Source: examples/data/A120-00-00.zip

An example notebook for blocked obstructions will be added in a future release; the API above covers the current workflow end-to-end.