Skip to content

Meshing: Generation, Diagnostics and Repair

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

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

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

Stage API Input → output
Bootstrap points generate_computation_points Authored perimeter text and spacing -> regular-grid computation points in text; no existing HDF required
Compile geometry RasCmdr preprocessing Referencing project/plan and authored geometry -> native compiled HDF workspace
Author controls Breakline/refinement methods Names, spacing and polygons/flowlines → updated text or compiled-HDF controls, as specified per method
Check domain audit_domain_containment Selected 2D area and cell spacing → DomainContainmentResult
Regenerate mesh generate, generate_all Current compiled HDF, domain, breaklines/refinements and spacing -> MeshResult records and updated computation points
Build properties compute_property_tables Mesh and terrain/classification associations → native property tables; Boolean result
Check boundary conflicts detect_bc_conflicts, fix_bc_conflicts Compiled perimeter faces and BC lines → conflicts or BCFixResult; repair can modify HDF
flowchart LR
    A[Geometry text and spatial inputs] --> S[Bootstrap points if no mesh exists]
    S --> B[Native geometry preprocessing]
    B --> C[Author and audit mesh controls]
    C --> D[Generate computation points and mesh]
    D --> E[Review repairs and associations]
    E --> F[Build property tables]
    F --> G[Prepare and compute hydraulic plan]

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

Diagnose before repairing

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

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

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

Python
from pathlib import Path
from ras_commander import HdfMesh, GeomMesh

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

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

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

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

Repair on a project copy

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

Python
from ras_commander import GeomMesh

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

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

Diagnostic method reference

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

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

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

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

Source code in ras_commander/hdf/HdfMesh.py
Python
 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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
class HdfMesh:
    """
    A class for handling mesh-related operations on HEC-RAS HDF files.

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

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

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

    @staticmethod
    @log_call
    @standardize_input(file_type="geom_hdf")
    def get_mesh_geometry_inventory(
        hdf_path: Union[str, Path],
        *,
        dataset_paths: Optional[Sequence[str]] = None,
        max_chunk_bytes: int = 8 * 1024 * 1024,
        ras_object=None,
    ) -> pd.DataFrame:
        """Inventory exact native 2D dataset identities without changing the HDF.

        Args:
            hdf_path: Geometry or child-result HDF path, or geometry number
                resolved by the input decorator with the explicit ras_object.
            dataset_paths: Exact previously inventoried paths to read. By default,
                inventory every dataset below ``Geometry/2D Flow Areas``. Supply
                the reference inventory's paths when results add property tables.
                Paths must be unique and remain below that native group.
            max_chunk_bytes: Maximum uncompressed bytes in a read slab; positive
                integer, default 8 MiB. An indivisible row exceeding it is rejected.
            ras_object: Explicit project context for geometry-number resolution.

        Returns:
            DataFrame with dataset_path, dtype, shape, bytes and sha256, ordered
            by dataset path. Dtype includes native descriptors and metadata;
            shape is a tuple. The digest covers fixed-width array bytes in C order,
            independent of HDF compression or storage chunk layout. Coordinates,
            units and CRS are not transformed. No file or artifact is written.

        Raises:
            ValueError: Empty/missing inventory, unsafe or linked paths, unsupported
                variable-width dtype, or invalid read budget.
            OSError: The HDF or a dataset cannot be read.

        Notes:
            Matching complete reference rows proves only those dataset identities.
            It does not compare HDF attributes, projections, boundary associations,
            additional result datasets, whole-file bytes or hydraulic acceptance.
            Callers must bind both HDF digests to fresh native execution receipts
            and validate the surrounding geometry, CRS and attachment contracts.
        """
        import hashlib
        import json

        if isinstance(max_chunk_bytes, bool) or not isinstance(max_chunk_bytes, int):
            raise ValueError("max_chunk_bytes must be a positive integer")
        if max_chunk_bytes <= 0:
            raise ValueError("max_chunk_bytes must be a positive integer")
        base = "Geometry/2D Flow Areas"
        rows = []
        with h5py.File(hdf_path, "r") as hdf:
            mesh_group = hdf
            for part in base.split("/"):
                if part not in mesh_group:
                    raise ValueError("native Geometry/2D Flow Areas group is absent")
                if not isinstance(mesh_group.get(part, getlink=True), h5py.HardLink):
                    raise ValueError("native mesh inventory contains a nonlocal group link")
                mesh_group = mesh_group[part]
                if not isinstance(mesh_group, h5py.Group):
                    raise ValueError("native Geometry/2D Flow Areas group is absent")
            paths = []

            def inspect_links(group, prefix, ancestors):
                address = h5py.h5o.get_info(group.id).addr
                if address in ancestors:
                    raise ValueError("native mesh inventory contains a cyclic group link")
                for name in sorted(group):
                    path = prefix + "/" + name
                    if not isinstance(group.get(name, getlink=True), h5py.HardLink):
                        raise ValueError("native mesh inventory contains a nonlocal link: " + path)
                    item = group[name]
                    if isinstance(item, h5py.Dataset):
                        paths.append(path)
                    elif isinstance(item, h5py.Group):
                        inspect_links(item, path, ancestors | {address})
                    else:
                        raise ValueError("unsupported native mesh object: " + path)

            inspect_links(mesh_group, base, set())
            if dataset_paths is not None:
                if isinstance(dataset_paths, (str, bytes)):
                    raise ValueError("dataset_paths must be a sequence of unique native paths")
                selected = list(dataset_paths)
                if any(not isinstance(p, str) for p in selected):
                    raise ValueError("dataset_paths must contain strings")
                if len(set(selected)) != len(selected):
                    raise ValueError("dataset_paths must contain unique native paths")
                if any(p not in paths for p in selected):
                    raise ValueError("requested native mesh dataset is missing or outside the group")
                paths = sorted(selected)
            if not paths:
                raise ValueError("native mesh dataset inventory is empty")
            for path in paths:
                dataset = hdf[path]
                if dataset.shape is None or dataset.dtype.hasobject:
                    raise ValueError("fixed-width native mesh dataset required: " + path)
                try:
                    dtype = json.dumps(
                        {"descr": dataset.dtype.descr, "metadata": dict(dataset.dtype.metadata or {})},
                        sort_keys=True, separators=(",", ":"),
                    )
                except (TypeError, ValueError) as error:
                    raise ValueError("unsupported native mesh dtype metadata: " + path) from error
                digest = hashlib.sha256()
                if dataset.ndim == 0:
                    if dataset.dtype.itemsize > max_chunk_bytes:
                        raise ValueError("native dataset scalar exceeds max_chunk_bytes: " + path)
                    digest.update(np.asarray(dataset[()], dtype=dataset.dtype).tobytes(order="C"))
                elif dataset.size:
                    row_bytes = dataset.dtype.itemsize * int(np.prod(dataset.shape[1:], dtype=object))
                    if row_bytes > max_chunk_bytes:
                        raise ValueError("native dataset row exceeds max_chunk_bytes: " + path)
                    slab_rows = max(1, max_chunk_bytes // max(1, row_bytes))
                    for start in range(0, dataset.shape[0], slab_rows):
                        digest.update(dataset[start:start + slab_rows].tobytes(order="C"))
                rows.append({
                    "dataset_path": path, "dtype": dtype, "shape": tuple(dataset.shape),
                    "bytes": int(dataset.size) * dataset.dtype.itemsize,
                    "sha256": digest.hexdigest(),
                })
        return pd.DataFrame(rows, columns=["dataset_path", "dtype", "shape", "bytes", "sha256"])

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_area_names(hdf_path: Path) -> List[str]:
        """
        Return a list of the 2D mesh area names from the RAS geometry.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.

        Returns
        -------
        List[str]
            A list of the 2D mesh area names within the RAS geometry.
            Returns an empty list if no 2D areas exist or if there's an error.
        """
        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                if "Geometry/2D Flow Areas" not in hdf_file:
                    return list()
                return list(
                    [
                        HdfUtils.convert_ras_string(n.decode('utf-8'))
                        for n in hdf_file["Geometry/2D Flow Areas/Attributes"][()]["Name"]
                    ]
                )
        except Exception as e:
            logger.error(f"Error reading mesh area names from {hdf_path}: {str(e)}")
            return list()

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

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

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

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

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

                group = hdf_file[base]
                attributes_path = f"{base}/Attributes"
                if "Attributes" not in group:
                    raise _MeshLayoutError("2D Flow Areas/Attributes is missing")
                attributes = group["Attributes"][()]
                if (
                    attributes.dtype.names is None
                    or "Name" not in attributes.dtype.names
                ):
                    raise _MeshLayoutError("2D Flow Areas/Attributes has no Name field")
                mesh_names = [
                    HdfUtils.convert_ras_string(_decode_hdf_scalar(value))
                    for value in attributes["Name"]
                ]

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

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

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

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

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

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

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

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

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

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_areas(hdf_path: Path) -> 'GeoDataFrame':
        """
        Return 2D flow area perimeter polygons.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.

        Returns
        -------
        GeoDataFrame
            A GeoDataFrame containing the 2D flow area perimeter polygons if 2D areas exist.
        """
        # Lazy imports for heavy dependencies
        from geopandas import GeoDataFrame
        from shapely.geometry import Polygon

        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    return GeoDataFrame()
                group = hdf_file["Geometry/2D Flow Areas"]
                mesh_area_polygons = []
                fallback_polygons = None
                for index, name in enumerate(mesh_area_names):
                    perimeter_path = f"{name}/Perimeter"
                    if perimeter_path in group:
                        mesh_area_polygons.append(Polygon(group[perimeter_path][()]))
                        continue
                    if fallback_polygons is None:
                        fallback_polygons = _strict_collection_perimeters(
                            group, mesh_area_names
                        )
                        logger.warning(
                            "Using validated collection-level 2D perimeter "
                            "fallback for %s; named-area face topology may still "
                            "be unavailable",
                            hdf_path.name,
                        )
                    mesh_area_polygons.append(fallback_polygons[index])
                return GeoDataFrame(
                    {"mesh_name": mesh_area_names, "geometry": mesh_area_polygons},
                    geometry="geometry",
                    crs=HdfBase.get_projection(hdf_file),
                )
        except Exception as e:
            logger.error(f"Error reading mesh areas from {hdf_path}: {str(e)}")
            return GeoDataFrame()

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_cell_polygons(
        hdf_path: Path,
        *,
        strict: bool = False,
    ) -> 'GeoDataFrame':
        """
        Return 2D flow mesh cell polygons.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.
        strict : bool, default False
            Raise :class:`MeshCellPolygonError` when a native cell produces no
            polygon or more than one polygon. The default preserves the legacy
            return behavior, emits a warning, and attaches anomaly rows to
            ``result.attrs["cell_polygon_diagnostics"]`` as an equality-safe
            tuple of record dictionaries. Use
            :meth:`diagnose_mesh_cell_polygons` for a DataFrame.

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

        Notes
        -----
        Cell IDs are native, zero-based IDs within each mesh. The returned row
        index must not be treated as a complete or positional cell identifier.
        Use :meth:`diagnose_mesh_cell_polygons` or ``strict=True`` whenever an
        exhaustive physical-cell mask is required.
        """
        # Lazy imports for heavy dependencies
        from geopandas import GeoDataFrame
        from shapely.geometry import Polygon
        from shapely.ops import polygonize

        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    return GeoDataFrame()

                # Get face geometries once
                face_gdf = HdfMesh.get_mesh_cell_faces(hdf_path)

                # Pre-allocate lists for better memory efficiency
                all_mesh_names = []
                all_cell_ids = []
                all_geometries = []
                diagnostics = []

                for mesh_name in mesh_area_names:
                    cell_info_path = (
                        f"Geometry/2D Flow Areas/{mesh_name}/"
                        "Cells Face and Orientation Info"
                    )
                    cell_values_path = (
                        f"Geometry/2D Flow Areas/{mesh_name}/"
                        "Cells Face and Orientation Values"
                    )
                    present = [
                        cell_info_path in hdf_file,
                        cell_values_path in hdf_file,
                    ]
                    if not any(present):
                        logger.warning(
                            "Cell-polygon topology is not present for mesh %r in %s; "
                            "cell centers and collection-level Cell Info/Cell Points "
                            "will not be promoted to polygon topology",
                            mesh_name,
                            hdf_path.name,
                        )
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": None,
                            "face_count": None,
                            "polygon_count": None,
                            "status": "not_present",
                            "reason_code": "cell_topology_not_present",
                            "face_ids": (),
                            "missing_face_ids": (),
                        })
                        continue
                    if not all(present):
                        raise _MeshLayoutError(
                            f"Cell-polygon topology is partial for mesh {mesh_name!r}"
                        )
                    # Get cell face info in one read
                    cell_face_info = hdf_file[cell_info_path][()]
                    cell_face_values = hdf_file[cell_values_path][()][:, 0]

                    # Create face lookup dictionary for this mesh
                    mesh_faces_dict = dict(face_gdf[face_gdf.mesh_name == mesh_name][["face_id", "geometry"]].values)

                    # Process each cell
                    for cell_id, (start, length) in enumerate(cell_face_info[:, :2]):
                        start = int(start)
                        length = int(length)
                        if (
                            start < 0
                            or length < 0
                            or start > len(cell_face_values)
                            or start + length > len(cell_face_values)
                        ):
                            diagnostics.append({
                                "mesh_name": mesh_name,
                                "cell_id": cell_id,
                                "face_count": length,
                                "polygon_count": 0,
                                "status": "omitted",
                                "reason_code": "invalid_face_span",
                                "face_ids": (),
                                "missing_face_ids": (),
                            })
                            continue
                        face_ids = cell_face_values[start:start + length]
                        missing_face_ids = [
                            int(face_id)
                            for face_id in face_ids
                            if face_id not in mesh_faces_dict
                        ]
                        if missing_face_ids:
                            diagnostics.append({
                                "mesh_name": mesh_name,
                                "cell_id": cell_id,
                                "face_count": int(length),
                                "polygon_count": 0,
                                "status": "omitted",
                                "reason_code": "missing_face_reference",
                                "face_ids": tuple(int(value) for value in face_ids),
                                "missing_face_ids": tuple(missing_face_ids),
                            })
                            continue
                        if length == 0:
                            diagnostics.append({
                                "mesh_name": mesh_name,
                                "cell_id": cell_id,
                                "face_count": 0,
                                "polygon_count": 0,
                                "status": "omitted",
                                "reason_code": "zero_faces",
                                "face_ids": (),
                                "missing_face_ids": (),
                            })
                            continue
                        if length < 3:
                            diagnostics.append({
                                "mesh_name": mesh_name,
                                "cell_id": cell_id,
                                "face_count": int(length),
                                "polygon_count": 0,
                                "status": "boundary_only",
                                "reason_code": "insufficient_faces",
                                "face_ids": tuple(int(value) for value in face_ids),
                                "missing_face_ids": (),
                            })
                            continue
                        face_geoms = [mesh_faces_dict[face_id] for face_id in face_ids]

                        # Create polygon
                        polygons = list(polygonize(face_geoms))
                        if not polygons:
                            diagnostics.append({
                                "mesh_name": mesh_name,
                                "cell_id": cell_id,
                                "face_count": int(length),
                                "polygon_count": 0,
                                "status": "omitted",
                                "reason_code": "no_polygon",
                                "face_ids": tuple(int(value) for value in face_ids),
                                "missing_face_ids": (),
                            })
                            continue
                        if len(polygons) > 1:
                            diagnostics.append({
                                "mesh_name": mesh_name,
                                "cell_id": cell_id,
                                "face_count": int(length),
                                "polygon_count": len(polygons),
                                "status": "ambiguous",
                                "reason_code": "multiple_polygons",
                                "face_ids": tuple(int(value) for value in face_ids),
                                "missing_face_ids": (),
                            })
                        all_mesh_names.append(mesh_name)
                        all_cell_ids.append(cell_id)
                        all_geometries.append(Polygon(polygons[0]))

                diagnostics_df = pd.DataFrame(
                    diagnostics,
                    columns=[
                        "mesh_name",
                        "cell_id",
                        "face_count",
                        "polygon_count",
                        "status",
                        "reason_code",
                        "face_ids",
                        "missing_face_ids",
                    ],
                )
                problematic = diagnostics_df[
                    diagnostics_df["status"].isin(
                        ("omitted", "ambiguous", "not_present", "read_error")
                    )
                ]
                if not problematic.empty:
                    summary = ", ".join(
                        f"{mesh!r}: {count}"
                        for mesh, count in problematic.groupby("mesh_name").size().items()
                    )
                    message = (
                        "Mesh cell polygon reconstruction was incomplete or ambiguous "
                        f"({summary}). Inspect diagnose_mesh_cell_polygons(); native "
                        "cell IDs remain authoritative."
                    )
                    if strict:
                        raise MeshCellPolygonError(message)
                    logger.warning(message)

                # Create GeoDataFrame in one go
                result = GeoDataFrame(
                    {
                        "mesh_name": all_mesh_names,
                        "cell_id": all_cell_ids,
                        "geometry": all_geometries
                    },
                    geometry="geometry",
                    crs=HdfBase.get_projection(hdf_file)
                )
                # DataFrames in ``attrs`` make ordinary operations such as
                # ``pd.concat([cells_a, cells_b])`` fail while pandas compares
                # metadata.  Store equality-safe records and keep the public
                # diagnostic method as the DataFrame-returning API.
                result.attrs["cell_polygon_diagnostics"] = tuple(
                    diagnostics_df.to_dict(orient="records")
                )
                return result

        except Exception as e:
            if strict:
                if isinstance(e, MeshCellPolygonError):
                    raise
                raise MeshCellPolygonError(
                    f"Could not reconstruct mesh cell polygons from {hdf_path}: {e}"
                ) from e
            logger.error(f"Error reading mesh cell polygons from {hdf_path}: {str(e)}")
            result = GeoDataFrame()
            result.attrs["cell_polygon_diagnostics"] = ({
                "mesh_name": None,
                "cell_id": None,
                "face_count": None,
                "polygon_count": None,
                "status": "read_error",
                "reason_code": type(e).__name__,
                "face_ids": (),
                "missing_face_ids": (),
            },)
            return result

    @staticmethod
    @log_call
    @standardize_input(file_type='geom_hdf')
    def diagnose_mesh_cell_polygons(hdf_path: Path) -> pd.DataFrame:
        """Return cells not reconstructed as exactly one polygon.

        The result contains the native ``mesh_name`` and zero-based ``cell_id``,
        face and polygon counts, a status and reason code, and the referenced
        face IDs. ``boundary_only`` rows identify validated native one- or
        two-face records and do not make strict reconstruction fail. ``omitted``
        and ``ambiguous`` rows identify physical-cell problems;
        ``not_present`` and ``read_error`` distinguish unavailable or malformed
        topology from a clean reconstruction. An empty result means every
        named mesh supplied topology and every processed physical cell produced
        exactly one polygon.
        """
        polygons = HdfMesh.get_mesh_cell_polygons(hdf_path, strict=False)
        diagnostic_records = polygons.attrs.get("cell_polygon_diagnostics")
        columns = [
            "mesh_name",
            "cell_id",
            "face_count",
            "polygon_count",
            "status",
            "reason_code",
            "face_ids",
            "missing_face_ids",
        ]
        if diagnostic_records is None:
            return pd.DataFrame(columns=[
                "mesh_name",
                "cell_id",
                "face_count",
                "polygon_count",
                "status",
                "reason_code",
                "face_ids",
                "missing_face_ids",
            ])
        return pd.DataFrame.from_records(diagnostic_records, columns=columns)

    @staticmethod
    def _physical_cell_counts(hdf_file: h5py.File) -> Dict[str, int]:
        """Return each 2D flow area's physical (non-ghost) cell count by name.

        HEC-RAS lists a 2D area's physical cells first in ``Cells Center
        Coordinate`` and in cell result arrays, followed by ghost cells outside
        the perimeter. ``Geometry/2D Flow Areas/Attributes`` ``Cell Count`` is
        the physical count. Meshes without a recorded count are omitted.
        """
        attributes = hdf_file.get("Geometry/2D Flow Areas/Attributes")
        if attributes is None or "Cell Count" not in (attributes.dtype.names or ()):
            return {}
        counts = {}
        for row in attributes[()]:
            count = row["Cell Count"]
            if np.isfinite(count) and count > 0:
                counts[str(HdfUtils.convert_ras_string(row["Name"]))] = int(count)
        return counts

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_cell_points(
        hdf_path: Path,
        include_ghost_cells: bool = True,
    ) -> 'GeoDataFrame':
        """
        Return 2D flow mesh cell center points.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.
        include_ghost_cells : bool, optional
            ``Cells Center Coordinate`` lists the physical cells followed by
            ghost cells outside the perimeter (IDs at or above the area's
            ``Attributes`` ``Cell Count``). Default True returns every entry.
            Pass False to return physical cells only, matching mesh polygons
            and the default ghost-free ``HdfResultsMesh`` cell results. A mesh
            whose ``Cell Count`` is not recorded keeps every entry.

        Returns
        -------
        GeoDataFrame
            A GeoDataFrame containing the 2D flow mesh cell center points with columns:
            - mesh_name: str - Name of the 2D flow area
            - cell_id: int - Unique cell identifier (0-indexed)
            - geometry: Point - Cell center point geometry
        """
        # Lazy imports for heavy dependencies
        from geopandas import GeoDataFrame
        from shapely.geometry import Point

        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    return GeoDataFrame()

                # Pre-allocate lists
                all_mesh_names = []
                all_cell_ids = []
                all_points = []
                physical_counts = (
                    {} if include_ghost_cells else HdfMesh._physical_cell_counts(hdf_file)
                )

                for mesh_name in mesh_area_names:
                    # Get all cell centers in one read
                    cell_centers = hdf_file[f"Geometry/2D Flow Areas/{mesh_name}/Cells Center Coordinate"][()]
                    if mesh_name in physical_counts:
                        cell_centers = cell_centers[:physical_counts[mesh_name]]
                    cell_count = len(cell_centers)

                    # Extend lists efficiently
                    all_mesh_names.extend([mesh_name] * cell_count)
                    all_cell_ids.extend(range(cell_count))
                    all_points.extend(Point(coords) for coords in cell_centers)

                # Create GeoDataFrame in one go
                return GeoDataFrame(
                    {
                        "mesh_name": all_mesh_names,
                        "cell_id": all_cell_ids,
                        "geometry": all_points
                    },
                    geometry="geometry",
                    crs=HdfBase.get_projection(hdf_file)
                )

        except Exception as e:
            logger.error(f"Error reading mesh cell points from {hdf_path}: {str(e)}")
            return GeoDataFrame()

    @staticmethod
    @log_call
    @standardize_input(file_type='geom_hdf')
    def get_mesh_cell_faces(hdf_path: Path) -> 'GeoDataFrame':
        """
        Return 2D flow mesh cell faces.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.

        Returns
        -------
        GeoDataFrame
            A GeoDataFrame containing the 2D flow mesh cell faces with columns:
            - mesh_name: str - Name of the 2D flow area
            - face_id: int - Unique face identifier (0-indexed)
            - geometry: LineString - Face edge geometry (may include intermediate perimeter points)
        """
        # Lazy imports for heavy dependencies
        from geopandas import GeoDataFrame
        from shapely.geometry import LineString

        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    return GeoDataFrame()

                # Pre-allocate lists
                all_mesh_names = []
                all_face_ids = []
                all_geometries = []

                for mesh_name in mesh_area_names:
                    mesh_base = f"Geometry/2D Flow Areas/{mesh_name}"
                    dataset_names = (
                        "Faces FacePoint Indexes",
                        "FacePoints Coordinate",
                        "Faces Perimeter Info",
                        "Faces Perimeter Values",
                    )
                    dataset_paths = [
                        f"{mesh_base}/{name}" for name in dataset_names
                    ]
                    present = [path in hdf_file for path in dataset_paths]
                    if not any(present):
                        logger.warning(
                            "Face topology is not present for mesh %r in %s; "
                            "cell centers and collection-level Cell Info/Cell Points "
                            "will not be promoted to faces",
                            mesh_name,
                            hdf_path.name,
                        )
                        continue
                    if not all(present):
                        raise _MeshLayoutError(
                            f"Face topology is partial for mesh {mesh_name!r}"
                        )
                    # Read all data at once
                    facepoints_index = hdf_file[dataset_paths[0]][()]
                    facepoints_coords = hdf_file[dataset_paths[1]][()]
                    faces_perim_info = hdf_file[dataset_paths[2]][()]
                    faces_perim_values = hdf_file[dataset_paths[3]][()]

                    # Process each face
                    for face_id, ((pnt_a_idx, pnt_b_idx), (start_row, count)) in enumerate(zip(facepoints_index, faces_perim_info)):
                        coords = [facepoints_coords[pnt_a_idx]]

                        if count > 0:
                            coords.extend(faces_perim_values[start_row:start_row + count])

                        coords.append(facepoints_coords[pnt_b_idx])

                        all_mesh_names.append(mesh_name)
                        all_face_ids.append(face_id)
                        all_geometries.append(LineString(coords))

                # Create GeoDataFrame in one go
                return GeoDataFrame(
                    {
                        "mesh_name": all_mesh_names,
                        "face_id": all_face_ids,
                        "geometry": all_geometries
                    },
                    geometry="geometry",
                    crs=HdfBase.get_projection(hdf_file)
                )

        except Exception as e:
            logger.error(f"Error reading mesh cell faces from {hdf_path}: {str(e)}")
            return GeoDataFrame()

    @staticmethod
    @log_call
    @standardize_input(file_type="geom_hdf")
    def get_mesh_perimeter_faces(
        hdf_path: str | Path,
        mesh_name: str,
        *,
        ras_object=None,
        on_duplicate_ownership: Literal["raise", "report"] = "raise",
    ) -> "GeoDataFrame":
        """Read every perimeter face of a named 2D area, including unassigned faces.

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

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

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

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

        from .HdfBndry import HdfBndry

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

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_area_attributes(hdf_path: Path) -> pd.DataFrame:
        """
        Return geometry 2D flow area attributes from a HEC-RAS HDF file.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.

        Returns
        -------
        pd.DataFrame
            A DataFrame containing the 2D flow area attributes with:
            - Index: str - Attribute names (e.g., 'Name', 'Cell Count', 'Face Count')
            - Value: varies - Attribute values (decoded from HDF bytes)
        """
        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                d2_flow_area = hdf_file.get("Geometry/2D Flow Areas/Attributes")
                if d2_flow_area is not None and isinstance(d2_flow_area, h5py.Dataset):
                    result = {}
                    for name in d2_flow_area.dtype.names:
                        try:
                            value = d2_flow_area[name][()]
                            if isinstance(value, bytes):
                                value = value.decode('utf-8')  # Decode as UTF-8
                            result[name] = value if not isinstance(value, bytes) else value.decode('utf-8')
                        except Exception as e:
                            logger.warning(f"Error converting attribute '{name}': {str(e)}")
                    return pd.DataFrame.from_dict(result, orient='index', columns=['Value'])
                else:
                    logger.debug("No 2D Flow Area attributes found or invalid dataset.")
                    return pd.DataFrame()  # Return an empty DataFrame
        except Exception as e:
            logger.error(f"Error reading 2D flow area attributes from {hdf_path}: {str(e)}")
            return pd.DataFrame()  # Return an empty DataFrame

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_face_property_tables(hdf_path: Path) -> Dict[str, pd.DataFrame]:
        """
        Extract Face Property Tables for each Face in all 2D Flow Areas.

        Returns elevation-area-wetted perimeter relationships for each face,
        which define the hydraulic properties at different water surface elevations.
        This data is used internally by HEC-RAS for 2D hydraulic computations.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.

        Returns
        -------
        Dict[str, pd.DataFrame]
            A dictionary where:
            - keys: mesh area names (str)
            - values: DataFrames with columns:
                - Face ID: unique identifier for each face (int)
                - Elevation: water surface elevation (float)
                - Area: face area at that elevation (float)
                - Wetted Perimeter: wetted perimeter length at that elevation (float)
                - Manning's n: Manning's roughness coefficient (float)
            Returns an empty dictionary if no 2D areas exist or if there's an error.
            Returns an empty DataFrame with correct columns for meshes where
            property tables don't exist.

        Notes
        -----
        The HDF path for this data is 'Geometry/2D Flow Areas/{mesh_name}/Faces Area Elevation Info'
        and 'Geometry/2D Flow Areas/{mesh_name}/Faces Area Elevation Values'.
        """
        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    logger.error(
                        f"No 2D mesh areas found in {hdf_path}; this API "
                        "requires a geometry HDF with 2D Flow Areas."
                    )
                    return {}

                result = {}
                for mesh_name in mesh_area_names:
                    base_path = f"Geometry/2D Flow Areas/{mesh_name}"
                    info_path = f"{base_path}/Faces Area Elevation Info"
                    values_path = f"{base_path}/Faces Area Elevation Values"

                    if info_path not in hdf_file or values_path not in hdf_file:
                        logger.error(
                            f"Face property tables not found for mesh '{mesh_name}'; "
                            "run the geometry preprocessor to create "
                            "'Faces Area Elevation Info' and "
                            "'Faces Area Elevation Values' before using this API."
                        )
                        result[mesh_name] = pd.DataFrame(columns=['Face ID', 'Elevation', 'Area', 'Wetted Perimeter', "Manning's n"])
                        continue

                    area_elevation_info = hdf_file[info_path][()]
                    area_elevation_values = hdf_file[values_path][()]

                    face_data = []
                    for face_id, (start_index, count) in enumerate(area_elevation_info):
                        face_values = area_elevation_values[start_index:start_index+count]
                        for elevation, area, wetted_perimeter, mannings_n in face_values:
                            face_data.append({
                                'Face ID': face_id,
                                'Elevation': float(elevation),
                                'Area': float(area),
                                'Wetted Perimeter': float(wetted_perimeter),
                                "Manning's n": float(mannings_n)
                            })

                    result[mesh_name] = pd.DataFrame(face_data)

                return result

        except Exception as e:
            logger.error(f"Error extracting face property tables from {hdf_path}: {str(e)}")
            return {}

    @staticmethod
    @log_call
    @standardize_input(file_type='geom_hdf')
    def get_mesh_face_hydraulic_properties_at_stage(
        hdf_path: Path,
        mesh_name: str,
        face_ids,
        water_surface,
        unit_system: str = 'us',
    ):
        """
        Interpolate 2D face hydraulic properties at supplied water-surface stages.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.
        mesh_name : str
            2D flow area name.
        face_ids : scalar or array-like
            Face IDs to evaluate.
        water_surface : scalar, 1D array, or 2D array
            Water-surface elevation(s). Scalars are broadcast to every face.
            1D arrays must contain one value per face. 2D arrays are interpreted
            as time-by-face.
        unit_system : str, default 'us'
            ``'us'``/``'customary'`` uses 1.486 in Manning's conveyance;
            ``'metric'``/``'si'`` uses 1.0.

        Returns
        -------
        xarray.Dataset
            Dataset with dimensions ``time`` and ``face_id`` containing:
            ``area``, ``wetted_perimeter``, ``mannings_n``,
            ``hydraulic_radius``, and ``conveyance``.

        Notes
        -----
        This helper is sourced from the geometry preprocessor face property
        tables stored in the geometry HDF. It is therefore a
        geometry-derived/interpolated view of face hydraulic properties, not
        the canonical native unsteady-results calculation path.

        When native face results such as ``Face Area`` or ``Face Manning's n``
        are available in the plan/results HDF, prefer
        ``HdfResultsMesh.get_mesh_faces_timeseries()`` for QAQC and direct
        comparison to native HEC-RAS output. Those values reflect the solver's
        canonical results path, including aggregation from computational time
        steps to output time steps.

        Conveyance is derived from face property tables using:
        ``K = C * A * (A / P) ** (2 / 3) / n``.

        Stages below the lowest tabulated elevation are treated as dry faces
        with zero area, wetted perimeter, hydraulic radius, and conveyance.
        """
        import xarray as xr

        try:
            coefficient = HdfMesh._manning_conveyance_coefficient(unit_system)
            face_id_array = HdfMesh._normalize_face_ids(face_ids)
            water_surface_array = HdfMesh._normalize_face_water_surface(
                water_surface, len(face_id_array)
            )

            face_property_tables = HdfMesh.get_mesh_face_property_tables(hdf_path)
            if mesh_name not in face_property_tables:
                raise ValueError(
                    f"Mesh '{mesh_name}' not found in face property tables. "
                    f"Available meshes: {list(face_property_tables.keys())}"
                )

            face_lookup = HdfMesh._build_face_property_lookup(
                face_property_tables[mesh_name]
            )

            shape = water_surface_array.shape
            area = np.full(shape, np.nan, dtype=float)
            wetted_perimeter = np.full(shape, np.nan, dtype=float)
            mannings_n = np.full(shape, np.nan, dtype=float)
            above_table_stage_count = 0
            above_table_face_ids = set()
            above_table_max_excess = 0.0

            for col_idx, face_id in enumerate(face_id_array):
                face_table = face_lookup.get(int(face_id))
                if face_table is None or face_table.empty:
                    logger.warning(
                        f"No face property table rows found for face {face_id} "
                        f"in mesh '{mesh_name}'"
                    )
                    continue

                max_table_elevation = float(face_table['Elevation'].max())
                face_water_surface = water_surface_array[:, col_idx]
                above_table_mask = (
                    np.isfinite(face_water_surface)
                    & np.isfinite(max_table_elevation)
                    & (face_water_surface > max_table_elevation)
                )
                if above_table_mask.any():
                    above_count = int(above_table_mask.sum())
                    above_table_stage_count += above_count
                    above_table_face_ids.add(int(face_id))
                    max_excess = float(
                        np.max(face_water_surface[above_table_mask] - max_table_elevation)
                    )
                    above_table_max_excess = max(above_table_max_excess, max_excess)

                interpolated = HdfMesh._interpolate_face_property_table(
                    face_table, water_surface_array[:, col_idx]
                )
                area[:, col_idx] = interpolated['area']
                wetted_perimeter[:, col_idx] = interpolated['wetted_perimeter']
                mannings_n[:, col_idx] = interpolated['mannings_n']

            above_table_face_count = len(above_table_face_ids)
            if above_table_stage_count:
                face_preview = sorted(above_table_face_ids)[:10]
                more_faces = ''
                if above_table_face_count > len(face_preview):
                    more_faces = f" and {above_table_face_count - len(face_preview)} more"
                logger.warning(
                    "Water-surface stages exceed the highest face property table "
                    f"elevation for {above_table_stage_count} stage/face value(s) "
                    f"across {above_table_face_count} face(s) in mesh '{mesh_name}'. "
                    "Values above the table are clipped to the highest tabulated "
                    f"face properties; max exceedance is {above_table_max_excess:.3f}. "
                    f"Face IDs: {face_preview}{more_faces}"
                )

            wet_mask = (area > 0) & (wetted_perimeter > 0)
            hydraulic_radius = np.divide(
                area,
                wetted_perimeter,
                out=np.zeros_like(area, dtype=float),
                where=wet_mask,
            )
            hydraulic_radius[~wet_mask & (np.isnan(area) | np.isnan(wetted_perimeter))] = np.nan

            valid_n = np.isfinite(mannings_n) & (mannings_n > 0)
            conveyance = np.divide(
                coefficient * area * np.power(hydraulic_radius, 2.0 / 3.0),
                mannings_n,
                out=np.zeros_like(area, dtype=float),
                where=wet_mask & valid_n,
            )
            conveyance[wet_mask & ~valid_n] = np.nan
            conveyance[np.isnan(area) | np.isnan(wetted_perimeter)] = np.nan

            return xr.Dataset(
                data_vars={
                    'area': (('time', 'face_id'), area),
                    'wetted_perimeter': (('time', 'face_id'), wetted_perimeter),
                    'mannings_n': (('time', 'face_id'), mannings_n),
                    'hydraulic_radius': (('time', 'face_id'), hydraulic_radius),
                    'conveyance': (('time', 'face_id'), conveyance),
                },
                coords={
                    'time': np.arange(water_surface_array.shape[0], dtype=int),
                    'face_id': face_id_array,
                },
                attrs={
                    'mesh_name': mesh_name,
                    'unit_system': unit_system,
                    'manning_conveyance_coefficient': coefficient,
                    'formula': 'K = C * A * (A / P) ** (2 / 3) / n',
                    'source': 'Geometry/2D Flow Areas/<mesh>/Faces Area Elevation',
                    'source_scope': 'geometry_preprocessor',
                    'above_table_stage_count': above_table_stage_count,
                    'above_table_face_count': above_table_face_count,
                    'above_table_max_excess': above_table_max_excess,
                    'above_table_handling': (
                        'Stages above the last tabulated elevation are clipped '
                        'to the highest tabulated face properties and logged as '
                        'a warning.'
                    ),
                    'preferred_native_alternative': (
                        'Use HdfResultsMesh.get_mesh_faces_timeseries() when '
                        "native Face Area or Face Manning's n outputs are "
                        'available in the plan/results HDF.'
                    ),
                    'dry_face_handling': (
                        'Stages below the first tabulated elevation use zero '
                        'area, wetted perimeter, hydraulic radius, and conveyance.'
                    ),
                },
            )

        except Exception as e:
            logger.error(
                f"Error computing face hydraulic properties from {hdf_path}: {str(e)}"
            )
            raise

    @staticmethod
    @log_call
    @standardize_input(file_type='geom_hdf')
    def get_reference_line_internal_faces(
        hdf_path: Path,
        mesh_name: Optional[str] = None
    ) -> pd.DataFrame:
        """
        Return internal mesh faces associated with native HEC-RAS reference lines.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.
        mesh_name : Optional[str], optional
            If provided, return only reference-line faces for this 2D flow area.

        Returns
        -------
        pd.DataFrame
            Rows keyed by reference line and face with columns such as
            ``reference_line_id``, ``profile_name``, ``mesh_name``, ``face_id``,
            ``fp_start_index``, ``fp_end_index``, ``station_start``,
            ``station_end``, ``station_length``, ``face_length``, and
            ``station_fraction`` where source fields are available. Returns an
            empty DataFrame when reference lines or internal faces are absent.
            ``station_fraction`` is the raw HDF-derived fraction and may be
            outside [0, 1] for unusual station data; consumers should validate
            or clip it before using it as a multiplier.
        """
        columns = [
            'reference_line_id',
            'profile_name',
            'mesh_name',
            'face_id',
            'fp_start_index',
            'fp_end_index',
            'station_start',
            'station_end',
            'station_length',
            'face_length',
            'station_fraction',
        ]

        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                ref_path = "Geometry/Reference Lines"
                attrs_path = f"{ref_path}/Attributes"
                internal_faces_path = f"{ref_path}/Internal Faces"

                if attrs_path not in hdf_file or internal_faces_path not in hdf_file:
                    return pd.DataFrame(columns=columns)

                attributes = hdf_file[attrs_path][()]
                internal_faces = hdf_file[internal_faces_path][()]
                if len(attributes) == 0 or len(internal_faces) == 0:
                    return pd.DataFrame(columns=columns)

                attr_lookup = HdfMesh._reference_line_attribute_lookup(attributes)
                rows = []
                for face_row in internal_faces:
                    reference_line_id = HdfMesh._get_hdf_row_value(
                        face_row, 'Reference Line ID', default=np.nan
                    )
                    if pd.isna(reference_line_id):
                        continue

                    reference_line_id = int(reference_line_id)
                    attr = attr_lookup.get(reference_line_id, {})
                    row_mesh_name = attr.get('mesh_name') or mesh_name
                    if mesh_name is not None and row_mesh_name != mesh_name:
                        continue

                    station_start = HdfMesh._get_hdf_row_value(
                        face_row, 'Station Start', default=np.nan
                    )
                    station_end = HdfMesh._get_hdf_row_value(
                        face_row, 'Station End', default=np.nan
                    )
                    face_id = HdfMesh._get_hdf_row_value(
                        face_row, 'Face Index', default=np.nan
                    )
                    face_length = HdfMesh._get_face_length(
                        hdf_file, row_mesh_name, face_id
                    )

                    station_length = np.nan
                    if np.isfinite(station_start) and np.isfinite(station_end):
                        station_length = float(station_end) - float(station_start)

                    station_fraction = np.nan
                    if np.isfinite(station_length) and np.isfinite(face_length) and face_length > 0:
                        station_fraction = station_length / face_length

                    rows.append({
                        'reference_line_id': reference_line_id,
                        'profile_name': attr.get('profile_name'),
                        'mesh_name': row_mesh_name,
                        'face_id': HdfMesh._safe_int(face_id),
                        'fp_start_index': HdfMesh._safe_int(HdfMesh._get_hdf_row_value(
                            face_row, 'FP Start Index', default=np.nan
                        )),
                        'fp_end_index': HdfMesh._safe_int(HdfMesh._get_hdf_row_value(
                            face_row, 'FP End Index', default=np.nan
                        )),
                        'station_start': float(station_start) if np.isfinite(station_start) else np.nan,
                        'station_end': float(station_end) if np.isfinite(station_end) else np.nan,
                        'station_length': station_length,
                        'face_length': face_length,
                        'station_fraction': station_fraction,
                    })

                return pd.DataFrame(rows, columns=columns)

        except Exception as e:
            logger.error(
                f"Error reading reference line internal faces from {hdf_path}: {str(e)}"
            )
            return pd.DataFrame(columns=columns)

    @staticmethod
    def _manning_conveyance_coefficient(unit_system: str) -> float:
        """Return Manning's conveyance coefficient for a supported unit system."""
        normalized = str(unit_system).strip().lower()
        if normalized in {
            'us',
            'u.s.',
            'us customary',
            'u.s. customary',
            'english',
            'customary',
            'imperial',
        }:
            return 1.486
        if normalized in {'metric', 'si'}:
            return 1.0
        raise ValueError(
            "unit_system must be one of 'us', 'customary', 'english', "
            "'metric', or 'si'"
        )

    @staticmethod
    def _normalize_face_ids(face_ids) -> np.ndarray:
        """Normalize scalar or array-like face IDs to a 1D integer array."""
        face_id_array = np.atleast_1d(np.asarray(face_ids))
        if face_id_array.ndim != 1:
            raise ValueError("face_ids must be a scalar or 1D array-like")
        if face_id_array.size == 0:
            raise ValueError("face_ids must contain at least one face ID")
        return face_id_array.astype(int)

    @staticmethod
    def _normalize_face_water_surface(water_surface, face_count: int) -> np.ndarray:
        """Normalize scalar, per-face, or time-by-face stages to a 2D array."""
        water_surface_array = np.asarray(water_surface, dtype=float)
        if water_surface_array.ndim == 0:
            return np.full((1, face_count), float(water_surface_array), dtype=float)
        if water_surface_array.ndim == 1:
            if water_surface_array.size != face_count:
                raise ValueError(
                    "1D water_surface inputs must have one value per face ID "
                    f"({face_count}); got {water_surface_array.size}"
                )
            return water_surface_array.reshape(1, face_count)
        if water_surface_array.ndim == 2:
            if water_surface_array.shape[1] != face_count:
                raise ValueError(
                    "2D water_surface inputs must have shape time-by-face "
                    f"with {face_count} columns; got {water_surface_array.shape}"
                )
            return water_surface_array
        raise ValueError("water_surface must be scalar, 1D per-face, or 2D time-by-face")

    @staticmethod
    def _build_face_property_lookup(face_property_table: pd.DataFrame) -> Dict[int, pd.DataFrame]:
        """Build a per-face lookup with sorted, de-duplicated elevations."""
        if face_property_table.empty:
            return {}

        lookup = {}
        required = ['Face ID', 'Elevation', 'Area', 'Wetted Perimeter', "Manning's n"]
        missing = [col for col in required if col not in face_property_table.columns]
        if missing:
            raise ValueError(f"Face property table is missing columns: {missing}")

        clean_table = face_property_table.dropna(subset=['Face ID', 'Elevation']).copy()
        for face_id, face_df in clean_table.groupby('Face ID'):
            face_df = (
                face_df
                .sort_values('Elevation')
                .groupby('Elevation', as_index=False)
                .last()
                .reset_index(drop=True)
            )
            lookup[int(face_id)] = face_df
        return lookup

    @staticmethod
    def _interpolate_face_property_table(
        face_table: pd.DataFrame,
        water_surface_values: np.ndarray
    ) -> Dict[str, np.ndarray]:
        """Interpolate face area, wetted perimeter, and Manning's n values."""
        elevations = face_table['Elevation'].to_numpy(dtype=float)
        if elevations.size == 0:
            nan_values = np.full_like(water_surface_values, np.nan, dtype=float)
            return {
                'area': nan_values.copy(),
                'wetted_perimeter': nan_values.copy(),
                'mannings_n': nan_values.copy(),
            }

        area_values = face_table['Area'].to_numpy(dtype=float)
        wetted_perimeter_values = face_table['Wetted Perimeter'].to_numpy(dtype=float)
        mannings_n_values = face_table["Manning's n"].to_numpy(dtype=float)

        area = np.interp(
            water_surface_values,
            elevations,
            area_values,
            left=0.0,
            right=area_values[-1],
        )
        wetted_perimeter = np.interp(
            water_surface_values,
            elevations,
            wetted_perimeter_values,
            left=0.0,
            right=wetted_perimeter_values[-1],
        )
        mannings_n = np.interp(
            water_surface_values,
            elevations,
            mannings_n_values,
            left=mannings_n_values[0],
            right=mannings_n_values[-1],
        )

        dry_mask = water_surface_values < elevations[0]
        area[dry_mask] = 0.0
        wetted_perimeter[dry_mask] = 0.0

        return {
            'area': area,
            'wetted_perimeter': wetted_perimeter,
            'mannings_n': mannings_n,
        }

    @staticmethod
    def _reference_line_attribute_lookup(attributes) -> Dict[int, Dict[str, Any]]:
        """Return reference-line names and mesh names keyed by reference-line ID."""
        lookup = {}
        for idx, attr in enumerate(attributes):
            profile_name = HdfMesh._decode_hdf_value(
                HdfMesh._get_hdf_row_value(attr, 'Name', default='')
            )
            mesh_value = HdfMesh._get_first_hdf_row_value(
                attr, ['SA-2D', 'SA/2D', 'mesh_name', 'Mesh Name'], default=None
            )
            lookup[idx] = {
                'profile_name': profile_name,
                'mesh_name': HdfMesh._decode_hdf_value(mesh_value) if mesh_value is not None else None,
            }
        return lookup

    @staticmethod
    def _get_face_length(hdf_file, mesh_name, face_id) -> float:
        """Read a face length from Faces NormalUnitVector and Length when available."""
        if mesh_name is None or not np.isfinite(face_id):
            return np.nan

        normals_path = f"Geometry/2D Flow Areas/{mesh_name}/Faces NormalUnitVector and Length"
        if normals_path not in hdf_file:
            return np.nan

        normals = hdf_file[normals_path]
        face_index = int(face_id)
        if face_index < 0 or face_index >= normals.shape[0] or normals.shape[1] < 3:
            return np.nan
        return float(normals[face_index, 2])

    @staticmethod
    def _get_first_hdf_row_value(row, names: List[str], default=None):
        """Return the first available named field value from a structured HDF row."""
        for name in names:
            value = HdfMesh._get_hdf_row_value(row, name, default=None)
            if value is not None:
                return value
        return default

    @staticmethod
    def _get_hdf_row_value(row, name: str, default=None):
        """Return a named field from a structured HDF row, or default."""
        dtype_names = getattr(getattr(row, 'dtype', None), 'names', None)
        if dtype_names and name in dtype_names:
            return row[name]
        return default

    @staticmethod
    def _decode_hdf_value(value) -> str:
        """Decode HDF byte/string values with RAS whitespace cleanup."""
        if value is None:
            return None
        try:
            converted = HdfUtils.convert_ras_string(value)
            return converted.strip() if isinstance(converted, str) else converted
        except Exception:
            if isinstance(value, bytes):
                return value.decode('utf-8', errors='ignore').strip()
            return str(value).strip()

    @staticmethod
    def _safe_int(value):
        """Return an int for finite values, otherwise pandas NA."""
        try:
            if pd.isna(value):
                return pd.NA
            return int(value)
        except Exception:
            return pd.NA

    @staticmethod
    @standardize_input(file_type='geom_hdf')
    def get_mesh_cell_property_tables(hdf_path: Path) -> Dict[str, pd.DataFrame]:
        """
        Extract Cell Property Tables for each Cell in all 2D Flow Areas.

        Returns elevation-volume relationships for each cell, which define how
        cell volume changes with water surface elevation. This data is used
        internally by HEC-RAS for 2D hydraulic computations.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS geometry HDF file.

        Returns
        -------
        Dict[str, pd.DataFrame]
            A dictionary where:
            - keys: mesh area names (str)
            - values: DataFrames with columns:
                - Cell ID: unique identifier for each cell
                - Elevation: water surface elevation (float)
                - Volume: cell volume at that elevation (float)
            Returns an empty dictionary if no 2D areas exist or if there's an error.

        Notes
        -----
        The HDF path for this data is 'Geometry/2D Flow Areas/{mesh_name}/Cells Volume Elevation Info'
        and 'Geometry/2D Flow Areas/{mesh_name}/Cells Volume Elevation Values'.

        Cell surface area is stored separately in 'Cells Surface Area' dataset (one value per cell),
        not in the elevation-volume table.
        """
        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    logger.error(
                        f"No 2D mesh areas found in {hdf_path}; this API "
                        "requires a geometry HDF with 2D Flow Areas."
                    )
                    return {}

                result = {}
                for mesh_name in mesh_area_names:
                    base_path = f"Geometry/2D Flow Areas/{mesh_name}"
                    info_path = f"{base_path}/Cells Volume Elevation Info"
                    values_path = f"{base_path}/Cells Volume Elevation Values"

                    if info_path not in hdf_file or values_path not in hdf_file:
                        logger.error(
                            f"Cell volume/elevation tables not found for mesh "
                            f"'{mesh_name}'; run the geometry preprocessor to "
                            "create 'Cells Volume Elevation Info' and "
                            "'Cells Volume Elevation Values' before using this API."
                        )
                        result[mesh_name] = pd.DataFrame(columns=['Cell ID', 'Elevation', 'Volume'])
                        continue

                    cell_elevation_info = hdf_file[info_path][()]
                    cell_elevation_values = hdf_file[values_path][()]

                    cell_data = []
                    for cell_id, (start_index, count) in enumerate(cell_elevation_info):
                        cell_values = cell_elevation_values[start_index:start_index+count]
                        for elevation, volume in cell_values:
                            cell_data.append({
                                'Cell ID': cell_id,
                                'Elevation': float(elevation),
                                'Volume': float(volume),
                            })

                    result[mesh_name] = pd.DataFrame(cell_data)

                return result

        except Exception as e:
            logger.error(f"Error extracting cell property tables from {hdf_path}: {str(e)}")
            return {}

    # =========================================================================
    # Spatial Query Utilities
    # =========================================================================

    @staticmethod
    def find_nearest_face(
        point,
        cell_faces_gdf: 'GeoDataFrame',
        mesh_name: str = None
    ) -> Optional[Tuple[int, float]]:
        """
        Find the nearest mesh cell face to a given point.

        This is useful for locating face elements near a point of interest,
        such as when extracting timeseries data at a specific location.

        Parameters
        ----------
        point : shapely.geometry.Point or tuple
            The query point. Can be a shapely Point or (x, y) tuple.
        cell_faces_gdf : GeoDataFrame
            GeoDataFrame containing cell face geometries, typically from
            get_mesh_cell_faces().
        mesh_name : str, optional
            If provided, filter to only faces in this mesh area.

        Returns
        -------
        Optional[Tuple[int, float]]
            A tuple containing:
            - face_id (int): The ID of the nearest cell face
            - distance (float): The distance to the nearest cell face
            Returns (None, None) if no faces found to search.

        Example
        -------
        >>> cell_faces = HdfMesh.get_mesh_cell_faces(hdf_path)
        >>> face_id, dist = HdfMesh.find_nearest_face((500000, 4000000), cell_faces)
        >>> if face_id is not None:
        ...     print(f"Nearest face: {face_id}, Distance: {dist:.2f}")
        """
        from shapely.geometry import Point

        # Convert tuple to Point if needed
        if isinstance(point, tuple):
            point = Point(point)

        # Filter by mesh_name if provided
        faces = cell_faces_gdf
        if mesh_name is not None:
            faces = faces[faces['mesh_name'] == mesh_name]

        if faces.empty:
            logger.warning("No faces found to search")
            return None, None

        # Calculate distances from point to all faces
        distances = faces.geometry.distance(point)

        # Find the index of minimum distance
        min_idx = distances.idxmin()

        return int(faces.loc[min_idx, 'face_id']), float(distances[min_idx])

    @staticmethod
    def find_nearest_cell(
        point,
        cell_points_gdf: 'GeoDataFrame',
        mesh_name: str = None
    ) -> Optional[Tuple[int, float]]:
        """
        Find the nearest mesh cell center to a given point.

        This is useful for locating cell elements near a point of interest,
        such as when extracting water surface elevations at a specific location.

        Parameters
        ----------
        point : shapely.geometry.Point or tuple
            The query point. Can be a shapely Point or (x, y) tuple.
        cell_points_gdf : GeoDataFrame
            GeoDataFrame containing cell center points, typically from
            get_mesh_cell_points().
        mesh_name : str, optional
            If provided, filter to only cells in this mesh area.

        Returns
        -------
        Optional[Tuple[int, float]]
            A tuple containing:
            - cell_id (int): The ID of the nearest cell
            - distance (float): The distance to the nearest cell center
            Returns (None, None) if no cells found to search.

        Example
        -------
        >>> cell_points = HdfMesh.get_mesh_cell_points(hdf_path)
        >>> cell_id, dist = HdfMesh.find_nearest_cell((500000, 4000000), cell_points)
        >>> if cell_id is not None:
        ...     print(f"Nearest cell: {cell_id}, Distance: {dist:.2f}")
        """
        from shapely.geometry import Point

        # Convert tuple to Point if needed
        if isinstance(point, tuple):
            point = Point(point)

        # Filter by mesh_name if provided
        cells = cell_points_gdf
        if mesh_name is not None:
            cells = cells[cells['mesh_name'] == mesh_name]

        if cells.empty:
            logger.warning("No cells found to search")
            return None, None

        # Calculate distances from point to all cell centers
        distances = cells.geometry.distance(point)

        # Find the index of minimum distance
        min_idx = distances.idxmin()

        return int(cells.loc[min_idx, 'cell_id']), float(distances[min_idx])

    @staticmethod
    def _calculate_line_angle(line) -> float:
        """
        Calculate the bearing angle of a line segment in degrees.

        Parameters
        ----------
        line : shapely.geometry.LineString
            The line geometry to calculate angle for.

        Returns
        -------
        float
            Angle in degrees (0-360).
        """
        from shapely.geometry import LineString

        if isinstance(line, LineString):
            x_diff = line.xy[0][-1] - line.xy[0][0]
            y_diff = line.xy[1][-1] - line.xy[1][0]
        else:
            # Assume it's a tuple of coordinates
            x_diff = line[1][0] - line[0][0]
            y_diff = line[1][1] - line[0][1]

        angle = np.degrees(np.arctan2(y_diff, x_diff))
        return angle % 360 if angle >= 0 else (angle + 360) % 360

    @staticmethod
    def _angle_difference(angle1: float, angle2: float) -> float:
        """
        Calculate minimum angle difference accounting for 180 degree equivalence.

        For face selection, we consider faces perpendicular to the profile line,
        so a face at 0 degrees is equivalent to one at 180 degrees.

        Parameters
        ----------
        angle1 : float
            First angle in degrees.
        angle2 : float
            Second angle in degrees.

        Returns
        -------
        float
            Minimum angle difference in degrees (0-90).
        """
        diff = abs(angle1 - angle2) % 180
        return min(diff, 180 - diff)

    @staticmethod
    def _break_line_into_segments(
        line,
        segment_length: float
    ) -> Tuple[List, List[float]]:
        """
        Break a line into segments of specified length and calculate angles.

        Parameters
        ----------
        line : shapely.geometry.LineString
            The line to break into segments.
        segment_length : float
            Target length for each segment.

        Returns
        -------
        Tuple[List, List[float]]
            A tuple containing:
            - List of segment geometries
            - List of angles for each segment
        """
        from shapely.geometry import LineString

        segments = []
        segment_angles = []

        total_length = line.length
        num_segments = max(1, int(total_length / segment_length))

        for i in range(num_segments):
            start_dist = i * segment_length
            end_dist = min((i + 1) * segment_length, total_length)

            start_point = line.interpolate(start_dist)
            end_point = line.interpolate(end_dist)

            segment = LineString([start_point, end_point])
            segments.append(segment)
            segment_angles.append(HdfMesh._calculate_line_angle(segment))

        return segments, segment_angles

    @staticmethod
    def get_faces_along_profile_line(
        profile_line,
        cell_faces_gdf: 'GeoDataFrame',
        distance_threshold: float = 10.0,
        angle_threshold: float = 60.0,
        mesh_name: str = None,
        order_by_distance: bool = True
    ) -> 'GeoDataFrame':
        """
        Get mesh cell faces that align with a profile line.

        This function finds faces that are:
        1. Within a distance threshold of the profile line
        2. Oriented perpendicular to the profile line (within angle threshold)

        This is useful for extracting cross-sectional flow data along a
        transect or profile line.

        Parameters
        ----------
        profile_line : shapely.geometry.LineString
            The profile line to find faces along.
        cell_faces_gdf : GeoDataFrame
            GeoDataFrame containing cell face geometries, typically from
            get_mesh_cell_faces().
        distance_threshold : float, default 10.0
            Maximum distance from profile line to include a face.
        angle_threshold : float, default 60.0
            Maximum angle deviation from perpendicular (degrees).
            A value of 90 would include faces parallel to the profile.
        mesh_name : str, optional
            If provided, filter to only faces in this mesh area.
        order_by_distance : bool, default True
            If True, order faces by distance along the profile line.

        Returns
        -------
        GeoDataFrame
            A GeoDataFrame containing selected faces with additional columns:
            - distance_along_profile: Distance from profile start
            - angle_to_profile: Angle deviation from perpendicular

        Example
        -------
        >>> from shapely.geometry import LineString
        >>> profile = LineString([(500000, 4000000), (501000, 4000000)])
        >>> cell_faces = HdfMesh.get_mesh_cell_faces(hdf_path)
        >>> profile_faces = HdfMesh.get_faces_along_profile_line(
        ...     profile, cell_faces, distance_threshold=15, angle_threshold=45
        ... )
        >>> print(f"Found {len(profile_faces)} faces along profile")
        """
        # Filter by mesh_name if provided
        faces = cell_faces_gdf.copy()
        if mesh_name is not None:
            faces = faces[faces['mesh_name'] == mesh_name]

        if faces.empty:
            logger.warning("No faces found to search")
            return faces

        # Break profile line into segments for angle comparison
        segments, segment_angles = HdfMesh._break_line_into_segments(
            profile_line, distance_threshold
        )

        # Find faces that match criteria
        selected_indices = set()
        face_angles = {}

        for face_idx, face_row in faces.iterrows():
            face_geom = face_row.geometry
            face_angle = HdfMesh._calculate_line_angle(face_geom)

            # Check each profile segment
            for segment, segment_angle in zip(segments, segment_angles):
                # Check distance
                if face_geom.distance(segment) <= distance_threshold:
                    # Check angle (perpendicular = 90 degree difference)
                    # We want faces perpendicular to profile, so target is segment_angle + 90
                    perpendicular_angle = (segment_angle + 90) % 360
                    angle_diff = HdfMesh._angle_difference(face_angle, perpendicular_angle)

                    if angle_diff <= angle_threshold:
                        selected_indices.add(face_idx)
                        face_angles[face_idx] = angle_diff
                        break

        # Create result GeoDataFrame
        if not selected_indices:
            logger.debug("No faces found along profile line with given thresholds")
            result = faces.iloc[0:0].copy()  # Empty GeoDataFrame with same structure
            result['distance_along_profile'] = []
            result['angle_to_profile'] = []
            return result

        result = faces.loc[list(selected_indices)].copy()

        # Calculate distance along profile for each face
        result['distance_along_profile'] = result.geometry.apply(
            lambda g: profile_line.project(g.centroid)
        )
        result['angle_to_profile'] = result.index.map(face_angles)

        # Order by distance along profile if requested
        if order_by_distance:
            result = result.sort_values('distance_along_profile').reset_index(drop=True)

        logger.debug(f"Found {len(result)} faces along profile line")
        return result

    @staticmethod
    def combine_faces_to_linestring(
        faces_gdf: 'GeoDataFrame',
        order_column: str = 'distance_along_profile'
    ) -> Optional[Any]:
        """
        Combine ordered faces into a single LineString.

        This is useful for creating a continuous line from selected profile faces.

        Parameters
        ----------
        faces_gdf : GeoDataFrame
            GeoDataFrame of faces to combine, should be ordered.
        order_column : str, default 'distance_along_profile'
            Column to use for ordering faces.

        Returns
        -------
        Optional[shapely.geometry.LineString]
            A LineString combining all face geometries, or None if faces_gdf is empty
            or fewer than 2 coordinates found.
        """
        from shapely.geometry import LineString

        if faces_gdf.empty:
            return None

        # Ensure ordered
        if order_column in faces_gdf.columns:
            faces_gdf = faces_gdf.sort_values(order_column)

        coords = []
        for _, face in faces_gdf.iterrows():
            face_coords = list(face.geometry.coords)
            if not coords:
                # First face - add all coordinates
                coords.extend(face_coords)
            else:
                # Subsequent faces - add only if not duplicate
                for coord in face_coords:
                    if coord != coords[-1]:
                        coords.append(coord)

        if len(coords) < 2:
            return None

        return LineString(coords)

    # =========================================================================
    # Sloped Interpolation Topology
    # =========================================================================

    @staticmethod
    @standardize_input(file_type='plan_hdf')
    def get_mesh_sloped_topology(
        hdf_path: Path,
        mesh_name: str = None
    ) -> Dict[str, Any]:
        """
        Extract all mesh topology needed for sloped water surface interpolation.

        This function performs a single HDF read to extract all geometric and
        topological data required for RASMapper's "Sloped (Cell Corners)"
        water surface rasterization algorithm.

        Parameters
        ----------
        hdf_path : Path
            Path to the HEC-RAS plan HDF file.
        mesh_name : str, optional
            Name of the specific mesh area to extract. If None, uses the first
            mesh area found.

        Returns
        -------
        Dict[str, Any]
            Dictionary containing all topology data:

            - 'mesh_name': str - Name of the mesh area
            - 'n_cells': int - Number of cells
            - 'n_faces': int - Number of faces
            - 'n_facepoints': int - Number of facepoints (vertices)

            Coordinates:
            - 'cell_centers': ndarray (n_cells, 2) float64 - Cell center X, Y
            - 'facepoint_coords': ndarray (n_facepoints, 2) float64 - Vertex X, Y

            Minimum elevations:
            - 'cell_min_elev': ndarray (n_cells,) float32 - Min terrain per cell
            - 'face_min_elev': ndarray (n_faces,) float32 - Min terrain per face

            Face connectivity:
            - 'face_cells': ndarray (n_faces, 2) int32 - [cell_a, cell_b] per face
              (-1 indicates perimeter/boundary)
            - 'face_facepoints': ndarray (n_faces, 2) int32 - [fp_a, fp_b] per face

            Facepoint-to-face connectivity (CSR-like):
            - 'facepoint_face_info': ndarray (n_facepoints, 2) int32 - [start, count]
            - 'facepoint_face_values': ndarray (n_connections, 2) int32 - [face_idx, orientation]

            Cell-to-face connectivity (CSR-like):
            - 'cell_face_info': ndarray (n_cells, 2) int32 - [start, count]
            - 'cell_face_values': ndarray (n_connections, 2) int32 - [face_idx, orientation]

        Notes
        -----
        The CSR-like format for variable-length connectivity uses:
        - info array: [start_index, count] per element
        - values array: actual connections, accessed as values[start:start+count]

        The orientation value indicates which side of the face the element is on:
        - 0: "a" side (first cell in face_cells)
        - 1: "b" side (second cell in face_cells)

        Example
        -------
        ```python
        >>> topology = HdfMesh.get_mesh_sloped_topology(plan_hdf_path)
        >>> print(f"Mesh: {topology['mesh_name']}")
        >>> print(f"Cells: {topology['n_cells']}, Faces: {topology['n_faces']}")
        >>>
        >>> # Access faces connected to facepoint 0
        >>> start, count = topology['facepoint_face_info'][0]
        >>> connected_faces = topology['facepoint_face_values'][start:start+count, 0]
        ```
        """
        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                # Get mesh area names
                mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
                if not mesh_area_names:
                    logger.error(
                        f"No 2D mesh areas found in {hdf_path}; this API "
                        "requires a geometry HDF with 2D Flow Areas."
                    )
                    return {}

                # Select mesh
                if mesh_name is None:
                    mesh_name = mesh_area_names[0]
                    if len(mesh_area_names) > 1:
                        logger.info(f"Multiple meshes found, using first: {mesh_name}")
                elif mesh_name not in mesh_area_names:
                    logger.error(f"Mesh '{mesh_name}' not found. Available: {mesh_area_names}")
                    return {}

                base_path = f"Geometry/2D Flow Areas/{mesh_name}"

                # Read all datasets in single file context
                cell_centers = hdf_file[f"{base_path}/Cells Center Coordinate"][()]
                cell_min_elev = hdf_file[f"{base_path}/Cells Minimum Elevation"][()]
                cell_face_info = hdf_file[f"{base_path}/Cells Face and Orientation Info"][()]
                cell_face_values = hdf_file[f"{base_path}/Cells Face and Orientation Values"][()]

                face_min_elev = hdf_file[f"{base_path}/Faces Minimum Elevation"][()]
                face_cells = hdf_file[f"{base_path}/Faces Cell Indexes"][()]
                face_facepoints = hdf_file[f"{base_path}/Faces FacePoint Indexes"][()]

                facepoint_coords = hdf_file[f"{base_path}/FacePoints Coordinate"][()]
                facepoint_face_info = hdf_file[f"{base_path}/FacePoints Face and Orientation Info"][()]
                facepoint_face_values = hdf_file[f"{base_path}/FacePoints Face and Orientation Values"][()]

                # Build result dictionary
                return {
                    # Metadata
                    'mesh_name': mesh_name,
                    'n_cells': len(cell_centers),
                    'n_faces': len(face_cells),
                    'n_facepoints': len(facepoint_coords),

                    # Coordinates
                    'cell_centers': cell_centers,
                    'facepoint_coords': facepoint_coords,

                    # Minimum elevations
                    'cell_min_elev': cell_min_elev,
                    'face_min_elev': face_min_elev,

                    # Face connectivity
                    'face_cells': face_cells,
                    'face_facepoints': face_facepoints,

                    # Facepoint-to-face connectivity (CSR-like)
                    'facepoint_face_info': facepoint_face_info,
                    'facepoint_face_values': facepoint_face_values,

                    # Cell-to-face connectivity (CSR-like)
                    'cell_face_info': cell_face_info,
                    'cell_face_values': cell_face_values,
                }

        except KeyError as e:
            logger.error(f"Missing required dataset in {hdf_path}: {e}")
            return {}
        except Exception as e:
            logger.error(f"Error reading sloped topology from {hdf_path}: {e}")
            return {}

    @staticmethod
    @log_call
    @standardize_input(file_type='geom_hdf')
    def get_mannings_calibration_table(hdf_path: Path) -> Optional[pd.DataFrame]:
        """Retrieve the Manning's n calibration table from a HEC-RAS geometry HDF file.

        Reads the compound dataset at
        ``Geometry/Land Cover (Manning's n)/Calibration Table`` which contains
        land cover names, base Manning's n values, and per-region calibration
        factors.

        Args:
            hdf_path: Path to the HEC-RAS geometry HDF file.

        Returns:
            A DataFrame with columns for each field in the calibration table
            (land cover name, base Manning's n, and one column per calibration
            region), or ``None`` if the dataset does not exist.

        Example
        -------
        >>> df = HdfMesh.get_mannings_calibration_table("model.g01.hdf")
        >>> print(df.columns.tolist()[:3])
        ['Land Cover Name', "Base Manning's n Value", ...]
        """
        try:
            with h5py.File(hdf_path, 'r') as hdf_file:
                table_path = "Geometry/Land Cover (Manning's n)/Calibration Table"
                if table_path not in hdf_file:
                    logger.error(
                        f"No Manning's n calibration table found in {hdf_path}; "
                        "create Manning's n calibration regions before using "
                        "this API."
                    )
                    return None

                data = hdf_file[table_path][()]

                df_dict = {}
                for field_name in data.dtype.names:
                    values = data[field_name]
                    if values.dtype.kind == 'S':
                        values = [v.decode('utf-8').strip() for v in values]
                    df_dict[field_name] = values

                return pd.DataFrame(df_dict)

        except Exception as e:
            logger.error(f"Error reading Manning's n calibration table from {hdf_path}: {str(e)}")
            return None

    # -------------------------------------------------------------------------
    # Write API: Face Property Tables (Manning's n vs Elevation)
    # -------------------------------------------------------------------------

    _LINUX_TMP_HDF_PATTERN = re.compile(
        r"\.p\d+\.tmp\.hdf$",
        re.IGNORECASE,
    )
    _LINUX_TMP_HDF_FILE_TYPE = "HEC-RAS Results"
    _LINUX_TMP_HDF_FILE_VERSION = "HEC-RAS 7.0 April 2026"
    _LINUX_TMP_EXPERIMENTAL_NOTICE = (
        "EXPERIMENTAL / NOT RECOMMENDED FOR PRODUCTION OR OTHER "
        "NON-EXPERIMENTAL USE. Tested only with HEC-RAS 7.0 April 2026 "
        "in the Windows-preprocess/Linux-solve '*.p##.tmp.hdf' workflow; "
        "all other versions and workflows are untested."
    )
    _FACE_PROPERTY_COLUMNS = (
        "Elevation",
        "Area",
        "Wetted Perimeter",
        "Manning's n",
    )

    @staticmethod
    def _decode_hdf_attr(value: Any) -> str:
        """Decode a scalar HDF attribute used by write-role guards."""
        if value is None:
            return ""
        if isinstance(value, bytes):
            return value.decode("utf-8", errors="replace").strip("\x00")
        if hasattr(value, "decode"):
            return value.decode("utf-8", errors="replace").strip("\x00")
        return str(value).strip("\x00")

    @staticmethod
    def _require_linux_tmp_write_acknowledgement(
        acknowledge_unsupported: bool,
    ) -> None:
        """Require an explicit acknowledgement before direct HDF mutation."""
        if not acknowledge_unsupported:
            raise RuntimeError(
                f"{HdfMesh._LINUX_TMP_EXPERIMENTAL_NOTICE} Direct "
                "face-property HDF writes require "
                "acknowledge_unsupported=True."
            )
        logger.warning(HdfMesh._LINUX_TMP_EXPERIMENTAL_NOTICE)

    @staticmethod
    def _validate_linux_tmp_face_table_schema(
        hdf_file: h5py.File,
        hdf_path: Path,
        mesh_name: str,
    ) -> Tuple[str, str, np.ndarray, np.ndarray]:
        """Validate the exact HEC-RAS 7.0 Linux temporary-result schema."""
        if not HdfMesh._LINUX_TMP_HDF_PATTERN.search(hdf_path.name):
            raise ValueError(
                "Direct face-property writes accept only filenames matching "
                "'*.p##.tmp.hdf'."
            )

        file_type = HdfMesh._decode_hdf_attr(hdf_file.attrs.get("File Type"))
        file_version = HdfMesh._decode_hdf_attr(
            hdf_file.attrs.get("File Version")
        )
        if file_type != HdfMesh._LINUX_TMP_HDF_FILE_TYPE:
            raise ValueError(
                "Linux temporary-HDF role guard requires root "
                f"File Type={HdfMesh._LINUX_TMP_HDF_FILE_TYPE!r}; "
                f"observed {file_type!r}."
            )
        if file_version != HdfMesh._LINUX_TMP_HDF_FILE_VERSION:
            raise ValueError(
                "Linux temporary-HDF version guard requires root "
                f"File Version={HdfMesh._LINUX_TMP_HDF_FILE_VERSION!r}; "
                f"observed {file_version!r}."
            )
        if "Geometry" not in hdf_file:
            raise ValueError("Temporary result HDF is missing /Geometry.")
        complete = HdfMesh._decode_hdf_attr(
            hdf_file["Geometry"].attrs.get("Complete Geometry")
        )
        if complete.lower() != "true":
            raise ValueError(
                "Temporary result HDF must have Complete Geometry=True before "
                "face-property writes."
            )

        base_path = f"Geometry/2D Flow Areas/{mesh_name}"
        info_path = f"{base_path}/Faces Area Elevation Info"
        values_path = f"{base_path}/Faces Area Elevation Values"
        facepoints_path = f"{base_path}/Faces FacePoint Indexes"
        for dataset_path in (info_path, values_path, facepoints_path):
            if dataset_path not in hdf_file:
                raise KeyError(
                    f"Required HEC-RAS 7.0 face-table dataset is missing: "
                    f"{dataset_path}"
                )
            if not isinstance(hdf_file[dataset_path], h5py.Dataset):
                raise ValueError(
                    f"Expected an HDF dataset at {dataset_path!r}."
                )

        old_info = hdf_file[info_path][()]
        old_values = hdf_file[values_path][()]
        facepoints = hdf_file[facepoints_path]
        if (
            old_info.ndim != 2
            or old_info.shape[1] != 2
            or old_info.shape[0] == 0
            or old_info.dtype.kind not in "iu"
        ):
            raise ValueError(
                f"{info_path} must be a nonempty integer (N, 2) dataset."
            )
        if (
            old_values.ndim != 2
            or old_values.shape[1] != 4
            or old_values.shape[0] == 0
            or old_values.dtype.kind not in "f"
        ):
            raise ValueError(
                f"{values_path} must be a nonempty floating-point (M, 4) "
                "dataset."
            )
        if (
            facepoints.ndim != 2
            or facepoints.shape[0] != old_info.shape[0]
            or facepoints.shape[1] < 2
            or facepoints.dtype.kind not in "iu"
        ):
            raise ValueError(
                f"{facepoints_path} must be an integer dataset with one row "
                "per face."
            )

        starts = old_info[:, 0].astype(np.int64, copy=False)
        counts = old_info[:, 1].astype(np.int64, copy=False)
        if np.any(starts < 0) or np.any(counts <= 0):
            raise ValueError(
                "Face property-table starts must be nonnegative and counts "
                "must be positive."
            )
        expected_starts = np.concatenate(
            ([0], np.cumsum(counts[:-1], dtype=np.int64))
        )
        if not np.array_equal(starts, expected_starts):
            raise ValueError(
                "Faces Area Elevation Info is not contiguous from row zero."
            )
        if int(starts[-1] + counts[-1]) != old_values.shape[0]:
            raise ValueError(
                "Face property-table Info rows do not cover the Values "
                "dataset exactly."
            )
        HdfMesh._validate_face_property_values(
            old_values,
            context="existing face property tables",
            info=old_info,
        )
        return info_path, values_path, old_info, old_values

    @staticmethod
    def _validate_face_property_values(
        values: np.ndarray,
        *,
        context: str,
        info: Optional[np.ndarray] = None,
    ) -> None:
        """Require finite hydraulic values and nonnegative physical columns."""
        values = np.asarray(values)
        if values.ndim != 2 or values.shape[1] != 4 or values.shape[0] == 0:
            raise ValueError(f"{context} must be a nonempty (N, 4) array.")
        if not np.isfinite(values).all():
            raise ValueError(f"{context} contains NaN or infinite values.")
        if np.any(values[:, 1:] < 0):
            raise ValueError(
                f"{context} contains negative Area, Wetted Perimeter, or "
                "Manning's n values."
            )
        if info is None:
            if values.shape[0] > 1 and not np.all(np.diff(values[:, 0]) > 0):
                raise ValueError(
                    f"{context} elevations must be strictly increasing."
                )
            return
        for face_id, (start, count) in enumerate(info):
            elevations = values[int(start): int(start + count), 0]
            if elevations.size > 1 and not np.all(np.diff(elevations) > 0):
                raise ValueError(
                    f"{context} face {face_id} elevations must be strictly "
                    "increasing."
                )

    @staticmethod
    def _normalize_linux_tmp_face_ids(
        face_ids: Optional[List[int]],
        num_faces: int,
    ) -> Optional[List[int]]:
        """Normalize face IDs and fail closed on duplicates or bounds errors."""
        if face_ids is None:
            return None
        normalized: List[int] = []
        seen = set()
        for value in face_ids:
            if isinstance(value, (bool, np.bool_)):
                raise ValueError(f"Face ID must be an integer, got {value!r}.")
            try:
                face_id = int(value)
            except (TypeError, ValueError) as exc:
                raise ValueError(
                    f"Face ID must be an integer, got {value!r}."
                ) from exc
            if isinstance(value, (float, np.floating)) and not float(
                value
            ).is_integer():
                raise ValueError(f"Face ID must be an integer, got {value!r}.")
            if face_id < 0 or face_id >= num_faces:
                raise ValueError(
                    f"Face ID {face_id} out of range; expected 0-"
                    f"{num_faces - 1}."
                )
            if face_id in seen:
                raise ValueError(f"Duplicate face ID: {face_id}.")
            seen.add(face_id)
            normalized.append(face_id)
        return normalized

    @staticmethod
    def _create_linux_tmp_hdf_backup(hdf_path: Path) -> Path:
        """Create a unique full-file backup immediately before a direct write."""
        timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
        unique_suffix = uuid4().hex[:8]
        backup_path = hdf_path.with_name(
            f"{hdf_path.stem}.pre-write.{timestamp}_{unique_suffix}.bak.hdf"
        )
        shutil.copy2(hdf_path, backup_path)
        logger.debug(
            "Backed up guarded Linux temporary HDF: %s",
            backup_path,
        )
        return backup_path

    @staticmethod
    @log_call
    def write_linux_tmp_face_property_tables(
        hdf_path: Union[str, Path],
        mesh_name: str,
        face_tables: Mapping[int, pd.DataFrame],
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> Path:
        """Write face tables to a guarded HEC-RAS 7.0 Linux ``.tmp.hdf``.

        Warning:
            EXPERIMENTAL. Not recommended for production or any other
            non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
            the Windows-preprocess/Linux-solve temporary-HDF workflow; all
            other versions and workflows are untested.

        This API is limited to the proven two-phase workflow: preprocess a plan
        into ``*.p##.tmp.hdf``, modify that temporary result, then pass it to
        ``RasCmdr.compute_plan_linux()``. The exact root file role/version,
        mesh schema, face IDs, and hydraulic values are checked before a unique
        full-file backup is created. The file is reopened after writing for
        exact Info/Values readback verification.

        ``pin_tables=True`` only sets the mesh ``Pinned`` metadata attribute.
        It does not protect edits from Windows HEC-RAS preprocessing.

        Args:
            hdf_path: HEC-RAS 7.0 ``*.p##.tmp.hdf`` path.
            mesh_name: Exact 2D flow-area name.
            face_tables: Face ID to DataFrame mapping. Required columns are
                ``Elevation``, ``Area``, ``Wetted Perimeter``, and
                ``Manning's n``.
            pin_tables: Set the informational ``Pinned`` attribute after the
                table write.
            acknowledge_unsupported: Must be explicitly ``True``.

        Returns:
            Path to the full-file pre-write backup.
        """
        HdfMesh._require_linux_tmp_write_acknowledgement(
            acknowledge_unsupported
        )
        hdf_path = Path(hdf_path)
        if not hdf_path.exists():
            raise FileNotFoundError(hdf_path)
        if not isinstance(face_tables, Mapping) or not face_tables:
            raise ValueError("face_tables must be a nonempty mapping.")

        base_path = f"Geometry/2D Flow Areas/{mesh_name}"
        with h5py.File(hdf_path, "r") as hdf_file:
            (
                info_path,
                values_path,
                old_info,
                old_values,
            ) = HdfMesh._validate_linux_tmp_face_table_schema(
                hdf_file,
                hdf_path,
                mesh_name,
            )
            old_info_ds = hdf_file[info_path]
            old_values_ds = hdf_file[values_path]
            num_faces = old_info.shape[0]
            info_attrs = dict(old_info_ds.attrs)
            values_attrs = dict(old_values_ds.attrs)

        normalized_ids = HdfMesh._normalize_linux_tmp_face_ids(
            list(face_tables),
            num_faces,
        )
        normalized_tables: Dict[int, np.ndarray] = {}
        for original_id, face_id in zip(face_tables, normalized_ids or []):
            table = face_tables[original_id]
            if not isinstance(table, pd.DataFrame):
                raise TypeError(
                    f"Face {face_id} table must be a pandas DataFrame."
                )
            missing = [
                column
                for column in HdfMesh._FACE_PROPERTY_COLUMNS
                if column not in table.columns
            ]
            if missing:
                raise ValueError(
                    f"Face {face_id} table missing columns: {missing}"
                )
            try:
                rows = table.loc[
                    :,
                    list(HdfMesh._FACE_PROPERTY_COLUMNS),
                ].to_numpy(dtype=float)
            except (TypeError, ValueError) as exc:
                raise ValueError(
                    f"Face {face_id} table contains nonnumeric values."
                ) from exc
            HdfMesh._validate_face_property_values(
                rows,
                context=f"face {face_id} replacement table",
            )
            normalized_tables[face_id] = rows.astype(
                old_values.dtype,
                copy=False,
            )

        new_face_slices = []
        for face_id in range(num_faces):
            if face_id in normalized_tables:
                new_face_slices.append(normalized_tables[face_id])
            else:
                start, count = old_info[face_id]
                new_face_slices.append(
                    old_values[int(start): int(start + count)]
                )

        new_values = np.vstack(new_face_slices).astype(
            old_values.dtype,
            copy=False,
        )
        new_info = np.zeros((num_faces, 2), dtype=old_info.dtype)
        offset = 0
        for face_id, face_slice in enumerate(new_face_slices):
            new_info[face_id, 0] = offset
            new_info[face_id, 1] = len(face_slice)
            offset += len(face_slice)
        HdfMesh._validate_face_property_values(
            new_values,
            context="rewritten face property tables",
            info=new_info,
        )

        # Creation kwargs depend on the final shapes, so reopen read-only after
        # constructing the replacement arrays.
        with h5py.File(hdf_path, "r") as hdf_file:
            info_create_kwargs = HdfMesh._dataset_create_kwargs(
                hdf_file[info_path],
                new_shape=new_info.shape,
            )
            values_create_kwargs = HdfMesh._dataset_create_kwargs(
                hdf_file[values_path],
                new_shape=new_values.shape,
            )

        backup_path = HdfMesh._create_linux_tmp_hdf_backup(hdf_path)
        try:
            with h5py.File(hdf_path, "r+") as hdf_file:
                del hdf_file[info_path]
                del hdf_file[values_path]

                ds_info = hdf_file.create_dataset(
                    info_path,
                    data=new_info,
                    **info_create_kwargs,
                )
                for key, value in info_attrs.items():
                    ds_info.attrs[key] = value

                ds_values = hdf_file.create_dataset(
                    values_path,
                    data=new_values,
                    **values_create_kwargs,
                )
                for key, value in values_attrs.items():
                    ds_values.attrs[key] = value

                if pin_tables:
                    hdf_file[base_path].attrs["Pinned"] = np.bool_(True)

            with h5py.File(hdf_path, "r") as hdf_file:
                (
                    _,
                    _,
                    observed_info,
                    observed_values,
                ) = HdfMesh._validate_linux_tmp_face_table_schema(
                    hdf_file,
                    hdf_path,
                    mesh_name,
                )
                if not np.array_equal(observed_info, new_info):
                    raise RuntimeError(
                        "Faces Area Elevation Info failed exact readback."
                    )
                if not np.array_equal(observed_values, new_values):
                    raise RuntimeError(
                        "Faces Area Elevation Values failed exact readback."
                    )
                if pin_tables and not bool(
                    hdf_file[base_path].attrs.get("Pinned", False)
                ):
                    raise RuntimeError(
                        "Mesh Pinned attribute failed readback."
                    )
        except Exception as exc:
            raise RuntimeError(
                "Guarded face-property write failed. Restore the full-file "
                f"backup at {backup_path}: {exc}"
            ) from exc

        logger.info(
            "Wrote guarded face property tables for %d faces in mesh %r "
            "(%d total rows); backup=%s",
            len(normalized_tables),
            mesh_name,
            new_values.shape[0],
            backup_path,
        )
        return backup_path

    @staticmethod
    @log_call
    def set_mesh_face_property_tables(
        hdf_path: Union[str, Path],
        mesh_name: str,
        face_tables: Dict[int, pd.DataFrame],
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> None:
        """Deprecated wrapper for :meth:`write_linux_tmp_face_property_tables`."""
        warnings.warn(
            "HdfMesh.set_mesh_face_property_tables() is deprecated; use "
            "write_linux_tmp_face_property_tables(). The compatibility name "
            "is retained through v1.1.x and will be removed no earlier than "
            "v1.2.0.",
            DeprecationWarning,
            stacklevel=2,
        )
        HdfMesh.write_linux_tmp_face_property_tables(
            hdf_path,
            mesh_name,
            face_tables,
            pin_tables=pin_tables,
            acknowledge_unsupported=acknowledge_unsupported,
        )

    @staticmethod
    def _dataset_create_kwargs(
        dataset: h5py.Dataset,
        new_shape: Optional[Tuple[int, ...]] = None,
    ) -> Dict[str, Any]:
        """
        Return creation keyword arguments needed to recreate an HDF dataset.

        HEC-RAS geometry and preprocessed plan HDF datasets can use chunking,
        compression, filters, fill values, and unlimited dimensions. Preserve
        those properties when rewriting face property tables so solver-facing
        files keep their original HDF layout.
        """
        kwargs: Dict[str, Any] = {}

        if dataset.chunks is not None:
            chunks = dataset.chunks
            if new_shape is not None:
                chunks = tuple(
                    min(chunk_dim, shape_dim)
                    for chunk_dim, shape_dim in zip(chunks, new_shape)
                )
            kwargs["chunks"] = chunks
        if dataset.maxshape is not None:
            maxshape = dataset.maxshape
            if new_shape is not None:
                maxshape = tuple(
                    None if max_dim is None else max(max_dim, shape_dim)
                    for max_dim, shape_dim in zip(maxshape, new_shape)
                )
            kwargs["maxshape"] = maxshape
        if dataset.compression is not None:
            kwargs["compression"] = dataset.compression
        if dataset.compression_opts is not None:
            kwargs["compression_opts"] = dataset.compression_opts
        if dataset.shuffle:
            kwargs["shuffle"] = True
        if dataset.fletcher32:
            kwargs["fletcher32"] = True
        if dataset.scaleoffset is not None:
            kwargs["scaleoffset"] = dataset.scaleoffset
        if dataset.fillvalue is not None:
            kwargs["fillvalue"] = dataset.fillvalue

        return kwargs

    @staticmethod
    @log_call
    def extend_linux_tmp_face_property_tables(
        hdf_path: Union[str, Path],
        mesh_name: str,
        extension_elevation: float,
        mannings_n_func: Callable[[float, float], float],
        elevation_step: float = 0.5,
        face_ids: Optional[List[int]] = None,
        polygon=None,
        region_name: Optional[str] = None,
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> Dict[str, Any]:
        """
        Extend guarded Linux temporary face tables to higher elevations.

        For each target face, appends rows from the current table maximum up
        to ``extension_elevation``. Area is extrapolated above the terrain
        maximum using the native face length when available, falling back to
        the last Wetted Perimeter value. Wetted Perimeter is held at the last
        tabulated value. Manning's n at each new elevation is computed via
        ``mannings_n_func``.

        .. warning::
            EXPERIMENTAL. Not recommended for production or any other
            non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
            the workflow below; all other versions and workflows are untested.
            Edits are overwritten by the Windows HEC-RAS geometry preprocessor
            on the next plan execution. The tested Linux two-phase workflow is:
            (1) preprocess on Windows via
            ``RasPreprocess.preprocess_plan()`` to generate the ``.tmp.hdf``,
            (2) apply edits to the ``.tmp.hdf``, (3) execute with
            ``RasCmdr.compute_plan_linux()``. This is an undocumented and
            unsupported method of injecting modified HDF inputs into the
            solver and may produce erroneous results.

        Parameters
        ----------
        hdf_path : Union[str, Path]
            Guarded HEC-RAS 7.0 ``*.p##.tmp.hdf`` result artifact.
        mesh_name : str
            Name of the 2D flow area.
        extension_elevation : float
            Target maximum elevation for the extended tables.
        mannings_n_func : Callable[[float, float], float]
            Function ``(depth, base_n) -> n`` where *depth* is the water
            depth above the face's minimum elevation and *base_n* is the
            Manning's n from the last existing table row.
        elevation_step : float, default 0.5
            Elevation increment between new rows.
        face_ids : Optional[List[int]]
            List of face IDs to extend. ``None`` extends all faces whose
            current maximum is below ``extension_elevation``.
        polygon : shapely Polygon/MultiPolygon or GeoDataFrame, optional
            If provided and ``face_ids`` is None, only extend faces whose
            midpoint falls within this polygon.
        region_name : str, optional
            If provided and ``face_ids`` is None, only extend faces within
            the named Manning's n calibration region from the geometry HDF.
            Precedence: ``face_ids`` > ``region_name`` > ``polygon``.
        pin_tables : bool, default True
            Pin tables after modification.

        Returns
        -------
        Dict[str, Any]
            Structured mutation report with ``rows_added``,
            ``faces_modified``, ``total_rows_added``, and ``backup_path``.
        """
        HdfMesh._require_linux_tmp_write_acknowledgement(
            acknowledge_unsupported
        )
        hdf_path = Path(hdf_path)
        base_path = f"Geometry/2D Flow Areas/{mesh_name}"
        info_path = f"{base_path}/Faces Area Elevation Info"
        values_path = f"{base_path}/Faces Area Elevation Values"

        if not np.isfinite(extension_elevation):
            raise ValueError("extension_elevation must be finite")
        if not np.isfinite(elevation_step) or elevation_step <= 0:
            raise ValueError("elevation_step must be finite and positive")

        with h5py.File(hdf_path, "r") as hdf_file:
            (
                _,
                _,
                old_info,
                _,
            ) = HdfMesh._validate_linux_tmp_face_table_schema(
                hdf_file,
                hdf_path,
                mesh_name,
            )
        num_faces = old_info.shape[0]
        explicit_face_ids = HdfMesh._normalize_linux_tmp_face_ids(
            face_ids,
            num_faces,
        )

        resolved = HdfMesh._resolve_face_ids(
            hdf_path,
            mesh_name,
            explicit_face_ids,
            polygon,
            region_name,
        )

        with h5py.File(str(hdf_path), 'r') as hdf_file:
            old_info = hdf_file[info_path][()]
            old_values = hdf_file[values_path][()]
            normals_path = f"{base_path}/Faces NormalUnitVector and Length"
            face_lengths = (
                hdf_file[normals_path][:, 2]
                if normals_path in hdf_file and hdf_file[normals_path].shape[1] >= 3
                else None
            )

        if resolved is None:
            face_ids_to_extend = list(range(num_faces))
        else:
            face_ids_to_extend = HdfMesh._normalize_linux_tmp_face_ids(
                list(resolved),
                num_faces,
            ) or []

        modified_tables: Dict[int, pd.DataFrame] = {}
        rows_added: Dict[int, int] = {}

        for fid in face_ids_to_extend:
            start, count = old_info[fid]
            face_vals = old_values[start:start + count]

            max_elev = face_vals[-1, 0]
            if max_elev >= extension_elevation:
                continue

            min_elev = face_vals[0, 0]
            last_area = face_vals[-1, 1]
            last_wp = face_vals[-1, 2]
            base_n = face_vals[-1, 3]
            top_width = last_wp
            if face_lengths is not None and fid < len(face_lengths):
                face_length = float(face_lengths[fid])
                if np.isfinite(face_length) and face_length > 0:
                    top_width = face_length

            new_rows = []

            def _build_extended_row(elev):
                depth_above_max = elev - max_elev
                new_area = last_area + top_width * depth_above_max
                new_wp = last_wp
                total_depth = elev - min_elev
                new_n = mannings_n_func(total_depth, base_n)
                return [elev, new_area, new_wp, new_n]

            elev = max_elev + elevation_step
            while elev <= extension_elevation + 1e-6:
                new_rows.append(_build_extended_row(elev))
                elev += elevation_step

            if not new_rows or new_rows[-1][0] < extension_elevation - 1e-6:
                new_rows.append(_build_extended_row(extension_elevation))

            if not new_rows:
                continue

            combined = np.vstack([face_vals, np.array(new_rows, dtype=np.float32)])
            df = pd.DataFrame(combined, columns=['Elevation', 'Area', 'Wetted Perimeter', "Manning's n"])
            modified_tables[fid] = df
            rows_added[fid] = len(new_rows)

        backup_path = None
        if modified_tables:
            backup_path = HdfMesh.write_linux_tmp_face_property_tables(
                hdf_path,
                mesh_name,
                modified_tables,
                pin_tables=pin_tables,
                acknowledge_unsupported=True,
            )

        logger.info(
            f"Extended {len(rows_added)} face tables in mesh '{mesh_name}', "
            f"total rows added: {sum(rows_added.values())}"
        )
        return {
            "rows_added": rows_added,
            "faces_modified": len(rows_added),
            "total_rows_added": sum(rows_added.values()),
            "backup_path": backup_path,
        }

    @staticmethod
    @log_call
    def extend_face_property_tables(
        hdf_path: Union[str, Path],
        mesh_name: str,
        extension_elevation: float,
        mannings_n_func: Callable[[float, float], float],
        elevation_step: float = 0.5,
        face_ids: Optional[List[int]] = None,
        polygon=None,
        region_name: Optional[str] = None,
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> Dict[int, int]:
        """Deprecated wrapper for guarded Linux temporary-table extension."""
        warnings.warn(
            "HdfMesh.extend_face_property_tables() is deprecated; use "
            "extend_linux_tmp_face_property_tables(). The compatibility name "
            "is retained through v1.1.x and will be removed no earlier than "
            "v1.2.0.",
            DeprecationWarning,
            stacklevel=2,
        )
        report = HdfMesh.extend_linux_tmp_face_property_tables(
            hdf_path,
            mesh_name,
            extension_elevation,
            mannings_n_func,
            elevation_step=elevation_step,
            face_ids=face_ids,
            polygon=polygon,
            region_name=region_name,
            pin_tables=pin_tables,
            acknowledge_unsupported=acknowledge_unsupported,
        )
        return report["rows_added"]

    @staticmethod
    @log_call
    def transform_linux_tmp_face_mannings_n(
        hdf_path: Union[str, Path],
        mesh_name: str,
        mannings_n_func: Callable[[float, float, float], float],
        face_ids: Optional[List[int]] = None,
        polygon=None,
        region_name: Optional[str] = None,
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> Dict[str, Any]:
        """Transform Manning's n in guarded Linux temporary face tables.

        Preserves Elevation, Area, and Wetted Perimeter columns. Only the
        Manning's n column is recomputed.

        .. warning::
            EXPERIMENTAL. Not recommended for production or any other
            non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
            the workflow below; all other versions and workflows are untested.
            Edits are overwritten by the Windows HEC-RAS geometry preprocessor
            on the next plan execution. The tested Linux two-phase workflow is:
            (1) preprocess on Windows via
            ``RasPreprocess.preprocess_plan()`` to generate the ``.tmp.hdf``,
            (2) apply edits to the ``.tmp.hdf``, (3) execute with
            ``RasCmdr.compute_plan_linux()``. This is an undocumented and
            unsupported method of injecting modified HDF inputs into the
            solver and may produce erroneous results.

        Parameters
        ----------
        hdf_path : Union[str, Path]
            Guarded HEC-RAS 7.0 ``*.p##.tmp.hdf`` result artifact.
        mesh_name : str
            Name of the 2D flow area.
        mannings_n_func : Callable[[float, float, float], float]
            Function ``(elevation, depth, current_n) -> new_n`` where
            *elevation* is the row elevation, *depth* is elevation minus
            the face minimum elevation, and *current_n* is the existing
            Manning's n value.
        face_ids : Optional[List[int]]
            Faces to modify. ``None`` modifies all faces.
        polygon : shapely Polygon/MultiPolygon or GeoDataFrame, optional
            If provided and ``face_ids`` is None, only modify faces whose
            midpoint falls within this polygon.
        region_name : str, optional
            If provided and ``face_ids`` is None, only modify faces within
            the named Manning's n calibration region from the geometry HDF.
            Precedence: ``face_ids`` > ``region_name`` > ``polygon``.
        pin_tables : bool, default True
            Pin tables after modification.

        Returns
        -------
        Dict[str, Any]
            Structured mutation report with ``faces_modified`` and the
            full-file ``backup_path``.
        """
        HdfMesh._require_linux_tmp_write_acknowledgement(
            acknowledge_unsupported
        )
        hdf_path = Path(hdf_path)

        with h5py.File(hdf_path, "r") as hdf_file:
            (
                _,
                _,
                old_info,
                old_values,
            ) = HdfMesh._validate_linux_tmp_face_table_schema(
                hdf_file,
                hdf_path,
                mesh_name,
            )
        num_faces = old_info.shape[0]
        explicit_face_ids = HdfMesh._normalize_linux_tmp_face_ids(
            face_ids,
            num_faces,
        )
        resolved = HdfMesh._resolve_face_ids(
            hdf_path,
            mesh_name,
            explicit_face_ids,
            polygon,
            region_name,
        )

        if resolved is None:
            target_ids = list(range(num_faces))
        else:
            target_ids = HdfMesh._normalize_linux_tmp_face_ids(
                list(resolved),
                num_faces,
            ) or []

        modified_tables: Dict[int, pd.DataFrame] = {}

        for fid in target_ids:
            start, count = old_info[fid]
            face_vals = old_values[start:start + count].copy()

            min_elev = face_vals[0, 0]
            for i in range(count):
                elev = float(face_vals[i, 0])
                depth = elev - float(min_elev)
                current_n = float(face_vals[i, 3])
                face_vals[i, 3] = mannings_n_func(elev, depth, current_n)

            df = pd.DataFrame(
                face_vals,
                columns=HdfMesh._FACE_PROPERTY_COLUMNS,
            )
            modified_tables[fid] = df

        backup_path = None
        if modified_tables:
            backup_path = HdfMesh.write_linux_tmp_face_property_tables(
                hdf_path,
                mesh_name,
                modified_tables,
                pin_tables=pin_tables,
                acknowledge_unsupported=True,
            )

        logger.info(f"Modified Manning's n for {len(modified_tables)} faces in mesh '{mesh_name}'")
        return {
            "faces_modified": len(modified_tables),
            "backup_path": backup_path,
        }

    @staticmethod
    @log_call
    def set_face_mannings_n_values(
        hdf_path: Union[str, Path],
        mesh_name: str,
        mannings_n_func: Callable[[float, float, float], float],
        face_ids: Optional[List[int]] = None,
        polygon=None,
        region_name: Optional[str] = None,
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> int:
        """Deprecated wrapper for guarded Linux temporary Manning transforms."""
        warnings.warn(
            "HdfMesh.set_face_mannings_n_values() is deprecated; use "
            "transform_linux_tmp_face_mannings_n(). The compatibility name "
            "is retained through v1.1.x and will be removed no earlier than "
            "v1.2.0.",
            DeprecationWarning,
            stacklevel=2,
        )
        report = HdfMesh.transform_linux_tmp_face_mannings_n(
            hdf_path,
            mesh_name,
            mannings_n_func,
            face_ids=face_ids,
            polygon=polygon,
            region_name=region_name,
            pin_tables=pin_tables,
            acknowledge_unsupported=acknowledge_unsupported,
        )
        return report["faces_modified"]

    @staticmethod
    @log_call
    def sample_linux_tmp_face_mannings_n_from_landcover_curves(
        hdf_path: Union[str, Path],
        mesh_name: str,
        curves: pd.DataFrame,
        landcover_hdf_path: Optional[Union[str, Path]] = None,
        face_ids: Optional[List[int]] = None,
        sample_spacing: float = 10.0,
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> Dict[str, Any]:
        """Sample land-cover curves into guarded Linux temporary face tables.

        The land-cover raster is sampled along each target face. For each face
        table elevation, class-specific roughness values are interpolated by
        depth and combined with an equal-class power mean (exponent 1.5).
        Repeated samples do not add weight: this is a class-presence heuristic,
        not fraction-, length-, area-, or conveyance-weighted roughness.
        Faces outside the raster or containing only nodata retain their original
        values.

        .. warning::
            EXPERIMENTAL. Not recommended for production or any other
            non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
            the workflow below; all other versions and workflows are untested.
            Edits are overwritten by the Windows HEC-RAS geometry preprocessor
            on the next plan execution. The tested Linux two-phase workflow is:
            (1) preprocess on Windows via
            ``RasPreprocess.preprocess_plan()`` to generate the ``.tmp.hdf``,
            (2) apply edits to the ``.tmp.hdf``, (3) execute with
            ``RasCmdr.compute_plan_linux()``. This is an undocumented and
            unsupported method of injecting modified HDF inputs into the
            solver and may produce erroneous results.

        Parameters
        ----------
        hdf_path : Union[str, Path]
            Guarded HEC-RAS 7.0 ``*.p##.tmp.hdf`` result artifact.
        mesh_name : str
            Name of the 2D flow area.
        curves : pd.DataFrame
            Depth-varying roughness curves with ``pixel_value``, ``depth``, and
            ``mannings_n`` columns.
        landcover_hdf_path : Optional[Union[str, Path]]
            Land-cover HDF path. The sidecar ``.tif`` raster is sampled.
        face_ids : Optional[List[int]]
            Faces to recompute. ``None`` recomputes all faces with sampled
            land-cover classes.
        sample_spacing : float, default 10.0
            Maximum spacing for additional samples along each face.
        pin_tables : bool, default True
            Pin tables after modification.

        Returns
        -------
        Dict[str, Any]
            Structured mutation report with ``faces_modified`` and the
            full-file ``backup_path``.
        """
        HdfMesh._require_linux_tmp_write_acknowledgement(
            acknowledge_unsupported
        )
        if landcover_hdf_path is None:
            raise ValueError("landcover_hdf_path is required")
        if not np.isfinite(sample_spacing) or sample_spacing <= 0:
            raise ValueError("sample_spacing must be finite and positive")

        import rasterio

        hdf_path = Path(hdf_path)
        with h5py.File(hdf_path, "r") as hdf_file:
            (
                _,
                _,
                old_info,
                _,
            ) = HdfMesh._validate_linux_tmp_face_table_schema(
                hdf_file,
                hdf_path,
                mesh_name,
            )
            hdf_projection = HdfMesh._decode_hdf_attr(
                hdf_file.attrs.get("Projection")
            )
        num_faces = old_info.shape[0]
        explicit_face_ids = HdfMesh._normalize_linux_tmp_face_ids(
            face_ids,
            num_faces,
        )

        landcover_hdf_path = Path(landcover_hdf_path)
        landcover_tif_path = landcover_hdf_path.with_suffix(".tif")
        if not landcover_tif_path.exists():
            candidates = sorted(
                landcover_hdf_path.parent.glob(f"{landcover_hdf_path.stem}*.tif")
            )
            if not candidates:
                raise FileNotFoundError(
                    f"Land cover TIF not found for {landcover_hdf_path}"
                )
            landcover_tif_path = candidates[0]

        required = {"pixel_value", "depth", "mannings_n"}
        missing = required - set(curves.columns)
        if missing:
            raise ValueError(f"curves missing columns: {sorted(missing)}")
        try:
            curve_values = curves.loc[
                :,
                ["pixel_value", "depth", "mannings_n"],
            ].to_numpy(dtype=float)
        except (TypeError, ValueError) as exc:
            raise ValueError("curves columns must be numeric.") from exc
        if curve_values.size == 0:
            raise ValueError("curves must contain at least one row.")
        if not np.isfinite(curve_values).all():
            raise ValueError("curves contains NaN or infinite values.")
        if np.any(curve_values[:, 0] < 0):
            raise ValueError("curves pixel_value values must be nonnegative.")
        if not np.all(curve_values[:, 0] == np.floor(curve_values[:, 0])):
            raise ValueError("curves pixel_value values must be integers.")
        if np.any(curve_values[:, 1:] < 0):
            raise ValueError(
                "curves depth and mannings_n values must be nonnegative."
            )

        curve_lookup = {}
        for pixel_value, group in curves.groupby("pixel_value"):
            group = group.sort_values("depth")
            depths = group["depth"].to_numpy(dtype=float)
            mannings_values = group["mannings_n"].to_numpy(dtype=float)
            if depths.size > 1 and not np.all(np.diff(depths) > 0):
                raise ValueError(
                    f"curves depths for pixel_value {pixel_value!r} must be "
                    "strictly increasing."
                )
            curve_lookup[int(pixel_value)] = (depths, mannings_values)

        face_tables_by_mesh = HdfMesh.get_mesh_face_property_tables(hdf_path)
        if mesh_name not in face_tables_by_mesh:
            raise KeyError(f"Face property tables not found for mesh '{mesh_name}'")
        face_tables = face_tables_by_mesh[mesh_name]

        faces_gdf = HdfMesh.get_mesh_cell_faces(hdf_path)
        if faces_gdf.empty:
            return {
                "faces_modified": 0,
                "backup_path": None,
            }
        faces_gdf = faces_gdf[faces_gdf["mesh_name"] == mesh_name]

        if explicit_face_ids is None:
            target_ids = sorted(face_tables["Face ID"].astype(int).unique())
        else:
            target_ids = explicit_face_ids

        def _line_sample_points(line):
            points = list(line.coords)
            if line.length > sample_spacing:
                distance = sample_spacing
                while distance < line.length:
                    points.append(line.interpolate(distance).coords[0])
                    distance += sample_spacing
            return points

        modified_tables: Dict[int, pd.DataFrame] = {}
        with rasterio.open(landcover_tif_path) as src:
            if src.crs is None:
                raise ValueError("Land-cover raster has no CRS.")
            if not hdf_projection:
                raise ValueError(
                    "Temporary result HDF has no root Projection attribute."
                )
            try:
                hdf_crs = rasterio.crs.CRS.from_wkt(hdf_projection)
            except Exception as exc:
                raise ValueError(
                    "Temporary result HDF Projection is not valid WKT."
                ) from exc
            if hdf_crs != src.crs:
                raise ValueError(
                    "Land-cover raster CRS does not match the temporary "
                    "result HDF Projection."
                )
            nodata = src.nodata
            for fid in target_ids:
                face_rows = faces_gdf[faces_gdf["face_id"].astype(int) == fid]
                if face_rows.empty:
                    continue

                sample_points = _line_sample_points(face_rows.iloc[0].geometry)
                sampled_classes = set()
                for sample in src.sample(sample_points):
                    if len(sample) == 0:
                        continue
                    value = sample[0]
                    if nodata is not None and value == nodata:
                        continue
                    pixel_value = int(value)
                    if pixel_value in curve_lookup:
                        sampled_classes.add(pixel_value)

                if not sampled_classes:
                    continue

                face_table = face_tables[
                    face_tables["Face ID"].astype(int) == fid
                ].copy()
                if face_table.empty:
                    continue

                min_elev = float(face_table["Elevation"].min())
                updated = face_table[
                    ['Elevation', 'Area', 'Wetted Perimeter', "Manning's n"]
                ].copy()
                for idx, row in updated.iterrows():
                    depth = float(row["Elevation"]) - min_elev
                    n_values = []
                    for pixel_value in sorted(sampled_classes):
                        depths, mannings_values = curve_lookup[pixel_value]
                        n_values.append(
                            float(np.interp(depth, depths, mannings_values))
                        )
                    updated.at[idx, "Manning's n"] = float(
                        np.mean(np.power(n_values, 1.5)) ** (1.0 / 1.5)
                    )

                modified_tables[fid] = updated

        backup_path = None
        if modified_tables:
            backup_path = HdfMesh.write_linux_tmp_face_property_tables(
                hdf_path,
                mesh_name,
                modified_tables,
                pin_tables=pin_tables,
                acknowledge_unsupported=True,
            )

        logger.info(
            f"Recomputed face Manning's n for {len(modified_tables)} faces "
            f"in mesh '{mesh_name}'"
        )
        return {
            "faces_modified": len(modified_tables),
            "backup_path": backup_path,
        }

    @staticmethod
    @log_call
    def recompute_face_mannings_n_from_landcover_curves(
        hdf_path: Union[str, Path],
        mesh_name: str,
        curves: pd.DataFrame,
        landcover_hdf_path: Optional[Union[str, Path]] = None,
        face_ids: Optional[List[int]] = None,
        sample_spacing: float = 10.0,
        pin_tables: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> int:
        """Deprecated wrapper for the equal-class Linux temporary-table API."""
        warnings.warn(
            "HdfMesh.recompute_face_mannings_n_from_landcover_curves() is "
            "deprecated; use "
            "sample_linux_tmp_face_mannings_n_from_landcover_curves(). This "
            "method is not conveyance-weighted. The compatibility name is "
            "retained through v1.1.x and will be removed no earlier than "
            "v1.2.0.",
            DeprecationWarning,
            stacklevel=2,
        )
        report = HdfMesh.sample_linux_tmp_face_mannings_n_from_landcover_curves(
            hdf_path,
            mesh_name,
            curves,
            landcover_hdf_path=landcover_hdf_path,
            face_ids=face_ids,
            sample_spacing=sample_spacing,
            pin_tables=pin_tables,
            acknowledge_unsupported=acknowledge_unsupported,
        )
        return report["faces_modified"]

    @staticmethod
    @log_call
    def set_mesh_pinned_attribute(
        hdf_path: Union[str, Path],
        mesh_name: str,
        pinned: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> Path:
        """Set or clear guarded Linux temporary-HDF ``Pinned`` metadata.

        Warning:
            EXPERIMENTAL. Not recommended for production or any other
            non-experimental use. Tested only with HEC-RAS 7.0 April 2026 in
            the Windows-preprocess/Linux-solve temporary-HDF workflow; all
            other versions and workflows are untested.

        ``Pinned`` is informational metadata that may be recognized by
        RASMapper. It is ignored by Windows HEC-RAS preprocessing and does not
        protect modified face tables. This method therefore accepts only the
        guarded 7.0 Linux two-phase ``*.p##.tmp.hdf`` role, requires explicit
        acknowledgement, creates a full-file backup, and verifies readback.

        Returns:
            Path to the full-file pre-write backup.
        """
        HdfMesh._require_linux_tmp_write_acknowledgement(
            acknowledge_unsupported
        )
        hdf_path = Path(hdf_path)
        if not hdf_path.exists():
            raise FileNotFoundError(hdf_path)
        group_path = f"Geometry/2D Flow Areas/{mesh_name}"

        with h5py.File(hdf_path, "r") as hdf_file:
            HdfMesh._validate_linux_tmp_face_table_schema(
                hdf_file,
                hdf_path,
                mesh_name,
            )

        backup_path = HdfMesh._create_linux_tmp_hdf_backup(hdf_path)
        try:
            with h5py.File(hdf_path, "r+") as hdf_file:
                group = hdf_file[group_path]
                if pinned:
                    group.attrs["Pinned"] = np.bool_(True)
                elif "Pinned" in group.attrs:
                    del group.attrs["Pinned"]

            with h5py.File(hdf_path, "r") as hdf_file:
                HdfMesh._validate_linux_tmp_face_table_schema(
                    hdf_file,
                    hdf_path,
                    mesh_name,
                )
                group = hdf_file[group_path]
                if pinned and not bool(group.attrs.get("Pinned", False)):
                    raise RuntimeError("Mesh Pinned attribute failed readback.")
                if not pinned and "Pinned" in group.attrs:
                    raise RuntimeError(
                        "Mesh Pinned attribute was not removed on readback."
                    )
        except Exception as exc:
            raise RuntimeError(
                "Guarded Pinned-attribute write failed. Restore the full-file "
                f"backup at {backup_path}: {exc}"
            ) from exc

        action = "Pinned" if pinned else "Unpinned"
        logger.info(
            "%s informational metadata for mesh %r; backup=%s",
            action,
            mesh_name,
            backup_path,
        )
        return backup_path

    @staticmethod
    @log_call
    def pin_property_tables(
        hdf_path: Union[str, Path],
        mesh_name: str,
        pinned: bool = True,
        *,
        acknowledge_unsupported: bool = False,
    ) -> None:
        """Deprecated wrapper for :meth:`set_mesh_pinned_attribute`."""
        warnings.warn(
            "HdfMesh.pin_property_tables() is deprecated; use "
            "set_mesh_pinned_attribute(). The Pinned attribute is "
            "informational and does not protect tables from Windows "
            "preprocessing. The compatibility name is retained through "
            "v1.1.x and will be removed no earlier than v1.2.0.",
            DeprecationWarning,
            stacklevel=2,
        )
        HdfMesh.set_mesh_pinned_attribute(
            hdf_path,
            mesh_name,
            pinned=pinned,
            acknowledge_unsupported=acknowledge_unsupported,
        )

    # -------------------------------------------------------------------------
    # Spatial Filtering: Polygon Mask for Selective Face Application
    # -------------------------------------------------------------------------

    @staticmethod
    @log_call
    def get_face_ids_in_polygon(
        hdf_path: Union[str, Path],
        mesh_name: str,
        polygon,
        method: str = 'midpoint',
    ) -> List[int]:
        """
        Return face IDs whose geometry falls within a polygon boundary.

        Parameters
        ----------
        hdf_path : Union[str, Path]
            Path to the HEC-RAS geometry HDF file (.g##.hdf).
        mesh_name : str
            Name of the 2D flow area / mesh.
        polygon : shapely.geometry.Polygon, shapely.geometry.MultiPolygon, or GeoDataFrame
            The masking polygon. If a GeoDataFrame is provided, all
            geometries are unioned into a single polygon.
        method : str, default 'midpoint'
            How to test each face against the polygon:
            - ``'midpoint'``: face midpoint must be within the polygon
            - ``'any_vertex'``: at least one face vertex must be within

        Returns
        -------
        List[int]
            Sorted list of face IDs (0-indexed) that satisfy the spatial filter.
        """
        from geopandas import GeoDataFrame
        from shapely import prepare
        from shapely.geometry import MultiPolygon, Point
        from shapely.ops import unary_union

        if isinstance(polygon, GeoDataFrame):
            polygon = unary_union(polygon.geometry)
        if isinstance(polygon, MultiPolygon):
            pass
        prepare(polygon)

        faces_gdf = HdfMesh.get_mesh_cell_faces(hdf_path)
        if faces_gdf.empty:
            return []

        faces_gdf = faces_gdf[faces_gdf['mesh_name'] == mesh_name]
        if faces_gdf.empty:
            return []

        matching_ids = []

        if method == 'midpoint':
            for _, row in faces_gdf.iterrows():
                mid = row.geometry.interpolate(0.5, normalized=True)
                if polygon.contains(mid):
                    matching_ids.append(int(row['face_id']))
        elif method == 'any_vertex':
            for _, row in faces_gdf.iterrows():
                coords = list(row.geometry.coords)
                if any(polygon.contains(Point(c)) for c in coords):
                    matching_ids.append(int(row['face_id']))
        else:
            raise ValueError(f"method must be 'midpoint' or 'any_vertex', got '{method}'")

        logger.debug(
            f"Found {len(matching_ids)} faces in polygon "
            f"(mesh '{mesh_name}', method='{method}')"
        )
        return sorted(matching_ids)

    @staticmethod
    @log_call
    def get_face_ids_in_calibration_region(
        hdf_path: Union[str, Path],
        mesh_name: str,
        region_name: str,
        method: str = 'midpoint',
    ) -> List[int]:
        """
        Return face IDs within a named Manning's n calibration region.

        Reads the calibration region polygon from the geometry HDF via
        ``HdfLandCover.get_mannings_region_polygons()`` and delegates
        to ``get_face_ids_in_polygon()``.

        Parameters
        ----------
        hdf_path : Union[str, Path]
            Path to the HEC-RAS geometry HDF file (.g##.hdf).
        mesh_name : str
            Name of the 2D flow area / mesh.
        region_name : str
            Name of the calibration region as defined in RASMapper GUI.
        method : str, default 'midpoint'
            Spatial test method (see ``get_face_ids_in_polygon``).

        Returns
        -------
        List[int]
            Sorted list of face IDs within the named calibration region.

        Raises
        ------
        ValueError
            If the named region is not found in the geometry HDF.
        """
        from .HdfLandCover import HdfLandCover

        regions_gdf = HdfLandCover.get_mannings_region_polygons(hdf_path)
        if regions_gdf.empty:
            raise ValueError(
                f"No Manning's n calibration regions found in '{hdf_path}'"
            )

        match = regions_gdf[regions_gdf['Name'] == region_name]
        if match.empty:
            available = regions_gdf['Name'].tolist()
            raise ValueError(
                f"Calibration region '{region_name}' not found. "
                f"Available regions: {available}"
            )

        region_polygon = match.geometry.iloc[0]

        return HdfMesh.get_face_ids_in_polygon(
            hdf_path, mesh_name, region_polygon, method=method
        )

    @staticmethod
    def _resolve_face_ids(
        hdf_path: Union[str, Path],
        mesh_name: str,
        face_ids: Optional[List[int]],
        polygon=None,
        region_name: Optional[str] = None,
        method: str = 'midpoint',
    ) -> Optional[List[int]]:
        """
        Resolve face_ids from explicit list, region_name, or polygon.

        Precedence: face_ids > region_name > polygon > None (all faces).
        """
        if face_ids is not None:
            return face_ids
        if region_name is not None:
            return HdfMesh.get_face_ids_in_calibration_region(
                hdf_path, mesh_name, region_name, method=method
            )
        if polygon is not None:
            return HdfMesh.get_face_ids_in_polygon(
                hdf_path, mesh_name, polygon, method=method
            )
        return None

diagnose_mesh_layout staticmethod

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

Inspect mesh-layout capabilities without modifying the HDF.

Parameters

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

Returns

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

Notes

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

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

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

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

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

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

            group = hdf_file[base]
            attributes_path = f"{base}/Attributes"
            if "Attributes" not in group:
                raise _MeshLayoutError("2D Flow Areas/Attributes is missing")
            attributes = group["Attributes"][()]
            if (
                attributes.dtype.names is None
                or "Name" not in attributes.dtype.names
            ):
                raise _MeshLayoutError("2D Flow Areas/Attributes has no Name field")
            mesh_names = [
                HdfUtils.convert_ras_string(_decode_hdf_scalar(value))
                for value in attributes["Name"]
            ]

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

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

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

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

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

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

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

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

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

diagnose_mesh_cell_polygons staticmethod

Python
diagnose_mesh_cell_polygons(hdf_path: Path) -> pd.DataFrame

Return cells not reconstructed as exactly one polygon.

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

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

    The result contains the native ``mesh_name`` and zero-based ``cell_id``,
    face and polygon counts, a status and reason code, and the referenced
    face IDs. ``boundary_only`` rows identify validated native one- or
    two-face records and do not make strict reconstruction fail. ``omitted``
    and ``ambiguous`` rows identify physical-cell problems;
    ``not_present`` and ``read_error`` distinguish unavailable or malformed
    topology from a clean reconstruction. An empty result means every
    named mesh supplied topology and every processed physical cell produced
    exactly one polygon.
    """
    polygons = HdfMesh.get_mesh_cell_polygons(hdf_path, strict=False)
    diagnostic_records = polygons.attrs.get("cell_polygon_diagnostics")
    columns = [
        "mesh_name",
        "cell_id",
        "face_count",
        "polygon_count",
        "status",
        "reason_code",
        "face_ids",
        "missing_face_ids",
    ]
    if diagnostic_records is None:
        return pd.DataFrame(columns=[
            "mesh_name",
            "cell_id",
            "face_count",
            "polygon_count",
            "status",
            "reason_code",
            "face_ids",
            "missing_face_ids",
        ])
    return pd.DataFrame.from_records(diagnostic_records, columns=columns)

get_mesh_cell_polygons staticmethod

Python
get_mesh_cell_polygons(hdf_path: Path, *, strict: bool = False) -> GeoDataFrame

Return 2D flow mesh cell polygons.

Parameters

hdf_path : Path Path to the HEC-RAS geometry HDF file. strict : bool, default False Raise :class:MeshCellPolygonError when a native cell produces no polygon or more than one polygon. The default preserves the legacy return behavior, emits a warning, and attaches anomaly rows to result.attrs["cell_polygon_diagnostics"] as an equality-safe tuple of record dictionaries. Use :meth:diagnose_mesh_cell_polygons for a DataFrame.

Returns

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

Notes

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

Source code in ras_commander/hdf/HdfMesh.py
Python
@staticmethod
@standardize_input(file_type='geom_hdf')
def get_mesh_cell_polygons(
    hdf_path: Path,
    *,
    strict: bool = False,
) -> 'GeoDataFrame':
    """
    Return 2D flow mesh cell polygons.

    Parameters
    ----------
    hdf_path : Path
        Path to the HEC-RAS geometry HDF file.
    strict : bool, default False
        Raise :class:`MeshCellPolygonError` when a native cell produces no
        polygon or more than one polygon. The default preserves the legacy
        return behavior, emits a warning, and attaches anomaly rows to
        ``result.attrs["cell_polygon_diagnostics"]`` as an equality-safe
        tuple of record dictionaries. Use
        :meth:`diagnose_mesh_cell_polygons` for a DataFrame.

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

    Notes
    -----
    Cell IDs are native, zero-based IDs within each mesh. The returned row
    index must not be treated as a complete or positional cell identifier.
    Use :meth:`diagnose_mesh_cell_polygons` or ``strict=True`` whenever an
    exhaustive physical-cell mask is required.
    """
    # Lazy imports for heavy dependencies
    from geopandas import GeoDataFrame
    from shapely.geometry import Polygon
    from shapely.ops import polygonize

    try:
        with h5py.File(hdf_path, 'r') as hdf_file:
            mesh_area_names = HdfMesh.get_mesh_area_names(hdf_path)
            if not mesh_area_names:
                return GeoDataFrame()

            # Get face geometries once
            face_gdf = HdfMesh.get_mesh_cell_faces(hdf_path)

            # Pre-allocate lists for better memory efficiency
            all_mesh_names = []
            all_cell_ids = []
            all_geometries = []
            diagnostics = []

            for mesh_name in mesh_area_names:
                cell_info_path = (
                    f"Geometry/2D Flow Areas/{mesh_name}/"
                    "Cells Face and Orientation Info"
                )
                cell_values_path = (
                    f"Geometry/2D Flow Areas/{mesh_name}/"
                    "Cells Face and Orientation Values"
                )
                present = [
                    cell_info_path in hdf_file,
                    cell_values_path in hdf_file,
                ]
                if not any(present):
                    logger.warning(
                        "Cell-polygon topology is not present for mesh %r in %s; "
                        "cell centers and collection-level Cell Info/Cell Points "
                        "will not be promoted to polygon topology",
                        mesh_name,
                        hdf_path.name,
                    )
                    diagnostics.append({
                        "mesh_name": mesh_name,
                        "cell_id": None,
                        "face_count": None,
                        "polygon_count": None,
                        "status": "not_present",
                        "reason_code": "cell_topology_not_present",
                        "face_ids": (),
                        "missing_face_ids": (),
                    })
                    continue
                if not all(present):
                    raise _MeshLayoutError(
                        f"Cell-polygon topology is partial for mesh {mesh_name!r}"
                    )
                # Get cell face info in one read
                cell_face_info = hdf_file[cell_info_path][()]
                cell_face_values = hdf_file[cell_values_path][()][:, 0]

                # Create face lookup dictionary for this mesh
                mesh_faces_dict = dict(face_gdf[face_gdf.mesh_name == mesh_name][["face_id", "geometry"]].values)

                # Process each cell
                for cell_id, (start, length) in enumerate(cell_face_info[:, :2]):
                    start = int(start)
                    length = int(length)
                    if (
                        start < 0
                        or length < 0
                        or start > len(cell_face_values)
                        or start + length > len(cell_face_values)
                    ):
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": cell_id,
                            "face_count": length,
                            "polygon_count": 0,
                            "status": "omitted",
                            "reason_code": "invalid_face_span",
                            "face_ids": (),
                            "missing_face_ids": (),
                        })
                        continue
                    face_ids = cell_face_values[start:start + length]
                    missing_face_ids = [
                        int(face_id)
                        for face_id in face_ids
                        if face_id not in mesh_faces_dict
                    ]
                    if missing_face_ids:
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": cell_id,
                            "face_count": int(length),
                            "polygon_count": 0,
                            "status": "omitted",
                            "reason_code": "missing_face_reference",
                            "face_ids": tuple(int(value) for value in face_ids),
                            "missing_face_ids": tuple(missing_face_ids),
                        })
                        continue
                    if length == 0:
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": cell_id,
                            "face_count": 0,
                            "polygon_count": 0,
                            "status": "omitted",
                            "reason_code": "zero_faces",
                            "face_ids": (),
                            "missing_face_ids": (),
                        })
                        continue
                    if length < 3:
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": cell_id,
                            "face_count": int(length),
                            "polygon_count": 0,
                            "status": "boundary_only",
                            "reason_code": "insufficient_faces",
                            "face_ids": tuple(int(value) for value in face_ids),
                            "missing_face_ids": (),
                        })
                        continue
                    face_geoms = [mesh_faces_dict[face_id] for face_id in face_ids]

                    # Create polygon
                    polygons = list(polygonize(face_geoms))
                    if not polygons:
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": cell_id,
                            "face_count": int(length),
                            "polygon_count": 0,
                            "status": "omitted",
                            "reason_code": "no_polygon",
                            "face_ids": tuple(int(value) for value in face_ids),
                            "missing_face_ids": (),
                        })
                        continue
                    if len(polygons) > 1:
                        diagnostics.append({
                            "mesh_name": mesh_name,
                            "cell_id": cell_id,
                            "face_count": int(length),
                            "polygon_count": len(polygons),
                            "status": "ambiguous",
                            "reason_code": "multiple_polygons",
                            "face_ids": tuple(int(value) for value in face_ids),
                            "missing_face_ids": (),
                        })
                    all_mesh_names.append(mesh_name)
                    all_cell_ids.append(cell_id)
                    all_geometries.append(Polygon(polygons[0]))

            diagnostics_df = pd.DataFrame(
                diagnostics,
                columns=[
                    "mesh_name",
                    "cell_id",
                    "face_count",
                    "polygon_count",
                    "status",
                    "reason_code",
                    "face_ids",
                    "missing_face_ids",
                ],
            )
            problematic = diagnostics_df[
                diagnostics_df["status"].isin(
                    ("omitted", "ambiguous", "not_present", "read_error")
                )
            ]
            if not problematic.empty:
                summary = ", ".join(
                    f"{mesh!r}: {count}"
                    for mesh, count in problematic.groupby("mesh_name").size().items()
                )
                message = (
                    "Mesh cell polygon reconstruction was incomplete or ambiguous "
                    f"({summary}). Inspect diagnose_mesh_cell_polygons(); native "
                    "cell IDs remain authoritative."
                )
                if strict:
                    raise MeshCellPolygonError(message)
                logger.warning(message)

            # Create GeoDataFrame in one go
            result = GeoDataFrame(
                {
                    "mesh_name": all_mesh_names,
                    "cell_id": all_cell_ids,
                    "geometry": all_geometries
                },
                geometry="geometry",
                crs=HdfBase.get_projection(hdf_file)
            )
            # DataFrames in ``attrs`` make ordinary operations such as
            # ``pd.concat([cells_a, cells_b])`` fail while pandas compares
            # metadata.  Store equality-safe records and keep the public
            # diagnostic method as the DataFrame-returning API.
            result.attrs["cell_polygon_diagnostics"] = tuple(
                diagnostics_df.to_dict(orient="records")
            )
            return result

    except Exception as e:
        if strict:
            if isinstance(e, MeshCellPolygonError):
                raise
            raise MeshCellPolygonError(
                f"Could not reconstruct mesh cell polygons from {hdf_path}: {e}"
            ) from e
        logger.error(f"Error reading mesh cell polygons from {hdf_path}: {str(e)}")
        result = GeoDataFrame()
        result.attrs["cell_polygon_diagnostics"] = ({
            "mesh_name": None,
            "cell_id": None,
            "face_count": None,
            "polygon_count": None,
            "status": "read_error",
            "reason_code": type(e).__name__,
            "face_ids": (),
            "missing_face_ids": (),
        },)
        return result

get_mesh_perimeter_faces staticmethod

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

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

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

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

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

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

Source code in ras_commander/hdf/HdfMesh.py
Python
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
@staticmethod
@log_call
@standardize_input(file_type="geom_hdf")
def get_mesh_perimeter_faces(
    hdf_path: str | Path,
    mesh_name: str,
    *,
    ras_object=None,
    on_duplicate_ownership: Literal["raise", "report"] = "raise",
) -> "GeoDataFrame":
    """Read every perimeter face of a named 2D area, including unassigned faces.

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

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

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

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

    from .HdfBndry import HdfBndry

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

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

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

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

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

Source code in ras_commander/check/RasCheck.py
Python
class RasCheck:
    """
    Quality assurance validation for HEC-RAS 6.x models.

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

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

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

    @staticmethod
    @log_call
    def run_all(
        plan: Union[str, Path],
        profiles: Optional[List[str]] = None,
        floodway_profile: Optional[str] = None,
        surcharge: float = 1.0,
        thresholds: Optional[ValidationThresholds] = None,
        ras_object=None
    ) -> CheckResults:
        """
        Run all validation checks on a HEC-RAS plan.

        Auto-detects steady vs unsteady flow and runs appropriate checks.

        Args:
            plan: Plan number (e.g., "01") or path to plan HDF file
            profiles: List of profile names to check (steady flow only, ignored for unsteady)
            floodway_profile: Name of floodway profile (steady flow only)
            surcharge: Maximum allowable surcharge in feet (steady flow only, default 1.0)
            thresholds: Custom ValidationThresholds (uses defaults if None)
            ras_object: Optional RasPrj instance (uses global ras if None)

        Returns:
            CheckResults object containing all validation messages and summaries.
            The flow_type attribute indicates whether steady or unsteady checks were run.

        Example (steady flow):
            >>> results = RasCheck.run_all("01",
            ...     profiles=['10yr', '50yr', '100yr', 'Floodway'],
            ...     floodway_profile='Floodway',
            ...     surcharge=1.0)
            >>> print(f"Flow type: {results.flow_type}")
            >>> print(f"Found {results.get_error_count()} errors")

        Example (unsteady flow):
            >>> results = RasCheck.run_all("01")  # Auto-detects unsteady
            >>> print(f"Flow type: {results.flow_type}")  # FlowType.UNSTEADY

        Notes:
            - For steady plans: Runs NT, XS, Structure, Floodway, Profiles checks
            - For unsteady plans: Runs NT, Mass Balance, Computation, Peaks, and Stability checks
            - Geometry-only checks (NT) work for both flow types
            - Floodway analysis is not applicable to unsteady flow
        """
        results = CheckResults()
        ras_obj = ras_object or ras

        if thresholds is None:
            thresholds = get_default_thresholds()

        # Resolve HDF paths
        plan_hdf, geom_hdf = _utils.resolve_hdf_paths(plan, ras_obj)

        # Detect flow type
        flow_type = _utils.detect_flow_type(plan_hdf)
        results.flow_type = flow_type

        logger.info(f"Detected flow type: {flow_type.value}")

        # Dispatch based on flow type
        if flow_type == FlowType.STEADY:
            return RasCheck._run_steady_checks(
                plan_hdf, geom_hdf, profiles, floodway_profile, surcharge, thresholds, results
            )
        elif flow_type == FlowType.UNSTEADY:
            return RasCheck._run_unsteady_checks(
                plan_hdf, geom_hdf, thresholds, results
            )
        else:
            # Geometry only - run NT check only
            logger.info("No results found in plan HDF, running geometry-only checks")
            nt_results = CheckNt.check_nt(geom_hdf, thresholds)
            results.messages.extend(nt_results.messages)
            results.nt_summary = nt_results.nt_summary
            results.statistics = _utils.calculate_statistics(results)
            return results

    @staticmethod
    def _run_steady_checks(
        plan_hdf: Path,
        geom_hdf: Path,
        profiles: Optional[List[str]],
        floodway_profile: Optional[str],
        surcharge: float,
        thresholds: ValidationThresholds,
        results: CheckResults
    ) -> CheckResults:
        """Run all steady flow checks."""
        # Get profile information
        available_profiles = _utils.get_available_profiles(plan_hdf)
        if profiles is None:
            profiles = available_profiles

        # Run individual checks (delegated to domain modules)
        nt_results = CheckNt.check_nt(geom_hdf, thresholds)
        results.messages.extend(nt_results.messages)
        results.nt_summary = nt_results.nt_summary

        xs_results = CheckXs.check_xs(plan_hdf, geom_hdf, profiles, thresholds)
        results.messages.extend(xs_results.messages)
        results.xs_summary = xs_results.xs_summary

        struct_results = CheckStructures.check_structures(plan_hdf, geom_hdf, profiles, thresholds)
        results.messages.extend(struct_results.messages)
        results.struct_summary = struct_results.struct_summary

        if floodway_profile and floodway_profile in profiles:
            base_profile = profiles[0] if profiles[0] != floodway_profile else profiles[1]
            fw_results = CheckFloodways.check_floodways(
                plan_hdf, geom_hdf, base_profile, floodway_profile, surcharge, thresholds
            )
            results.messages.extend(fw_results.messages)
            results.floodway_summary = fw_results.floodway_summary

        if len(profiles) >= 2:
            # Exclude floodway from profiles check
            check_profiles = [p for p in profiles if p != floodway_profile]
            if len(check_profiles) >= 2:
                prof_results = CheckProfiles.check_profiles(plan_hdf, check_profiles, thresholds)
                results.messages.extend(prof_results.messages)
                results.profiles_summary = prof_results.profiles_summary

        # HTAB parameter checks (geometry-only, uses plain text .g## file)
        geom_file = geom_hdf.parent / geom_hdf.stem  # model.g01.hdf -> model.g01
        if geom_file.exists():
            htab_results = CheckNt.check_htab_params(geom_file, thresholds)
            results.messages.extend(htab_results.messages)

            struct_htab_results = CheckNt.check_structure_htab_params(geom_file, thresholds)
            results.messages.extend(struct_htab_results.messages)

            subgrid_results = CheckNt.check_subgrid_sampling(geom_file, thresholds)
            results.messages.extend(subgrid_results.messages)

        # Calculate statistics
        results.statistics = _utils.calculate_statistics(results)

        return results

    @staticmethod
    def _run_unsteady_checks(
        plan_hdf: Path,
        geom_hdf: Path,
        thresholds: ValidationThresholds,
        results: CheckResults
    ) -> CheckResults:
        """
        Run all unsteady flow checks.

        Unsteady checks include:
        - NT Check: Manning's n values (geometry-only, shared with steady)
        - Mass Balance Check: Volume conservation validation
        - Computation Check: HEC-RAS warnings and performance
        - Peaks Check: Maximum WSE and velocity validation
        - Stability Check: Iteration counts and convergence (when 2D present)
        - 2D Mesh Check: Cell quality and face velocity (when 2D present)

        Note:
            Floodway and Profiles checks are NOT applicable to unsteady flow.
        """
        logger.info("Running unsteady flow validation checks")

        # Geometry checks (shared with steady)
        nt_results = CheckNt.check_nt(geom_hdf, thresholds)
        results.messages.extend(nt_results.messages)
        results.nt_summary = nt_results.nt_summary

        # Unsteady-specific checks
        mass_balance_results = CheckUnsteady.check_mass_balance(plan_hdf, thresholds)
        results.messages.extend(mass_balance_results.messages)
        results.mass_balance_summary = mass_balance_results.mass_balance_summary

        computation_results = CheckUnsteady.check_computation(plan_hdf, thresholds)
        results.messages.extend(computation_results.messages)

        # Peaks validation
        peaks_results = CheckUnsteady.check_peaks(plan_hdf, geom_hdf, thresholds)
        results.messages.extend(peaks_results.messages)
        results.peaks_summary = peaks_results.peaks_summary

        # Stability and 2D mesh checks (when 2D present)
        if _utils.has_2d_mesh(plan_hdf):
            stability_results = CheckUnsteady.check_stability(plan_hdf, thresholds)
            results.messages.extend(stability_results.messages)
            results.stability_summary = stability_results.stability_summary

            mesh_results = CheckUnsteady.check_mesh_quality(plan_hdf, geom_hdf, thresholds)
            results.messages.extend(mesh_results.messages)
            results.mesh_summary = mesh_results.mesh_summary
        else:
            msg = CheckMessage(
                message_id="US_INFO_01",
                severity=Severity.INFO,
                check_type="UNSTEADY",
                message="No 2D flow areas found - 2D stability and mesh quality checks skipped"
            )
            results.messages.append(msg)

        # Add info message about floodway not applicable
        msg = CheckMessage(
            message_id="US_INFO_02",
            severity=Severity.INFO,
            check_type="UNSTEADY",
            message="Floodway analysis is not applicable to unsteady flow simulations"
        )
        results.messages.append(msg)

        # HTAB parameter checks (geometry-only, uses plain text .g## file)
        geom_file = geom_hdf.parent / geom_hdf.stem  # model.g01.hdf -> model.g01
        if geom_file.exists():
            htab_results = CheckNt.check_htab_params(geom_file, thresholds)
            results.messages.extend(htab_results.messages)

            struct_htab_results = CheckNt.check_structure_htab_params(geom_file, thresholds)
            results.messages.extend(struct_htab_results.messages)

            subgrid_results = CheckNt.check_subgrid_sampling(geom_file, thresholds)
            results.messages.extend(subgrid_results.messages)

        # Calculate statistics
        results.statistics = _utils.calculate_statistics(results)

        return results

    # =========================================================================
    # Facade delegates - preserve backward-compatible public API
    # =========================================================================

    @staticmethod
    def check_nt(geom_hdf, thresholds=None):
        """Delegate to CheckNt.check_nt."""
        return CheckNt.check_nt(geom_hdf, thresholds)

    @staticmethod
    def check_htab_params(geom_file, thresholds=None):
        """Delegate to CheckNt.check_htab_params."""
        return CheckNt.check_htab_params(geom_file, thresholds)

    @staticmethod
    def check_structure_htab_params(geom_file, thresholds=None):
        """Delegate to CheckNt.check_structure_htab_params."""
        return CheckNt.check_structure_htab_params(geom_file, thresholds)

    @staticmethod
    def check_xs(plan_hdf, geom_hdf, profiles, thresholds=None):
        """Delegate to CheckXs.check_xs."""
        return CheckXs.check_xs(plan_hdf, geom_hdf, profiles, thresholds)

    @staticmethod
    def check_structures(plan_hdf, geom_hdf, profiles, thresholds=None):
        """Delegate to CheckStructures.check_structures."""
        return CheckStructures.check_structures(plan_hdf, geom_hdf, profiles, thresholds)

    @staticmethod
    def check_floodways(plan_hdf, geom_hdf, base_profile, floodway_profile, surcharge=1.0, thresholds=None):
        """Delegate to CheckFloodways.check_floodways."""
        return CheckFloodways.check_floodways(plan_hdf, geom_hdf, base_profile, floodway_profile, surcharge, thresholds)

    @staticmethod
    def check_profiles(plan_hdf, profiles, thresholds=None):
        """Delegate to CheckProfiles.check_profiles."""
        return CheckProfiles.check_profiles(plan_hdf, profiles, thresholds)

    @staticmethod
    def check_unsteady_mass_balance(plan_hdf, thresholds=None):
        """Delegate to CheckUnsteady.check_mass_balance."""
        return CheckUnsteady.check_mass_balance(plan_hdf, thresholds)

    @staticmethod
    def check_unsteady_computation(plan_hdf, thresholds=None):
        """Delegate to CheckUnsteady.check_computation."""
        return CheckUnsteady.check_computation(plan_hdf, thresholds)

    @staticmethod
    def check_unsteady_peaks(plan_hdf, geom_hdf, thresholds=None):
        """Delegate to CheckUnsteady.check_peaks."""
        return CheckUnsteady.check_peaks(plan_hdf, geom_hdf, thresholds)

    @staticmethod
    def check_unsteady_stability(plan_hdf, thresholds=None):
        """Delegate to CheckUnsteady.check_stability."""
        return CheckUnsteady.check_stability(plan_hdf, thresholds)

    @staticmethod
    def check_mesh_quality(plan_hdf, geom_hdf, thresholds=None):
        """Delegate to CheckUnsteady.check_mesh_quality."""
        return CheckUnsteady.check_mesh_quality(plan_hdf, geom_hdf, thresholds)

    @staticmethod
    def check_subgrid_sampling(geom_file, thresholds=None):
        """Delegate to CheckNt.check_subgrid_sampling."""
        return CheckNt.check_subgrid_sampling(geom_file, thresholds)

check_mesh_quality staticmethod

Python
check_mesh_quality(plan_hdf, geom_hdf, thresholds=None)

Delegate to CheckUnsteady.check_mesh_quality.

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

check_subgrid_sampling staticmethod

Python
check_subgrid_sampling(geom_file, thresholds=None)

Delegate to CheckNt.check_subgrid_sampling.

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

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

Runtime and persisted changes

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

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

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

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

Examples with retained outputs

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

Repair persistence and failure contract

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

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

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

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

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

Saved-point compilation and RAS Mapper constraints

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

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

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

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

Optional multi-configuration screening

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

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

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

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

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

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

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

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

Carry refinement regions into a child area

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

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

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

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

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

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

Anchor a child's regular grid to its parent

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

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

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

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

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

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

HEC-RAS Version Support for Headless Mesh Generation

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

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

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

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

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

Known limitations.

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

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

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

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

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

HEC-RAS Refinement-Region Caveats

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

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

Mesh methods

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

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

All methods are static — no instantiation needed.

Example

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

Source code in ras_commander/geom/GeomMesh.py
Python
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
class GeomMesh:
    """
    Headless 2D mesh generation, repair, and BC conflict resolution.

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

    All methods are static — no instantiation needed.

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

    @staticmethod
    @log_call
    def setup_gdal_bridge(
        hecras_dir: Optional[Union[str, Path]] = None,
        python_dir: Optional[Union[str, Path]] = None,
        create_junction: bool = True,
    ) -> bool:
        """
        Configure HEC-RAS GDAL runtime for RasMapperLib.

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

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

        if hecras_dir is None:
            hecras_dir = _find_hecras_dir()

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

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

        return True

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

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

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

        This read-only check is cross-platform and does not load RasMapperLib.
        A missing, stale, malformed, or ambiguous geometry HDF fails closed.
        ``require_complete_products`` defaults to False and is forwarded to
        native preprocessing when ``recompile_via_rasexe=True`` permits mutation.
        """
        geom_path = _resolve_geom_text_path(geom_number, ras_object)
        hdf_path = _ensure_hdf(
            geom_path,
            require_current=True,
            ras_object=ras_object,
            mesh_name=mesh_name,
            recompile_via_rasexe=recompile_via_rasexe,
            ignore_seed_count=True,
            require_complete_products=require_complete_products,
        )
        hdf_metadata = _read_mesh_metadata_from_hdf(hdf_path)
        area_names = list(hdf_metadata)
        if mesh_name is None:
            if not isinstance(mesh_index, int) or isinstance(mesh_index, bool):
                raise TypeError("mesh_index must be an integer")
            if mesh_index < 0 or mesh_index >= len(area_names):
                raise IndexError(
                    f"mesh_index {mesh_index} is outside the {len(area_names)} "
                    "compiled 2D flow area(s)"
                )
            mesh_name = area_names[mesh_index]
        elif mesh_name not in hdf_metadata:
            raise ValueError(
                f"2D flow area {mesh_name!r} is not present exactly once in "
                f"{hdf_path.name}"
            )

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

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

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

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

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

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

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

    @staticmethod
    @log_call
    def get_breakline_names(
        geom_number: Union[str, Number, Path],
        ras_object=None,
    ) -> list[tuple[int, str]]:
        """
        Read breakline names from a .g## text file.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        from ..hdf.HdfBndry import HdfBndry

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

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

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

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

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

        from .GeomParser import GeomParser

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        attr_dtype = _refinement_region_attribute_dtype()

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

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

                old_attrs = _coerce_refinement_region_attributes(old_attrs)

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

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

            new_fid = existing_n

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @staticmethod
    @log_call
    def compile_geometry(
        geom_number: Union[str, Number, Path],
        hecras_dir: Optional[Union[str, Path]] = None,
        ras_object=None,
    ) -> Path:
        """
        Disabled compatibility shim for .g## text -> .g##.hdf generation.

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

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

        Returns:
            Never returns successfully.

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

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

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

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

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

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

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

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

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

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

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

        prior_association = _read_geometry_association(
            hdf_path,
            resolve_paths=False,
        )

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

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

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

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

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

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

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

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

        Returns:
            True if property tables were computed successfully.

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

        _load_dlls(hecras_dir)

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

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

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

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

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

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

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

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

        return bool(result)

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

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

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

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

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

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

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

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

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

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

        Returns:
            MeshResult with status, mesh_name, cell_count (= number of generated
            computation points), and geom_text_path. Points are written to the
            .g## text; the full mesh is produced by the subsequent HEC-RAS
            geometry preprocess.
        """
        import numpy as np
        from .GeomStorage import GeomStorage

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

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

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

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

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

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

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

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

    @staticmethod
    @log_call
    def generate(
        geom_number: Union[str, Number, Path],
        mesh_name: Optional[str] = None,
        mesh_index: int = 0,
        cell_size: Optional[float] = None,
        bl_spacing: Optional[float] = None,
        near_repeats: Optional[int] = None,
        protection_radius: Optional[int] = None,
        min_face_length_ratio: float = 0.05,
        max_iterations: int = 8,
        hecras_dir: Optional[Union[str, Path]] = None,
        bl_spacing_near: Optional[float] = None,
        bl_spacing_far: Optional[float] = None,
        ras_object=None,
        recompile_via_rasexe: bool = False,
        _require_current_hdf: bool = True,
        refinement_region_constraints: bool = False,
        strict_refinement_containment: bool = False,
        robustness_screening: bool = False,
        require_complete_products: bool = False,
        grid_anchor: Optional[Union[GridAnchor, Tuple[float, float]]] = None,
    ) -> MeshResult:
        """
        Generate or regenerate a 2D mesh headlessly via text-first workflow.

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

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

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

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

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

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

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


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

        repair_reason = None
        try:
            text_path = geom_path

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            current_perim = perim
            current_seeds_pm = seeds_pm

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @staticmethod
    @log_call
    def detect_bc_conflicts(
        geom_hdf_path: Union[str, Path],
        cell_size: float,
    ) -> List[BCConflict]:
        """
        Detect perimeter faces covered by 2+ BC lines.

        Args:
            geom_hdf_path: Path to compiled .g##.hdf file.
            cell_size: Mesh cell size for intersection buffer scaling.

        Returns:
            List of BCConflict (one per conflicting face).
        """
        import h5py
        from shapely.geometry import LineString as ShapelyLine

        conflicts = []
        buf = 0.01 * cell_size

        with h5py.File(str(geom_hdf_path), "r") as hf:
            for area_group in _iter_bc_flow_area_groups(hf):
                flow_area_name = area_group.name.rsplit("/", 1)[-1]
                bcs = _read_bc_features(area_group, ShapelyLine)
                if not bcs:
                    continue

                for face_id, face_line in _read_bc_face_segments(area_group, ShapelyLine):
                    hitting = []
                    hitting_types = []
                    for bc in bcs:
                        if bc["geom"] is not None and face_line.distance(bc["geom"]) < buf:
                            hitting.append(bc["name"])
                            hitting_types.append(bc["type"])

                    if len(hitting) >= 2:
                        nd_bc = next(
                            (n for n, t in zip(hitting, hitting_types)
                             if "normal" in t.lower()),
                            None,
                        )
                        conflicts.append(BCConflict(
                            face_id=face_id,
                            flow_area_name=flow_area_name,
                            bc_names=hitting,
                            bc_types=hitting_types,
                            normal_depth_bc=nd_bc,
                        ))

        return conflicts

    @staticmethod
    @log_call
    def fix_bc_conflicts(
        geom_hdf_path: Union[str, Path],
        cell_size: float,
        dry_run: bool = False,
    ) -> BCFixResult:
        """
        Detect and fix BC conflicts by trimming overlapping BC endpoints.

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

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

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

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

        import numpy as np

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

        if not area_results:
            return BCFixResult()

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

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

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

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

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

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

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

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

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

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

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

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

            area_result["bc_coords"] = bc_coords

        if result.conflicts_fixed == 0:
            return result

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

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

setup_gdal_bridge staticmethod

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

Configure HEC-RAS GDAL runtime for RasMapperLib.

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

Returns True if the process runtime was configured successfully.

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

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

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

    if hecras_dir is None:
        hecras_dir = _find_hecras_dir()

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

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

    return True

audit_domain_containment staticmethod

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

Audit mesh features before point generation.

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

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

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

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

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

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

    This read-only check is cross-platform and does not load RasMapperLib.
    A missing, stale, malformed, or ambiguous geometry HDF fails closed.
    ``require_complete_products`` defaults to False and is forwarded to
    native preprocessing when ``recompile_via_rasexe=True`` permits mutation.
    """
    geom_path = _resolve_geom_text_path(geom_number, ras_object)
    hdf_path = _ensure_hdf(
        geom_path,
        require_current=True,
        ras_object=ras_object,
        mesh_name=mesh_name,
        recompile_via_rasexe=recompile_via_rasexe,
        ignore_seed_count=True,
        require_complete_products=require_complete_products,
    )
    hdf_metadata = _read_mesh_metadata_from_hdf(hdf_path)
    area_names = list(hdf_metadata)
    if mesh_name is None:
        if not isinstance(mesh_index, int) or isinstance(mesh_index, bool):
            raise TypeError("mesh_index must be an integer")
        if mesh_index < 0 or mesh_index >= len(area_names):
            raise IndexError(
                f"mesh_index {mesh_index} is outside the {len(area_names)} "
                "compiled 2D flow area(s)"
            )
        mesh_name = area_names[mesh_index]
    elif mesh_name not in hdf_metadata:
        raise ValueError(
            f"2D flow area {mesh_name!r} is not present exactly once in "
            f"{hdf_path.name}"
        )

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

set_breakline_spacing staticmethod

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

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

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

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

Parameters:

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

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

required
near Optional[float]

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

None
far Optional[float]

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

None
near_repeats Optional[int]

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

None
protection_radius Optional[int]

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

None
breakline_name Optional[str]

Name of the breakline to modify.

None
breakline_fid Optional[int]

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

None
all_breaklines bool

If True, apply spacing to every breakline.

False
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None

Returns:

Type Description
Path

Path to .bak backup file created before writing.

Raises:

Type Description
ValueError

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

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

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

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

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

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

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

get_breakline_names staticmethod

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

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

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

Returns:

Type Description
list[tuple[int, str]]

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

list[tuple[int, str]]

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

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

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

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

set_breakline_name staticmethod

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

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

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

Parameters:

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

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

required
new_name str

New name to assign.

required
breakline_fid Optional[int]

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

None
old_name Optional[str]

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

None
ras_object RasPrj

Optional RasPrj instance.

None

Returns:

Type Description
Path

Path to .bak backup file created before writing.

Raises:

Type Description
ValueError

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

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

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

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

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

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

get_breakline_spacing staticmethod

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

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

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

Returns:

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

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

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

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

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

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

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

get_refinement_region_names staticmethod

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

Read refinement region names from the compiled HDF.

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

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

Returns:

Type Description
list[tuple[int, str]]

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

list[tuple[int, str]]

0-based index.

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

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

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

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

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

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

set_refinement_region_name staticmethod

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

Rename a refinement region in the compiled HDF.

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

Parameters:

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

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

required
new_name str

New name to assign.

required
region_fid Optional[int]

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

None
old_name Optional[str]

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

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance.

None

Raises:

Type Description
ValueError

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

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

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

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

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

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

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

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

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

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

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

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

get_refinement_regions staticmethod

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

Read refinement region names and spacing from the compiled HDF.

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

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

Returns:

Type Description
List of dicts with keys

fid, name, spacing_dx, spacing_dy.

list[dict]

Empty list if no refinement regions exist.

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

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

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

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

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

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

set_refinement_region_spacing staticmethod

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

Set refinement region cell spacing in the compiled HDF.

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

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

Parameters:

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

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

required
spacing_dx Optional[float]

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

None
spacing_dy Optional[float]

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

None
region_name Optional[str]

Name of the refinement region to modify.

None
region_fid Optional[int]

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

None
all_regions bool

If True, apply spacing to every region.

False
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance.

None

Raises:

Type Description
ValueError

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

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

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

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

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

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

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

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

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

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

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

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

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

replace_refinement_regions staticmethod

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

Atomically replace the complete HDF refinement-region collection.

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

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

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

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

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

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

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

    from .GeomParser import GeomParser

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

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

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

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

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

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

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

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

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

clip_refinement_regions staticmethod

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

Prepare delivered refinement regions for a smaller 2D perimeter.

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

Parameters:

Name Type Description Default
geom_number str | Number | Path

Source geometry number or .g## text path.

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

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

required
min_area float

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

0.0
invalid_regions str

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

'raise'
hecras_dir str | Path | None

Optional HEC-RAS installation for source HDF validation.

None
ras_object RasPrj | None

Optional source RasPrj context.

None

Returns:

Type Description
list[dict[str, Any]]

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

DataFrame

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

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

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

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

source_area, retained_area, output_fids, touches_perimeter and

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

below_one_cell_area. Areas use squared project units.

Raises:

Type Description
ValueError

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

Notes

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

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

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

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

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

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

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

    from ..hdf.HdfBndry import HdfBndry

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

add_refinement_region staticmethod

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

Create a new refinement region in the compiled geometry HDF.

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

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

Parameters:

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

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

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

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

required
spacing_dx float

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

required
spacing_dy Optional[float]

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

None
name str

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

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

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance.

None
use_rasmapper Optional[bool]

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

None

Returns:

Type Description
int

The 0-based FID of the newly created region.

Raises:

Type Description
ValueError

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

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

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

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

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

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

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

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

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

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

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

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

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

    attr_dtype = _refinement_region_attribute_dtype()

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

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

            old_attrs = _coerce_refinement_region_attributes(old_attrs)

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

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

        new_fid = existing_n

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

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

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

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

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

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

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

add_flowline_refinement_regions staticmethod

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

Buffer channel flowlines into HEC-RAS refinement regions.

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

Parameters:

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

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

required
flowlines GeoDataFrame | GeoSeries | LineString | MultiLineString | Iterable

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

required
buffer_width float

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

required
spacing_dx Optional[float]

Refinement-region X spacing. Defaults to buffer_width.

None
spacing_dy Optional[float]

Refinement-region Y spacing. Defaults to spacing_dx.

None
name_prefix str

Prefix used when name_column is not supplied.

'FlowlineRR'
name_column Optional[str]

Optional GeoDataFrame column for region names.

None
simplify_tolerance Optional[float]

Optional line simplification tolerance applied before buffering.

None
preserve_topology bool

Passed to shapely simplify().

True
trim_geometries GeoDataFrame | BaseGeometry | Iterable

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

None
trim_distance float

Optional buffer distance applied to trim_geometries before subtraction.

0.0
trim_hook Optional[Callable]

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

None
trim_overlaps bool

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

False
cap_style Union[str, int]

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

'flat'
join_style Union[str, int]

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

'round'
mitre_limit float

Shapely buffer mitre limit.

5.0
min_area float

Skip trimmed polygon parts smaller than this area.

0.0
project_crs Optional[object]

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

None
hecras_dir Optional[Union[str, Path]]

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

None
ras_object RasPrj

Optional RasPrj instance.

None

Returns:

Type Description
list[dict]

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

list[dict]

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

Raises:

Type Description
ValueError

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

compile_geometry staticmethod

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

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

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

Parameters:

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

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

required
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None

Returns:

Type Description
Path

Never returns successfully.

Raises:

Type Description
FileNotFoundError

If geometry file cannot be resolved.

RuntimeError

Always, because this path is unavailable.

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

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

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

    Returns:
        Never returns successfully.

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

get_geometry_association staticmethod

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

Read terrain and classification associations from a geometry HDF.

Parameters:

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

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

required
hecras_dir Optional[Union[str, Path]]

Kept for API symmetry; no DLLs are loaded here.

None
ras_object RasPrj

Optional RasPrj instance for geometry-number lookup.

None
resolve_paths bool

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

True

Returns:

Type Description
dict

Dict with keys terrain_hdf_path, landcover_hdf_path,

dict

infiltration_hdf_path, sediment_soils_hdf_path, matching

dict

*_layer_name keys, and si_units.

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

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

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

set_geometry_association staticmethod

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

Associate terrain / classification layers to an existing geometry HDF.

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

Parameters:

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

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

required
terrain_hdf_path Optional[Union[str, Path]]

Terrain HDF to associate.

None
landcover_hdf_path Optional[Union[str, Path]]

Land-cover / Manning's n HDF.

None
infiltration_hdf_path Optional[Union[str, Path]]

Infiltration HDF.

None
sediment_soils_hdf_path Optional[Union[str, Path]]

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

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for geometry-number lookup.

None
validate bool

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

True

Returns:

Type Description
Path

Path to the existing geometry HDF that was updated.

Raises:

Type Description
ValueError

If no association paths are supplied.

FileNotFoundError

If any supplied artifact is missing.

RuntimeError

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

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

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

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

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

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

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

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

    prior_association = _read_geometry_association(
        hdf_path,
        resolve_paths=False,
    )

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

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

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

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

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

compute_property_tables staticmethod

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

Compute 2D hydraulic property tables for a geometry.

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

Parameters:

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

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

required
mesh_name Optional[str]

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

None
mesh_index int

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

0
force bool

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

True
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None

Returns:

Type Description
bool

True if property tables were computed successfully.

Raises:

Type Description
FileNotFoundError

If geometry file cannot be resolved.

RuntimeError

If terrain is missing or computation fails.

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

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

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

    Returns:
        True if property tables were computed successfully.

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

    _load_dlls(hecras_dir)

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

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

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

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

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

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

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

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

    return bool(result)

generate_computation_points staticmethod

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

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

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

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

Parameters:

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

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

required
mesh_name Optional[str]

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

None
mesh_index int

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

0
cell_size Optional[float]

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

None
hecras_dir Optional[Union[str, Path]]

Override HEC-RAS installation directory (for RasMapperLib).

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None
repair_generated_points bool

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

False
min_face_length_ratio float

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

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

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

None

Returns:

Type Description
'MeshResult'

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

'MeshResult'

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

'MeshResult'

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

'MeshResult'

geometry preprocess.

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

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

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

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

    Returns:
        MeshResult with status, mesh_name, cell_count (= number of generated
        computation points), and geom_text_path. Points are written to the
        .g## text; the full mesh is produced by the subsequent HEC-RAS
        geometry preprocess.
    """
    import numpy as np
    from .GeomStorage import GeomStorage

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

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

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

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

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

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

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

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

get_grid_anchor staticmethod

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

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

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

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

Parameters:

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

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

required
mesh_name Optional[str]

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

None
mesh_index int

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

0
ras_object RasPrj

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

None

Returns:

Type Description
GridAnchor

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

GridAnchor

source naming the HDF file and area.

Raises:

Type Description
FileNotFoundError

The geometry or its compiled HDF is missing.

ValueError

The area is missing or has no positive spacing.

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

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

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

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

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

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

generate staticmethod

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

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

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

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

Parameters:

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

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

required
mesh_name Optional[str]

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

None
mesh_index int

0-based index if mesh_name not provided.

0
cell_size Optional[float]

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

None
bl_spacing Optional[float]

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

None
near_repeats Optional[int]

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

None
protection_radius Optional[int]

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

None
min_face_length_ratio float

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

0.05
max_iterations int

Maximum fix-and-retry attempts.

8
hecras_dir Optional[Union[str, Path]]

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

None
bl_spacing_near Optional[float]

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

None
bl_spacing_far Optional[float]

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

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None
recompile_via_rasexe bool

If True, refresh a missing or content-stale compiled geometry HDF through GeomPreprocessor/Ras.exe. The geometry must be referenced by a plan in ras_object.

False
require_complete_products bool

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

False
refinement_region_constraints bool

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

False
strict_refinement_containment bool

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

False
robustness_screening bool

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

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

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

None

Returns:

Type Description
MeshResult

MeshResult with status, cell_count, face_count, fixes_applied, and

MeshResult

the compiled geometry HDF path on success. perimeter_repairs

MeshResult

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

MeshResult

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

MeshResult

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

MeshResult

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

MeshResult

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

MeshResult

supply an initialized project with a referencing plan.

Raises:

Type Description
ValueError

The face-length ratio is not positive and finite.

TypeError

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

RuntimeError

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

Source code in ras_commander/geom/GeomMesh.py
Python
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
@staticmethod
@log_call
def generate(
    geom_number: Union[str, Number, Path],
    mesh_name: Optional[str] = None,
    mesh_index: int = 0,
    cell_size: Optional[float] = None,
    bl_spacing: Optional[float] = None,
    near_repeats: Optional[int] = None,
    protection_radius: Optional[int] = None,
    min_face_length_ratio: float = 0.05,
    max_iterations: int = 8,
    hecras_dir: Optional[Union[str, Path]] = None,
    bl_spacing_near: Optional[float] = None,
    bl_spacing_far: Optional[float] = None,
    ras_object=None,
    recompile_via_rasexe: bool = False,
    _require_current_hdf: bool = True,
    refinement_region_constraints: bool = False,
    strict_refinement_containment: bool = False,
    robustness_screening: bool = False,
    require_complete_products: bool = False,
    grid_anchor: Optional[Union[GridAnchor, Tuple[float, float]]] = None,
) -> MeshResult:
    """
    Generate or regenerate a 2D mesh headlessly via text-first workflow.

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

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

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

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

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

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

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


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

    repair_reason = None
    try:
        text_path = geom_path

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        current_perim = perim
        current_seeds_pm = seeds_pm

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

generate_all staticmethod

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

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

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

Parameters:

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

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

required
cell_size Optional[float]

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

None
bl_spacing Optional[float]

Shorthand — sets both near and far breakline spacing.

None
bl_spacing_near Optional[float]

Breakline near-spacing override.

None
bl_spacing_far Optional[float]

Breakline far-spacing override.

None
near_repeats Optional[int]

Number of offset seed rows along breaklines.

None
protection_radius Optional[int]

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

None
min_face_length_ratio float

Minimum face-length ratio for mesh quality.

0.05
max_iterations int

Maximum fix-loop iterations per mesh area.

8
hecras_dir Optional[Union[str, Path]]

Override path to the HEC-RAS installation directory.

None
ras_object RasPrj

Optional RasPrj instance for multi-project support.

None
recompile_via_rasexe bool

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

False
require_complete_products bool

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

False
refinement_region_constraints bool

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

False
strict_refinement_containment bool

Apply the old inward region margin; defaults to False.

False
robustness_screening bool

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

False

Returns:

Type Description
List[MeshResult]

List of MeshResult, one per 2D flow area.

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

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

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

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

detect_bc_conflicts staticmethod

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

Detect perimeter faces covered by 2+ BC lines.

Parameters:

Name Type Description Default
geom_hdf_path Union[str, Path]

Path to compiled .g##.hdf file.

required
cell_size float

Mesh cell size for intersection buffer scaling.

required

Returns:

Type Description
List[BCConflict]

List of BCConflict (one per conflicting face).

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

    Args:
        geom_hdf_path: Path to compiled .g##.hdf file.
        cell_size: Mesh cell size for intersection buffer scaling.

    Returns:
        List of BCConflict (one per conflicting face).
    """
    import h5py
    from shapely.geometry import LineString as ShapelyLine

    conflicts = []
    buf = 0.01 * cell_size

    with h5py.File(str(geom_hdf_path), "r") as hf:
        for area_group in _iter_bc_flow_area_groups(hf):
            flow_area_name = area_group.name.rsplit("/", 1)[-1]
            bcs = _read_bc_features(area_group, ShapelyLine)
            if not bcs:
                continue

            for face_id, face_line in _read_bc_face_segments(area_group, ShapelyLine):
                hitting = []
                hitting_types = []
                for bc in bcs:
                    if bc["geom"] is not None and face_line.distance(bc["geom"]) < buf:
                        hitting.append(bc["name"])
                        hitting_types.append(bc["type"])

                if len(hitting) >= 2:
                    nd_bc = next(
                        (n for n, t in zip(hitting, hitting_types)
                         if "normal" in t.lower()),
                        None,
                    )
                    conflicts.append(BCConflict(
                        face_id=face_id,
                        flow_area_name=flow_area_name,
                        bc_names=hitting,
                        bc_types=hitting_types,
                        normal_depth_bc=nd_bc,
                    ))

    return conflicts

fix_bc_conflicts staticmethod

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

Detect and fix BC conflicts by trimming overlapping BC endpoints.

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

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

Parameters:

Name Type Description Default
geom_hdf_path Union[str, Path]

Path to compiled .g##.hdf file.

required
cell_size float

Mesh cell size for buffer scaling.

required
dry_run bool

If True, detect only — do not modify HDF.

False

Returns:

Type Description
BCFixResult

BCFixResult with conflicts_found, conflicts_fixed, unresolvable.

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

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

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

    Args:
        geom_hdf_path: Path to compiled .g##.hdf file.
        cell_size: Mesh cell size for buffer scaling.
        dry_run: If True, detect only — do not modify HDF.

    Returns:
        BCFixResult with conflicts_found, conflicts_fixed, unresolvable.
    """
    import h5py
    from math import hypot
    from shapely.geometry import LineString as ShapelyLine, Point as ShapelyPoint

    import numpy as np

    cell_size = _normalize_positive_value(cell_size, "cell_size")
    geom_hdf_path = str(geom_hdf_path)
    area_results = []
    with h5py.File(geom_hdf_path, "r") as hf:
        for area_group in _iter_bc_flow_area_groups(hf):
            bcs = _read_bc_features(area_group, ShapelyLine)
            if not bcs:
                continue
            face_segments = _read_bc_face_segments(area_group, ShapelyLine)
            if not face_segments:
                continue
            area_results.append(
                {
                    "flow_area_name": area_group.name.rsplit("/", 1)[-1],
                    "area_group_path": area_group.name,
                    "bcs": bcs,
                    "face_segments": face_segments,
                }
            )

    if not area_results:
        return BCFixResult()

    buf = max(0.1, cell_size * 0.01)
    result = BCFixResult()
    for area_result in area_results:
        conflicts = []
        for fid, face_geom in area_result["face_segments"]:
            face_buf = face_geom.buffer(buf)
            hitting = [
                (b["name"], b["type"])
                for b in area_result["bcs"]
                if b["geom"] is not None and face_buf.intersects(b["geom"])
            ]
            if len(hitting) >= 2:
                nd_bc = next((n for n, t in hitting if "normal" in t.lower()), None)
                conflicts.append(BCConflict(
                    face_id=fid,
                    flow_area_name=area_result["flow_area_name"],
                    bc_names=[n for n, _ in hitting],
                    bc_types=[t for _, t in hitting],
                    normal_depth_bc=nd_bc,
                ))
        area_result["conflicts"] = conflicts
        result.conflicts_found += len(conflicts)

    if result.conflicts_found == 0 or dry_run:
        if dry_run:
            for area_result in area_results:
                result.unresolvable.extend(area_result["conflicts"])
        return result

    for area_result in area_results:
        conflicts = area_result["conflicts"]
        if not conflicts:
            continue

        bc_coords = {
            b["name"]: list(b["geom"].coords) if b["geom"] else []
            for b in area_result["bcs"]
        }
        face_mids = {
            fid: ((g.coords[0][0] + g.coords[1][0]) / 2,
                  (g.coords[0][1] + g.coords[1][1]) / 2)
            for fid, g in area_result["face_segments"]
        }
        face_geoms = {fid: g for fid, g in area_result["face_segments"]}

        for conflict in conflicts:
            if conflict.normal_depth_bc is not None:
                trim_name = conflict.normal_depth_bc
            else:
                lengths = {}
                for name in conflict.bc_names:
                    c = bc_coords.get(name, [])
                    if len(c) >= 2:
                        lengths[name] = ShapelyLine(c).length
                if not lengths:
                    result.unresolvable.append(conflict)
                    continue
                trim_name = max(lengths, key=lengths.get)

            coords = bc_coords.get(trim_name, [])
            if len(coords) < 2:
                result.unresolvable.append(conflict)
                continue

            face_geom = face_geoms[conflict.face_id]
            face_mid = face_mids[conflict.face_id]

            start_dist = hypot(coords[0][0] - face_mid[0], coords[0][1] - face_mid[1])
            end_dist = hypot(coords[-1][0] - face_mid[0], coords[-1][1] - face_mid[1])
            trim_from_start = start_dist <= end_dist

            trimmed = list(coords)
            trimmed_count = 0
            while len(trimmed) >= 2:
                if face_geom.buffer(buf).intersects(ShapelyLine(trimmed)):
                    trimmed = trimmed[1:] if trim_from_start else trimmed[:-1]
                    trimmed_count += 1
                    continue
                ep = trimmed[0] if trim_from_start else trimmed[-1]
                ep_to_conflict = hypot(ep[0] - face_mid[0], ep[1] - face_mid[1])
                nearest_other = min(
                    (hypot(ep[0] - mid[0], ep[1] - mid[1])
                     for fid, mid in face_mids.items() if fid != conflict.face_id),
                    default=float("inf"),
                )
                if ep_to_conflict <= nearest_other:
                    trimmed = trimmed[1:] if trim_from_start else trimmed[:-1]
                    trimmed_count += 1
                    continue
                break

            if len(trimmed) < 2:
                line_geom = ShapelyLine(coords)
                face_mid_pt = ShapelyPoint(*face_mid)
                proj = line_geom.project(face_mid_pt)
                pullback = face_geom.length + buf * 2
                if trim_from_start:
                    new_dist = proj + pullback
                    if new_dist >= line_geom.length:
                        result.unresolvable.append(conflict)
                        continue
                    new_pt = line_geom.interpolate(new_dist)
                    remaining = [c for c in coords
                                 if line_geom.project(ShapelyPoint(*c)) >= new_dist]
                    trimmed = [(new_pt.x, new_pt.y)] + remaining
                else:
                    new_dist = proj - pullback
                    if new_dist <= 0:
                        result.unresolvable.append(conflict)
                        continue
                    new_pt = line_geom.interpolate(new_dist)
                    remaining = [c for c in coords
                                 if line_geom.project(ShapelyPoint(*c)) <= new_dist]
                    trimmed = remaining + [(new_pt.x, new_pt.y)]
                if len(trimmed) < 2 or face_geom.buffer(buf).intersects(ShapelyLine(trimmed)):
                    result.unresolvable.append(conflict)
                    continue

            trimmed_line = ShapelyLine(trimmed)
            covers_other = any(
                fid != conflict.face_id and g.buffer(buf).intersects(trimmed_line)
                for fid, g in face_geoms.items()
            )
            if not covers_other:
                result.unresolvable.append(conflict)
                continue

            bc_coords[trim_name] = trimmed
            direction = "start" if trim_from_start else "end"
            result.trims.append(
                (
                    f"{area_result['flow_area_name']}/{trim_name}",
                    f"trimmed {trimmed_count} pts from {direction}",
                )
            )
            result.conflicts_fixed += 1

        area_result["bc_coords"] = bc_coords

    if result.conflicts_fixed == 0:
        return result

    with h5py.File(geom_hdf_path, "r+") as hf:
        for area_result in area_results:
            if "bc_coords" not in area_result:
                continue
            for b in area_result["bcs"]:
                bc_feature_path = f"{area_result['area_group_path']}/BC Lines/{b['name']}"
                if bc_feature_path not in hf:
                    continue
                bc_feature = hf[bc_feature_path]
                if "Coordinates" in bc_feature:
                    del bc_feature["Coordinates"]
                bc_feature.create_dataset(
                    "Coordinates",
                    data=np.array(area_result["bc_coords"].get(b["name"], []), dtype=np.float64),
                )

    result.modified_hdf = True
    logger.info(
        f"BC conflicts fixed: {result.conflicts_fixed}/{result.conflicts_found} "
        f"(trims: {result.trims})"
    )
    return result

Result and audit records

For generate() and generate_all(), inspect MeshResult.ok/status, error information and repair evidence rather than cell count alone.

generate_computation_points() currently reports successful bootstrap with status == "success", while MeshResult.ok and bool(result) recognize only "complete". For this method, check status, cell_count and error_message explicitly; a false ok alone does not mean bootstrap failed. Its cell_count counts generated points, not a compiled hydraulic mesh.

DomainContainmentResult.ok means no recorded containment violations. BCFixResult.ok means no unresolved conflicts in that result; these are operation-specific states, not hydraulic acceptance criteria.

MeshResult dataclass

Result of a headless mesh generation attempt.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass
class MeshResult:
    """Result of a headless mesh generation attempt."""

    mesh_name: str
    status: str  # "complete", "error", "exception"
    mesh_state: str = ""
    cell_count: int = 0
    face_count: int = 0
    iterations: int = 0
    fixes_applied: List[str] = field(default_factory=list)
    error_message: str = ""
    geom_text_path: str = ""
    geom_hdf_path: str = ""
    domain_containment: Optional[DomainContainmentResult] = None
    perimeter_repairs: list[dict[str, Any]] = field(default_factory=list)

    # Empty when disabled; otherwise records rounds, convergence, timing and errors.
    robustness_screening: Dict[str, Any] = field(default_factory=dict)

    # Empty unless generate(grid_anchor=...) was used; then the anchor and
    # lattice/seed counts of each anchored point generation.
    grid_anchor: Dict[str, Any] = field(default_factory=dict)

    @property
    def ok(self) -> bool:
        return self.status == "complete"

    def __bool__(self) -> bool:
        return self.ok

GridAnchor dataclass

One point of a 2D area's regular computation-point lattice.

RAS Mapper lays the regular (base) grid of a 2D flow area from the area's own bounding box: the first point is half a cell inside the minimum x and the maximum y, then one point every spacing_dx / spacing_dy. A child area cut from a parent therefore gets a grid that is offset from the parent's by a sub-cell vector. A GridAnchor names a lattice point (and the spacing) that the regenerated grid must pass through instead, so a child or ensemble member re-meshes on the parent's lattice.

Coordinates and spacing are in the geometry's projected CRS and horizontal units. Only the phase (x mod spacing_dx, y mod spacing_dy) matters; any lattice point of the parent gives the same grid.

Attributes:

Name Type Description
x float

X coordinate of a lattice point.

y float

Y coordinate of a lattice point.

spacing_dx float

Lattice spacing in x (the base cell size).

spacing_dy float

Lattice spacing in y.

source str

Free-text provenance, such as the parent HDF and area name.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class GridAnchor:
    """One point of a 2D area's regular computation-point lattice.

    RAS Mapper lays the regular (base) grid of a 2D flow area from the
    area's own bounding box: the first point is half a cell inside the
    minimum x and the maximum y, then one point every ``spacing_dx`` /
    ``spacing_dy``. A child area cut from a parent therefore gets a grid
    that is offset from the parent's by a sub-cell vector. A ``GridAnchor``
    names a lattice point (and the spacing) that the regenerated grid must
    pass through instead, so a child or ensemble member re-meshes on the
    parent's lattice.

    Coordinates and spacing are in the geometry's projected CRS and
    horizontal units. Only the phase ``(x mod spacing_dx, y mod spacing_dy)``
    matters; any lattice point of the parent gives the same grid.

    Attributes:
        x: X coordinate of a lattice point.
        y: Y coordinate of a lattice point.
        spacing_dx: Lattice spacing in x (the base cell size).
        spacing_dy: Lattice spacing in y.
        source: Free-text provenance, such as the parent HDF and area name.
    """

    x: float
    y: float
    spacing_dx: float
    spacing_dy: float
    source: str = ""

    def __post_init__(self) -> None:
        for name in ("x", "y", "spacing_dx", "spacing_dy"):
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                raise TypeError(f"GridAnchor.{name} must be a number")
            if not math.isfinite(float(value)):
                raise ValueError(f"GridAnchor.{name} must be finite")
        if self.spacing_dx <= 0 or self.spacing_dy <= 0:
            raise ValueError("GridAnchor spacing must be positive")

    @property
    def phase(self) -> Tuple[float, float]:
        """Lattice phase ``(x mod spacing_dx, y mod spacing_dy)``."""
        return (
            float(self.x) % float(self.spacing_dx),
            float(self.y) % float(self.spacing_dy),
        )

    def to_dict(self) -> Dict[str, Any]:
        """Return machine-readable anchor evidence."""
        return {
            "x": float(self.x),
            "y": float(self.y),
            "spacing_dx": float(self.spacing_dx),
            "spacing_dy": float(self.spacing_dy),
            "phase": list(self.phase),
            "source": self.source,
        }

phase property

Python
phase: Tuple[float, float]

Lattice phase (x mod spacing_dx, y mod spacing_dy).

to_dict

Python
to_dict() -> Dict[str, Any]

Return machine-readable anchor evidence.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return machine-readable anchor evidence."""
    return {
        "x": float(self.x),
        "y": float(self.y),
        "spacing_dx": float(self.spacing_dx),
        "spacing_dy": float(self.spacing_dy),
        "phase": list(self.phase),
        "source": self.source,
    }

DomainContainmentResult dataclass

Pre-mesh containment evidence for one 2D flow area.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class DomainContainmentResult:
    """Pre-mesh containment evidence for one 2D flow area."""

    mesh_name: str
    geom_hdf_path: str
    base_cell_spacing: float
    inward_buffer_distance: float
    admissible_geometry_type: str
    checked_counts: Dict[str, int]
    violations: List[DomainContainmentViolation]

    @property
    def ok(self) -> bool:
        return not self.violations

    def __bool__(self) -> bool:
        return self.ok

    def to_dict(self) -> Dict[str, Any]:
        """Return machine-readable audit evidence without geometry payloads."""
        return {
            "mesh_name": self.mesh_name,
            "geom_hdf_path": self.geom_hdf_path,
            "base_cell_spacing": self.base_cell_spacing,
            "inward_buffer_distance": self.inward_buffer_distance,
            "admissible_geometry_type": self.admissible_geometry_type,
            "checked_counts": dict(self.checked_counts),
            "violation_count": len(self.violations),
            "ok": self.ok,
            "violations": [item.to_dict() for item in self.violations],
        }

to_dict

Python
to_dict() -> Dict[str, Any]

Return machine-readable audit evidence without geometry payloads.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return machine-readable audit evidence without geometry payloads."""
    return {
        "mesh_name": self.mesh_name,
        "geom_hdf_path": self.geom_hdf_path,
        "base_cell_spacing": self.base_cell_spacing,
        "inward_buffer_distance": self.inward_buffer_distance,
        "admissible_geometry_type": self.admissible_geometry_type,
        "checked_counts": dict(self.checked_counts),
        "violation_count": len(self.violations),
        "ok": self.ok,
        "violations": [item.to_dict() for item in self.violations],
    }

DomainContainmentViolation dataclass

One mesh-owned feature that is not inside the eroded 2D domain.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass(frozen=True)
class DomainContainmentViolation:
    """One mesh-owned feature that is not inside the eroded 2D domain."""

    feature_type: str
    feature_name: str
    feature_index: int
    geometry_type: str
    reason: str
    outside_length: float = 0.0
    outside_area: float = 0.0
    structure_type: str = ""

    def to_dict(self) -> Dict[str, Any]:
        """Return machine-readable violation evidence."""
        return {
            "feature_type": self.feature_type,
            "feature_name": self.feature_name,
            "feature_index": self.feature_index,
            "geometry_type": self.geometry_type,
            "reason": self.reason,
            "outside_length": self.outside_length,
            "outside_area": self.outside_area,
            "structure_type": self.structure_type,
        }

to_dict

Python
to_dict() -> Dict[str, Any]

Return machine-readable violation evidence.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Return machine-readable violation evidence."""
    return {
        "feature_type": self.feature_type,
        "feature_name": self.feature_name,
        "feature_index": self.feature_index,
        "geometry_type": self.geometry_type,
        "reason": self.reason,
        "outside_length": self.outside_length,
        "outside_area": self.outside_area,
        "structure_type": self.structure_type,
    }

BCConflict dataclass

A perimeter face covered by 2+ BC lines.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass
class BCConflict:
    """A perimeter face covered by 2+ BC lines."""

    face_id: int
    bc_names: List[str]
    flow_area_name: str = ""
    bc_types: List[str] = field(default_factory=list)
    normal_depth_bc: Optional[str] = None

BCFixResult dataclass

Result of BC conflict detection and repair.

Source code in ras_commander/geom/GeomMeshDataclasses.py
Python
@dataclass
class BCFixResult:
    """Result of BC conflict detection and repair."""

    conflicts_found: int = 0
    conflicts_fixed: int = 0
    trims: List[tuple] = field(default_factory=list)
    unresolvable: List[BCConflict] = field(default_factory=list)
    modified_hdf: bool = False

    @property
    def ok(self) -> bool:
        return len(self.unresolvable) == 0

    def __bool__(self) -> bool:
        return self.ok