Skip to content

Converters

DHyDAMO Converters API

Converters from HyDAMO data to D-HYDRO model objects, and from DAMO tables to HyDAMO.

df2hydrolibmodel

Convert the HyDAMO data to HYDROLIB-core models (structures, cross sections, forcings, fields).

ConstantWithInterpolation

Bases: Constant

Constant [Forcing] block that also writes timeInterpolation.

Workaround for the D-HYDRO GUI (2026.02), which raises an error when timeInterpolation is missing, although it has no meaning for a constant. hydrolib-core's Constant has no such field (a value passed to it is silently dropped). D-Flow FM (2026.02) accepts it and ignores it for constant values.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
119
120
121
122
123
124
125
126
127
128
129
class ConstantWithInterpolation(Constant):
    """Constant [Forcing] block that also writes timeInterpolation.

    Workaround for the D-HYDRO GUI (2026.02), which raises an error when timeInterpolation is missing,
    although it has no meaning for a constant. hydrolib-core's Constant has no such field (a value passed
    to it is silently dropped). D-Flow FM (2026.02) accepts it and ignores it for constant values.
    """

    timeinterpolation: TimeInterpolation = Field(
        TimeInterpolation.linear, alias="timeInterpolation"
    )

Df2HydrolibModel

HYDROLIB-core objects for everything in a HyDAMO object.

All conversions are done when the object is created; the results are in its attributes, e.g. structures, crossdefs, crosslocs and inifields.

Parameters

hydamo : HyDAMO The HyDAMO data to convert. assign_default_profiles : bool, optional Give the branches without a cross section the default cross section definition of hydamo.crosssections, halfway along the branch. Defaults to False.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
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
class Df2HydrolibModel:
    """HYDROLIB-core objects for everything in a HyDAMO object.

    All conversions are done when the object is created; the results are in its
    attributes, e.g. ``structures``, ``crossdefs``, ``crosslocs`` and ``inifields``.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO data to convert.
    assign_default_profiles : bool, optional
        Give the branches without a cross section the default cross section definition
        of ``hydamo.crosssections``, halfway along the branch. Defaults to False.
    """

    def __init__(self, hydamo: HyDAMO, assign_default_profiles: bool = False) -> None:
        self.hydamo = hydamo
        self.structures: list[Structure] = []
        self.crossdefs: list[CrossSectionDefinition] = []
        self.crosslocs: list[CrossSection] = []
        self.boundaries: list[Boundary] = []
        self.boundaries_ext: list[Boundary] = []
        self.boundaries_bc: list[ForcingBase] = []
        self.laterals_ext: list[Lateral] = []
        self.laterals_bc: list[ForcingBase] = []
        self.friction_defs: list[FrictGlobal] = []
        self.obspoints: list[ObservationPoint] = []
        self.storagenodes: list[StorageNode] = []
        self.inifields: list[InitialField] = []
        self.parameterfields: list[ParameterField] = []
        # data for the spatial fields, written by write_spatial_fields()
        self.spatial_data: dict[str, dict] = {}

        self.assign_default_profiles = assign_default_profiles
        self.forcingmodel = ForcingModel()
        self.forcingmodel.filepath = Path("boundaryconditions.bc")
        self.forcingmodel.forcing = []

        self.onedfieldmodels: list[OneDFieldGlobal] = []

        self.write_all()

    def write_all(self) -> None:
        """Convert all objects; called when the object is created."""
        self.regular_weirs_to_dhydro()
        self.orifices_to_dhydro()
        self.universal_weirs_to_dhydro()
        self.bridges_to_dhydro()
        self.culverts_to_dhydro()
        self.pumps_to_dhydro()
        self.compounds_to_dhydro()
        self.crosssection_locations_to_dhydro()
        self.crosssection_definitions_to_dhydro()
        self.friction_definitions_to_dhydro()
        self.boundaries_to_dhydro()
        self.laterals_to_dhydro()
        self.observation_points_to_dhydro()
        self.storagenodes_to_dhydro()
        self.inifields_to_dhydro()
        self.spatial_fields_to_dhydro()

    def ext_model(self) -> ExtModel:
        """Return the external forcings model (bnd.ext) with the boundaries and laterals.

        Use as ``fm.external_forcing.extforcefilenew = models.ext_model()``. The file version
        is set to ``EXT_FILE_VERSION``, as D-HYDRO 2026.02 does not read the default version of
        hydrolib-core 1.6.

        Returns
        -------
        ExtModel
            The external forcings model, readable by D-HYDRO.
        """
        extmodel = ExtModel(boundary=self.boundaries_ext, lateral=self.laterals_ext)
        extmodel.general.fileversion = EXT_FILE_VERSION
        return extmodel

    @staticmethod
    def _clear_comments(lst: INIBasedModel | list) -> None:
        """Remove the comments of INI objects, in place."""
        if not isinstance(lst, list):
            lst = [lst]
        for item in lst:
            if item.comments is None:
                continue
            for field, _ in item.comments:
                setattr(item.comments, field, "")

    def compounds_to_dhydro(self) -> None:
        """Convert the compound structures to Compound objects."""
        structs = [
            Compound(**struc)
            # into=dict only affects the type mypy sees, not the result:
            # - without it, pandas-stubs gives dict[Hashable, Any], which mypy rejects for **struc;
            # - into=dict[str, Any] would be exact, but pandas raises a TypeError on it;
            # - the bare dict gives dict[Any, Any], which is safe: our column names are always strings.
            for struc in self.hydamo.structures.compounds_df.to_dict(
                "records", into=dict
            )
        ]
        self._clear_comments(structs)
        self.structures += structs

    def regular_weirs_to_dhydro(self) -> None:
        """Convert the regular weirs to Weir objects."""
        structs = [
            Weir(**struc)
            # into=dict: see compounds_to_dhydro
            for struc in self.hydamo.structures.rweirs_df.to_dict("records", into=dict)
        ]
        self._clear_comments(structs)
        self.structures += structs

    def orifices_to_dhydro(self) -> None:
        """Convert the orifices to Orifice objects."""
        structs = [
            Orifice(**struc)
            # into=dict: see compounds_to_dhydro
            for struc in self.hydamo.structures.orifices_df.to_dict(
                "records", into=dict
            )
        ]
        self._clear_comments(structs)
        self.structures += structs

    def universal_weirs_to_dhydro(self) -> None:
        """Convert the universal weirs to UniversalWeir objects."""
        structs = [
            UniversalWeir(**struc)
            # into=dict: see compounds_to_dhydro
            for struc in self.hydamo.structures.uweirs_df.to_dict("records", into=dict)
        ]
        self._clear_comments(structs)
        self.structures += structs

    def bridges_to_dhydro(self) -> None:
        """Convert the bridges to Bridge objects."""
        structs = [
            Bridge(**struc)
            # into=dict: see compounds_to_dhydro
            for struc in self.hydamo.structures.bridges_df.to_dict("records", into=dict)
        ]
        self._clear_comments(structs)
        self.structures += structs

    def culverts_to_dhydro(self) -> None:
        """Convert the culverts to Culvert objects."""
        structs = [
            Culvert(**struc)
            # into=dict: see compounds_to_dhydro
            for struc in self.hydamo.structures.culverts_df.to_dict(
                "records", into=dict
            )
        ]
        self._clear_comments(structs)
        self.structures += structs

    def pumps_to_dhydro(self) -> None:
        """Convert the pumps to Pump objects."""
        structs = [
            Pump(**struc)
            # into=dict: see compounds_to_dhydro
            for struc in self.hydamo.structures.pumps_df.to_dict("records", into=dict)
        ]
        self._clear_comments(structs)
        self.structures += structs

    def crosssection_locations_to_dhydro(self) -> None:
        """Convert the cross section locations to CrossSection objects.

        With ``assign_default_profiles``, the default definition is first added to the
        default locations (or else to the branches without a cross section).
        """
        # Check which of the branches do not have a cross section. Add the default one to those
        branchids = {
            dct["branchid"]
            for dct in self.hydamo.crosssections.crosssection_loc.values()
        }

        # check if there locations specified where a default profile should be added
        default_locs: list[str] | pd.Index
        if hasattr(self.hydamo.crosssections, "default_locations"):
            default_locs = self.hydamo.crosssections.default_locations
        else:
            default_locs = self.hydamo.branches.index[
                ~self.hydamo.branches["code"].isin(branchids)
            ]

        # If any are missing, check if a default cross section definition has been defined
        if (len(default_locs) > 0) & (self.assign_default_profiles):
            default_definition = self.hydamo.crosssections.default_definition
            if default_definition is None:
                logger.warning(
                    "Not all branches have a cross section appointed to them. We assume D-Hydro can interpolate over these branches, otherwise errors will occur."
                )
            else:
                logger.info(
                    f"Adding default cross section definition to branches with ids: {', '.join(list(default_locs))}"
                )
                half_lengths = self.hydamo.branches.geometry.length / 2
                for branchid in default_locs:
                    self.hydamo.crosssections.add_crosssection_location(
                        branchid=branchid,
                        chainage=float(half_lengths.loc[branchid]),
                        definition=default_definition,
                        minz=np.nan,
                        shift=self.hydamo.crosssections.default_definition_shift,
                    )

        # Add cross sections to dhydro format
        css = [
            CrossSection(**cloc)
            for cloc in self.hydamo.crosssections.crosssection_loc.values()
        ]

        self._clear_comments(css)
        self.crosslocs += css

    def crosssection_definitions_to_dhydro(self) -> None:
        """Convert the cross section definitions to CrossSectionDefinition objects."""

        def _get_cstype_part_of_dict(cstype: str) -> dict:
            """Return the cross section definitions of one type."""
            return {
                key: dct
                for key, dct in self.hydamo.crosssections.crosssection_def.items()
                if dct["type"] == cstype
            }

        # Circles
        cs_circle = _get_cstype_part_of_dict("circle")
        circles = [CircleCrsDef(**cs) for cs in cs_circle.values()]
        self._clear_comments(circles)
        self.crossdefs += circles

        # YZ
        cs_yz = _get_cstype_part_of_dict("yz")
        yz_profiles = [YZCrsDef(**cs) for cs in cs_yz.values()]
        self._clear_comments(yz_profiles)
        self.crossdefs += yz_profiles

        # Rectangle
        cs_rect = _get_cstype_part_of_dict("rectangle")
        rectangles = [RectangleCrsDef(**cs) for cs in cs_rect.values()]
        self._clear_comments(rectangles)
        self.crossdefs += rectangles

        # Trapezium
        cs_zw = _get_cstype_part_of_dict("zw")
        zw_profiles = [ZWCrsDef(**cs) for cs in cs_zw.values()]
        self._clear_comments(zw_profiles)
        self.crossdefs += zw_profiles

    def boundaries_to_dhydro(self) -> None:
        """Convert the boundaries to [Boundary] blocks and forcings."""
        for bound in self.hydamo.external_forcings.boundary_nodes.values():
            bnd_bc: ConstantWithInterpolation | TimeSeries | QHTableWithInterpolation
            if bound["vec1"] is None:
                bnd_bc = ConstantWithInterpolation(
                    name=bound["nodeid"],
                    function="constant",
                    quantity=bound["quantity"],
                    unit=bound["unit2"],
                    datablock=[[bound["vec2"]]],
                )
            elif bound["unit1"].startswith("minutes"):
                bnd_bc = TimeSeries(
                    name=bound["nodeid"],
                    function="timeseries",
                    timeinterpolation="linear",
                    quantityunitpair=[
                        QuantityUnitPair(quantity="time", unit=bound["unit1"]),
                        QuantityUnitPair(
                            quantity=bound["quantity"], unit=bound["unit2"]
                        ),
                    ],
                    datablock=list(map(list, zip(bound["vec1"], bound["vec2"]))),
                )
            else:
                bnd_bc = QHTableWithInterpolation(
                    name=bound["nodeid"],
                    function="qhtable",
                    quantityunitpair=[
                        QuantityUnitPair(
                            quantity="qhbnd waterlevel", unit=bound["unit2"]
                        ),
                        QuantityUnitPair(
                            quantity="qhbnd discharge", unit=bound["unit1"]
                        ),
                    ],
                    datablock=list(map(list, zip(bound["vec2"], bound["vec1"]))),
                )

            self.forcingmodel.forcing.append(bnd_bc)
        for bound in self.hydamo.external_forcings.boundary_nodes.values():
            bnd_ext = Boundary(
                nodeid=bound["nodeid"],
                quantity=bound["quantity"],
                forcingfile=self.forcingmodel,
            )
            self.forcingmodel.filepath = Path("boundaryconditions.bc")
            self.boundaries_ext.append(bnd_ext)

    def laterals_to_dhydro(self) -> None:
        """Convert the laterals to [Lateral] blocks and forcings."""
        for key, lateral in self.hydamo.external_forcings.lateral_nodes.items():
            if isinstance(lateral["discharge"], str):
                # realtime boundary
                lat_ext = Lateral(
                    id=key,
                    locationtype="1d",
                    branchid=lateral["branchid"],
                    chainage=lateral["chainage"],
                    discharge=lateral["discharge"],
                )
            else:
                # time series or constant value
                lat_bc: TimeSeries | ConstantWithInterpolation
                if isinstance(lateral["discharge"], pd.Series):
                    lat_bc = TimeSeries(
                        name=key,
                        function="timeseries",
                        timeinterpolation="linear",
                        quantityunitpair=[
                            QuantityUnitPair(
                                quantity="time", unit=lateral["time_unit"]
                            ),
                            QuantityUnitPair(quantity="lateral_discharge", unit="m3/s"),
                        ],
                        datablock=list(
                            map(list, zip(lateral["time"], lateral["value"]))
                        ),
                    )
                    self.laterals_bc.append(lat_bc)
                else:
                    # add_lateral validates the discharge as a pd.Series, float or str
                    lat_bc = ConstantWithInterpolation(
                        name=key,
                        function="constant",
                        quantity="lateral_discharge",
                        unit="m3/s",
                        datablock=[[lateral["discharge"]]],
                    )
                self.forcingmodel.forcing.append(lat_bc)
                lat_ext = Lateral(
                    id=key,
                    locationtype=lateral["locationtype"],
                    branchid=lateral["branchid"],
                    chainage=float(lateral["chainage"]),
                    discharge=self.forcingmodel,
                )
            self.laterals_ext.append(lat_ext)

    def friction_definitions_to_dhydro(self) -> None:
        """Convert the friction definitions to FrictGlobal objects."""
        frictdefs = [
            FrictGlobal(**frictdef)
            for frictdef in self.hydamo.roughness_definitions.values()
        ]
        self._clear_comments(frictdefs)
        self.friction_defs += frictdefs

    def storagenodes_to_dhydro(self) -> None:
        """Convert the storage nodes to StorageNode objects."""
        stornodes = [
            StorageNode(**stornode)
            for stornode in self.hydamo.storagenodes.storagenodes.values()
        ]
        self._clear_comments(stornodes)
        self.storagenodes += stornodes

    def observation_points_to_dhydro(self) -> None:
        """Convert the observation points to ObservationPoint objects."""
        if hasattr(self.hydamo.observationpoints, "observation_points"):
            obspoints = [
                ObservationPoint(**obs)
                # into=dict: see compounds_to_dhydro
                for obs in self.hydamo.observationpoints.observation_points.drop(
                    columns="geometry"
                ).to_dict("records", into=dict)
            ]
            self._clear_comments(obspoints)
            self.obspoints += obspoints

    def inifields_to_dhydro(self) -> None:
        """Convert uniform initial water levels and depths to InitialField objects with a 1dField data file.

        The corresponding OneDFieldGlobal objects are stored in self.onedfieldmodels, in the same order as the
        1dField entries in self.inifields. Use write_initial_fields() to write them.
        """
        initial = [
            ("waterlevel", self.hydamo.external_forcings.initial_waterlevel_polygons),
            ("waterdepth", self.hydamo.external_forcings.initial_waterdepth_polygons),
        ]
        for quantity, gdf in initial:
            # uniform 1D values are written per branch by spatial_fields_to_dhydro
            if gdf.empty or (gdf["locationtype"] == "1d").all():
                continue
            if gdf.geometry.notna().any() or len(gdf) > 1:
                raise ValueError(
                    f"Initial {quantity} with polygons is not supported by set_initial_{quantity}. "
                    "Use hydamo.external_forcings.set_spatial_field() for spatially varying values."
                )
            row = gdf.iloc[0]
            # e.g. initialwaterlevel_2d.ini; the 1D files use the names of the GUI (ONEDFIELD_FILES)
            filename = f"initial{quantity}_{row['locationtype']}.ini"
            inifield = InitialField(
                quantity=quantity,
                datafiletype="1dField",
                datafile=filename,
                locationtype=row["locationtype"],
            )
            onedfield = OneDFieldGlobal(
                quantity=quantity,
                unit="m",
                value=str(row[quantity]),
            )
            self._clear_comments(inifield)
            self._clear_comments(onedfield)
            self.inifields.append(inifield)
            self.onedfieldmodels.append(onedfield)

    def spatial_fields_to_dhydro(self) -> None:
        """Convert spatial fields (branch values, polygons, rasters or samples) to InitialField/ParameterField objects.

        Branch values are derived from the HyDAMO branches. All initial water level and water depth fields per
        branch (including uniform 1D values) are combined into one 1dField file per quantity (ONEDFIELD_FILES), as
        the D-HYDRO GUI expects. This gives the same result in D-Flow FM: a field per branch fills whole branches
        and the last field wins, so per branch the values of the last field are kept, and a branch that a later
        field gives the other quantity is moved to that quantity. The combined block is placed at the position of
        the last field of that quantity. Polygon files get one .pol file and one block per distinct value. Only the
        references are created here; the data files themselves are written by write_spatial_fields().
        """
        # footprints of the initial water level and depth fields, to check where both apply
        level_depth_fields = []
        # initial water level and depth per branch, combined into one 1dField file per quantity
        combined = _CombinedOneDFields()
        # order of the blocks: ("combined", kind) or ("blocks", spatial field, [(filename, datafiletype, value)])
        order: list[tuple] = []
        for sf in self.hydamo.external_forcings.spatial_fields:
            kind = None
            if sf["kind"] == "initial":
                kind = level_or_depth(sf["quantity"])
            if sf["filetype"] == "branch" and kind is not None:
                # combined with the other fields of this quantity, at the position of the last one; see the docstring
                branch_values = self._branch_values(sf)
                combined.add(kind, sf["quantity"], branch_values)
                order = [entry for entry in order if entry != ("combined", kind)] + [
                    ("combined", kind)
                ]
                data: dict | None = {"branches": branch_values}
            else:
                order.append(("blocks", sf, self._field_blocks(sf)))
                data = self.spatial_data.get(sf["filename"])
            footprint = self._level_depth_footprint(sf, data)
            if footprint is not None:
                level_depth_fields.append(footprint)

        self._add_fields_in_order(order, combined)
        self._check_level_and_depth(level_depth_fields, self.hydamo.branches)
        self._check_uniform_depth(level_depth_fields)

    def _add_fields_in_order(
        self, order: list[tuple], combined: _CombinedOneDFields
    ) -> None:
        """Add the blocks of the spatial fields to the initial and parameter fields, in their order.

        Parameters
        ----------
        order : list[tuple]
            ("combined", kind) for a combined 1dField file, or ("blocks", spatial field,
            [(filename, datafiletype, value)]) for the blocks of another field.
        combined : _CombinedOneDFields
            The combined initial water level and depth per branch.
        """
        for entry in order:
            if entry[0] == "combined":
                self._add_combined_field(entry[1], combined)
                continue
            _, sf, blocks = entry
            for filename, datafiletype, value in blocks:
                self._add_block_field(sf, filename, datafiletype, value)

    def _field_blocks(self, sf: dict) -> list[tuple[str, str, float | None]]:
        """Return the data and blocks of a spatial field that is not combined with other fields.

        The data is stored in self.spatial_data, and written by write_spatial_fields().

        Parameters
        ----------
        sf : dict
            The spatial field, see ExternalForcings.set_spatial_field.

        Returns
        -------
        list[tuple[str, str, float | None]]
            (filename, datafiletype, value) per block; value is only set for polygon files.
        """
        builders = {
            "polygon": self._polygon_blocks,
            "branch": self._branch_blocks,
            "raster": self._raster_blocks,
        }
        return builders.get(sf["filetype"], self._sample_blocks)(sf)

    def _polygon_blocks(self, sf: dict) -> list[tuple[str, str, float | None]]:
        """One .pol file and one block per distinct value of a polygon field.

        Parameters
        ----------
        sf : dict
            The spatial field.

        Returns
        -------
        list[tuple[str, str, float | None]]
            (filename, 'polygon', value) per distinct value.
        """
        gdf, column = sf["gdf"], sf["column"]
        values = sorted(gdf[column].astype(float).unique())
        stem, suffix = Path(sf["filename"]).stem, Path(sf["filename"]).suffix or ".pol"
        blocks: list[tuple[str, str, float | None]] = []
        for i, value in enumerate(values):
            filename = sf["filename"] if len(values) == 1 else f"{stem}_{i:02d}{suffix}"
            geometries = gdf.loc[gdf[column].astype(float) == value].geometry
            self.spatial_data[filename] = {
                "filetype": "polygon",
                "polygons": [
                    poly for geom in geometries for poly in common.as_polygon_list(geom)
                ],
            }
            blocks.append((filename, "polygon", value))
        return blocks

    def _branch_values(
        self, sf: dict
    ) -> dict[Hashable, tuple[list[float], list[float]]]:
        """Values per branch of a field: a uniform value, or derived from polygons or points.

        Parameters
        ----------
        sf : dict
            The spatial field, with filetype 'branch'.

        Returns
        -------
        dict[Hashable, tuple[list[float], list[float]]]
            Chainages and values per branch id.

        Raises
        ------
        ValueError
            For a uniform value without branches.
        """
        gdf, column = sf["gdf"], sf["column"]
        if sf.get("uniform") is not None:
            branches = self.hydamo.branches
            if branches is None or branches.empty:
                raise ValueError(
                    f"A uniform initial {sf['quantity']} for 1D requires the branches."
                )
            branch_values = {
                branch_id: ([0.0, line.length], [sf["uniform"]] * 2)
                for branch_id, line in zip(branches.index, branches.geometry)
            }
        elif gdf.geom_type.isin(["Polygon", "MultiPolygon"]).all():
            branch_values = polygons_to_branch_values(self.hydamo.branches, gdf, column)
        else:
            branch_values = points_to_branch_values(
                self.hydamo.branches, gdf, column, max_distance=sf["max_snap_distance"]
            )
        if not branch_values:
            logger.warning(f"No values on any branch for {sf['filename']}.")
        return branch_values

    def _branch_blocks(self, sf: dict) -> list[tuple[str, str, float | None]]:
        """Return a 1dField file and block for a field per branch that is not combined.

        E.g. a parameter field.

        Parameters
        ----------
        sf : dict
            The spatial field, with filetype 'branch'.

        Returns
        -------
        list[tuple[str, str, float | None]]
            One block (filename, '1dField', None).
        """
        self.spatial_data[sf["filename"]] = {
            "filetype": "branch",
            "branches": self._branch_values(sf),
            "quantity": sf["quantity"],
            "nodata": sf["nodata"],
        }
        return [(sf["filename"], "1dField", None)]

    def _raster_blocks(self, sf: dict) -> list[tuple[str, str, float | None]]:
        """Return a raster (GeoTIFF or ArcInfo grid) and block for a polygon field.

        Parameters
        ----------
        sf : dict
            The spatial field, with filetype 'raster'.

        Returns
        -------
        list[tuple[str, str, float | None]]
            One block (filename, 'arcInfo' or 'GeoTIFF', None).
        """
        gdf = sf["gdf"]
        array, transform = rasterize_polygons(
            gdf, sf["column"], sf["cellsize"], fill=sf["nodata"]
        )
        self.spatial_data[sf["filename"]] = {
            "filetype": "raster",
            "array": array,
            "transform": transform,
            "crs": gdf.crs,
            "nodata": sf["nodata"],
        }
        datafiletype = (
            "arcInfo" if Path(sf["filename"]).suffix.lower() == ".asc" else "GeoTIFF"
        )
        return [(sf["filename"], datafiletype, None)]

    def _sample_blocks(self, sf: dict) -> list[tuple[str, str, float | None]]:
        """Return a sample file (.xyz) and block for a point field.

        Parameters
        ----------
        sf : dict
            The spatial field, with filetype 'sample'.

        Returns
        -------
        list[tuple[str, str, float | None]]
            One block (filename, 'sample', None).
        """
        if sf.get("xyz_file") is not None:
            # an existing .xyz file: copied unchanged by write_spatial_fields(), its values are not read
            self.spatial_data[sf["filename"]] = {
                "filetype": "xyz_file",
                "path": sf["xyz_file"],
            }
            return [(sf["filename"], "sample", None)]
        gdf = sf["gdf"]
        self.spatial_data[sf["filename"]] = {
            "filetype": "sample",
            "x": gdf.geometry.x.to_numpy(),
            "y": gdf.geometry.y.to_numpy(),
            "z": gdf[sf["column"]].to_numpy(dtype=float),
        }
        return [(sf["filename"], "sample", None)]

    def _add_combined_field(self, kind: str, combined: _CombinedOneDFields) -> None:
        """Add the combined 1dField file and [Initial] block of a quantity, if it has values.

        Parameters
        ----------
        kind : str
            'waterlevel' or 'waterdepth'.
        combined : _CombinedOneDFields
            The combined values per branch.
        """
        if not combined.branches[kind]:
            return
        filename = ONEDFIELD_FILES[kind]
        self.spatial_data[filename] = {
            "filetype": "branch",
            "branches": combined.branches[kind],
            "quantity": combined.quantity[kind],
            "nodata": -999.0,
        }
        field = InitialField(
            quantity=combined.quantity[kind], datafile=filename, datafiletype="1dField"
        )
        self._clear_comments(field)
        self.inifields.append(field)

    def _add_block_field(
        self, sf: dict, filename: str, datafiletype: str, value: float | None
    ) -> None:
        """Add an [Initial] or [Parameter] block for a data file of a spatial field.

        Parameters
        ----------
        sf : dict
            The spatial field.
        filename : str
            The data file.
        datafiletype : str
            Data file type, e.g. '1dField', 'polygon', 'GeoTIFF' or 'sample'.
        value : float | None
            Value inside the polygons, for polygon files.
        """
        kwargs = {
            "quantity": sf["quantity"],
            "datafile": filename,
            "datafiletype": datafiletype,
            "interpolationmethod": sf["interpolationmethod"],
            "locationtype": sf["locationtype"],
            "operand": sf["operand"],
        }
        if value is not None:
            kwargs["value"] = value
        if datafiletype == "1dField":
            # interpolation and location type are not used for 1dField files
            del kwargs["interpolationmethod"], kwargs["locationtype"]
        if sf["interpolationmethod"] == "averaging":
            kwargs["averagingtype"] = sf["averagingtype"]
        # only the sample settings that are set: unset ones are left to D-Flow FM's defaults
        for setting, setting_value in sf.get("sample_settings", {}).items():
            if setting_value is not None:
                kwargs[setting] = setting_value

        if sf["kind"] == "initial":
            initial_field = InitialField(**kwargs)
            self._clear_comments(initial_field)
            self.inifields.append(initial_field)
        else:
            parameter_field = ParameterField(**kwargs)
            self._clear_comments(parameter_field)
            self.parameterfields.append(parameter_field)

    def _level_depth_footprint(self, sf: dict, data: dict | None) -> dict | None:
        """Where an initial water level or depth field gives values on the 1D network.

        - 'branch': the whole branches in the 1dField file (values are kept constant beyond the first and
          last chainage);
        - 'polygon' and 'raster': the polygons;
        - 'sample': the convex hull of the points, which triangulation fills (tested with D-HYDRO 2026.02).

        Returns None for other quantities, parameter fields and 2D-only fields.
        """
        kind = level_or_depth(sf["quantity"])
        if sf["kind"] != "initial" or kind is None:
            return None
        if sf["filetype"] != "branch" and sf["locationtype"] not in ("1d", "all"):
            return None
        footprint = {
            "kind": kind,
            "quantity": sf["quantity"],
            "filename": sf["filename"],
            "filetype": sf["filetype"],
            # a uniform value (set_initial_waterlevel/-depth) is a background that later fields override on purpose
            "background": sf.get("uniform") is not None,
        }
        if sf["filetype"] == "branch":
            footprint["branches"] = set(data["branches"]) if data else set()
            footprint["area"] = None
        elif sf["filetype"] == "sample":
            if data is None:
                raise ValueError(f"No sample data for {sf['filename']}.")
            footprint["branches"] = None
            footprint["area"] = shapely.MultiPoint(
                list(zip(data["x"], data["y"]))
            ).convex_hull
        else:
            footprint["branches"] = None
            footprint["area"] = shapely.union_all(sf["gdf"].geometry.to_numpy())
        return footprint

    @staticmethod
    def _covered_parts(
        footprint: dict, branches: gpd.GeoDataFrame
    ) -> dict[str, list[tuple[float, float]]]:
        """Parts of the branches covered by a footprint, as {branch id: [(start chainage, end chainage), ...]}.

        Chainage intervals are compared instead of line geometries, which is robust to rounding in intersections.
        """
        if footprint["branches"] is not None:
            selected = branches.loc[branches.index.isin(list(footprint["branches"]))]
            return {
                branch_id: [(0.0, line.length)]
                for branch_id, line in zip(selected.index, selected.geometry)
            }
        candidates = branches.iloc[
            branches.sindex.query(footprint["area"], predicate="intersects")
        ]
        covered = {}
        for branch_id, line in zip(candidates.index, candidates.geometry):
            intervals = []
            for part in line_parts(line.intersection(footprint["area"])):
                chainages = [line.project(shapely.Point(c)) for c in part.coords]
                intervals.append((min(chainages), max(chainages)))
            if intervals:
                covered[branch_id] = intervals
        return covered

    @staticmethod
    def _overlap_length(
        intervals_i: list[tuple[float, float]], intervals_j: list[tuple[float, float]]
    ) -> float:
        """Total length of the overlap between two lists of chainage intervals."""
        return sum(
            max(0.0, min(b_i, b_j) - max(a_i, a_j))
            for a_i, b_i in intervals_i
            for a_j, b_j in intervals_j
        )

    @classmethod
    def _check_level_and_depth(
        cls, fields: list[dict], branches: gpd.GeoDataFrame, tolerance: float = 0.01
    ) -> None:
        """Warn where a water level field and a water depth field both give values on the same part of a branch.

        D-Flow FM applies the fields in order, and the last field wins, also between water level and water
        depth (tested with D-HYDRO 2026.02). The footprints are larger than the input geometries suggest:
        triangulation fills the convex hull of the samples, and a 1dField file fills whole branches. Overlap
        only at junctions (shorter than `tolerance`) is ignored.

        Also warns for a water depth from polygons, samples or rasters after a water level from polygons, samples
        or rasters. In DIMR tests (2026.02) such a water depth field removed those water levels everywhere, also
        outside its own area. Water levels per branch (1dField) were kept, and a water depth per branch removed
        nothing. Rasters were not tested and are treated like samples.
        """
        has_branches = (
            branches is not None and not branches.empty and "geometry" in branches
        )
        parts = (
            [cls._covered_parts(f, branches) for f in fields] if has_branches else []
        )

        for (i, field_i), (j, field_j) in itertools.combinations(enumerate(fields), 2):
            if (
                field_i["kind"] == field_j["kind"]
                or field_i["background"]
                or field_j["background"]
            ):
                continue
            message = cls._overlap_message(field_i, field_j)
            if has_branches:
                shared = cls._shared_branches(parts[i], parts[j], tolerance)
                if shared:
                    logger.warning(
                        f"{len(shared)} branch(es) {message} Branches: {shared[:10]}"
                    )
            elif cls._areas_overlap(field_i, field_j):
                # no network to check against: the areas overlap
                logger.warning(f"The areas of the 1D fields {message}")

        cls._warn_depth_after_level(fields)

    @staticmethod
    def _overlap_message(field_i: dict, field_j: dict) -> str:
        """Message for a water level and a water depth field that give values at the same place.

        Parameters
        ----------
        field_i, field_j : dict
            Footprints of the earlier and the later field.

        Returns
        -------
        str
            The message, with a note on why the footprints may be larger than expected.
        """
        notes = []
        if "sample" in (field_i["filetype"], field_j["filetype"]):
            notes.append(
                "samples with triangulation fill the convex hull of the points"
            )
        if "branch" in (field_i["filetype"], field_j["filetype"]):
            notes.append("a 1dField file fills the whole branch")
        note = f" Note: {'; '.join(notes)}." if notes else ""
        header = (
            f"get both a {field_i['quantity']} ({field_i['filename']}) and a {field_j['quantity']} "
            f"({field_j['filename']}). There the {field_j['quantity']} applies, as it is added last."
        )
        return f"{header}{note}"

    @classmethod
    def _shared_branches(
        cls,
        parts_i: dict[str, list[tuple[float, float]]],
        parts_j: dict[str, list[tuple[float, float]]],
        tolerance: float,
    ) -> list[str]:
        """Branches where two footprints overlap over more than `tolerance`.

        Parameters
        ----------
        parts_i, parts_j : dict[str, list[tuple[float, float]]]
            Covered chainage intervals per branch id, see _covered_parts.
        tolerance : float
            Overlap up to this length (e.g. only at junctions) is ignored.

        Returns
        -------
        list[str]
            Sorted branch ids.
        """
        return sorted(
            branch_id
            for branch_id in parts_i.keys() & parts_j.keys()
            if cls._overlap_length(parts_i[branch_id], parts_j[branch_id]) > tolerance
        )

    @staticmethod
    def _areas_overlap(field_i: dict, field_j: dict) -> bool:
        """Whether the areas of two footprints overlap; False if one of them has no area (fields per branch).

        Parameters
        ----------
        field_i, field_j : dict
            Footprints of two fields.

        Returns
        -------
        bool
            True if the areas overlap.
        """
        if field_i["area"] is None or field_j["area"] is None:
            return False
        return field_i["area"].intersection(field_j["area"]).area > 0.0

    @staticmethod
    def _warn_depth_after_level(fields: list[dict]) -> None:
        """Warn for a water depth from polygons, samples or rasters after such a water level.

        In tests with D-HYDRO 2026.02, such a water depth field removed those water levels everywhere, also
        outside its own area. Fields per branch (1dField) are not affected.

        Parameters
        ----------
        fields : list[dict]
            Footprints of the initial water level and depth fields, in their order.
        """
        for j, field in enumerate(fields):
            if field["kind"] != "waterdepth" or field["filetype"] == "branch":
                continue
            earlier = [
                f["filename"]
                for f in fields[:j]
                if f["kind"] == "waterlevel" and f["filetype"] != "branch"
            ]
            if earlier:
                logger.warning(
                    f"The {field['quantity']} field {field['filename']} ({field['filetype']}) is added after water level "
                    f"field(s) {earlier}. In tests with D-HYDRO 2026.02, a water depth from polygons or samples removed "
                    "earlier water levels from polygons or samples everywhere, also outside its own area. Add water "
                    "depth fields before water level fields, or write the water levels per branch."
                )

    def _check_uniform_depth(self, fields: list[dict]) -> None:
        """Warn when a uniform water depth is combined with spatial water levels: the depth overrides them.

        Only for a uniform depth for 2D or 'all' ([Global] value); a uniform 1D depth is written per branch and
        behaves like any other field.
        """
        uniform_depth = self.hydamo.external_forcings.initial_waterdepth_polygons
        levels = [
            f["filename"]
            for f in fields
            if f["kind"] == "waterlevel" and not f["background"]
        ]
        if (
            not uniform_depth.empty
            and (uniform_depth["locationtype"] != "1d").any()
            and levels
        ):
            logger.warning(
                f"A uniform initial water depth is combined with spatial water level field(s) {levels}. "
                "In D-HYDRO 2026.02 the uniform water depth overrides these water levels, whatever the order."
            )

    def write_spatial_fields(self, output_dir: Path | str) -> None:
        """Write the data files of the spatial fields (1dField files, polygon files, rasters and samples).

        The files are referenced relative to initialFields.ini, so output_dir should be the
        folder where the FMModel (and its initialFields.ini) is saved.

        Parameters
        ----------
        output_dir : Path or str
            The fm folder of the model.
        """
        output_dir = Path(output_dir)
        for filename, data in self.spatial_data.items():
            path = output_dir / filename
            path.parent.mkdir(parents=True, exist_ok=True)
            if data["filetype"] == "branch":
                # The D-HYDRO GUI requires a [Global] block. D-Flow FM (2026.02) treats the nodata value as no
                # value, so branches without values keep the value of earlier fields or WaterLevIni.
                quantity = data["quantity"]
                unit = (
                    "m"
                    if quantity.lower().replace("initial", "")
                    in ("waterlevel", "waterdepth")
                    else "-"
                )
                OneDFieldModel(
                    global_=OneDFieldGlobal(
                        quantity=quantity, unit=unit, value=data["nodata"]
                    ),
                    branch=[
                        OneDFieldBranch(
                            branchid=str(branch_id),
                            numlocations=len(chainage),
                            chainage=chainage,
                            values=values,
                        )
                        for branch_id, (chainage, values) in data["branches"].items()
                    ],
                ).save(filepath=path)
            elif data["filetype"] == "polygon":
                objects = []
                for i, polygon in enumerate(data["polygons"]):
                    coords = list(polygon.exterior.coords)
                    objects.append(
                        PolyObject(
                            metadata=Metadata(
                                name=f"{path.stem}_{i:04d}",
                                n_rows=len(coords),
                                n_columns=2,
                            ),
                            points=[
                                PolyPoint(x=x, y=y, data=[]) for x, y, *_ in coords
                            ],
                        )
                    )
                PolyFile(objects=objects).save(filepath=path)
            elif data["filetype"] == "xyz_file":
                shutil.copyfile(data["path"], path)
            elif data["filetype"] == "raster":
                write_raster(
                    path,
                    data["array"],
                    data["transform"],
                    crs=data["crs"],
                    nodata=data["nodata"],
                )
            else:
                xyz = XYZModel(
                    points=[
                        XYZPoint(x=x, y=y, z=z)
                        for x, y, z in zip(data["x"], data["y"], data["z"])
                    ]
                )
                xyz.save(filepath=path)

    def write_initial_fields(self, fm: FMModel, fm_dir: Path | str) -> IniFieldModel:
        """Add all initial fields and parameter fields to the FM model and write their data files.

        This writes the 1dField files (uniform values), rasters and sample files to fm_dir, and links them
        in initialFields.ini, using paths relative to the fm folder. Call this before saving the FM model.
        It logs a warning when D-Flow FM would use the uniform bed level (BedlevUni) for the whole 2D mesh,
        see _warn_missing_bedlevel.

        Parameters
        ----------
        fm : FMModel
            The FM model.
        fm_dir : Path or str
            Folder where the FM model (mdu file) is written.

        Returns
        -------
        IniFieldModel
            The initial fields model, also set as ``fm.geometry.inifieldfile``.
        """
        fm_dir = Path(fm_dir)
        fm_dir.mkdir(parents=True, exist_ok=True)

        onedfield_inifields = [f for f in self.inifields if f.datafiletype == "1dField"]
        for inifield, onedfield in zip(onedfield_inifields, self.onedfieldmodels):
            if inifield.datafile is None or inifield.datafile.filepath is None:
                raise ValueError(
                    f"The 1dField initial field for {inifield.quantity} has no data file."
                )
            onedfieldmodel = OneDFieldModel(global_=onedfield)
            onedfieldmodel.save(filepath=fm_dir / inifield.datafile.filepath.name)

        self.write_spatial_fields(fm_dir)
        self._warn_missing_bedlevel(fm)

        inifieldmodel = IniFieldModel(
            initial=self.inifields, parameter=self.parameterfields
        )
        fm.geometry.inifieldfile = inifieldmodel
        return inifieldmodel

    def _warn_missing_bedlevel(self, fm: FMModel) -> None:
        """Warn when the 2D mesh gets no bed level for the bedLevType of the model.

        D-Flow FM then uses the uniform bed level (BedlevUni). Where it takes the bed level from (D-Flow FM source,
        2026): with bedLevType 1 the face bed level of the net file and a 2D bed level field, with 3 the node
        bed level and a 2D bed level field, with 4 to 6 only the node bed level (a bed level field is not used).
        bedLevType 2 is not checked. Models without a 2D mesh are not checked: 1D bed levels come from the cross
        sections.

        Parameters
        ----------
        fm : FMModel
            The FM model, with the network and bedLevType.
        """
        netfile = fm.geometry.netfile
        if not isinstance(netfile, NetworkModel) or netfile.network._mesh2d.is_empty():
            return
        mesh2d = netfile.network._mesh2d
        bedlevtype = fm.geometry.bedlevtype
        bedlevel_field = False
        for field in self.inifields:
            if field.quantity.lower() != "bedlevel":
                continue
            if str(field.locationtype).lower() in {"2d", "all"}:
                bedlevel_field = True
                break
        hint = "Use mesh2d_altitude_from_raster with where='{}', or a bed level field from set_spatial_field."
        # where D-Flow FM takes the bed level from per bedLevType, and the BedlevUni fallback:
        # https://github.com/Deltares/Delft3D/blob/62e91f7a617226e0938e065fdd8fc969eb7f1d72/src/engines_gpl/dflowfm/packages/dflowfm_kernel/src/dflowfm_kernel/prepost/setbedlevelfromextfile.f90
        if bedlevtype == 1 and mesh2d.mesh2d_face_z.size == 0 and not bedlevel_field:
            logger.warning(
                "bedLevType is 1, but the 2D mesh has no face bed level and there is no 2D bed level field, so "
                f"D-Flow FM uses BedlevUni everywhere. {hint.format('face')}"
            )
        elif bedlevtype == 3 and mesh2d.mesh2d_node_z.size == 0 and not bedlevel_field:
            logger.warning(
                "bedLevType is 3, but the 2D mesh has no node bed level and there is no 2D bed level field, so "
                f"D-Flow FM uses BedlevUni everywhere. {hint.format('node')}"
            )
        elif bedlevtype in {4, 5, 6} and mesh2d.mesh2d_node_z.size == 0:
            unused = ""
            if bedlevel_field:
                unused = (
                    " D-Flow FM does not use a bed level field with bedLevType 4 to 6."
                )
            logger.warning(
                f"bedLevType is {bedlevtype}, but the 2D mesh has no node bed level, so D-Flow FM uses BedlevUni "
                f"everywhere.{unused} Use mesh2d_altitude_from_raster with where='node', or bedLevType 1 or 3."
            )

    def initial_conditions_at_nodes(
        self,
        network: Network,
        output_file: Path | str | None = None,
        crs: CRS | str | None = None,
    ) -> gpd.GeoDataFrame:
        """Approximate the initial water level or depth at the 1D computational nodes.

        A diagnostic to check the initial conditions, e.g. in a GIS, since the D-HYDRO GUI hardly shows them.
        It is not computed by D-Flow FM: it reproduces how D-Flow FM applied the initial fields in tests with
        D-HYDRO 2026.02 (1404 to 1421 of the 1421 nodes of the test model matched the water level at t=0;
        differences at junctions and structures). Other D-Flow FM versions may behave differently. The fields
        differences at junctions and structures). Other D-Flow FM versions may behave differently. The fields
        are applied in their order:

        - values per branch (1dField) are interpolated along the branch and kept constant beyond the first and
          last chainage; uniform values apply everywhere;
        - samples are interpolated linearly in triangles (inside their convex hull), polygon files apply inside
          the polygons; rasters are not evaluated;
        - where fields overlap the last one applies, also between water level and water depth;
        - a water depth from polygons or samples removes earlier water levels from polygons or samples;
        - a uniform water depth overrides spatial water levels.
        Nodes without a value keep the default water level of the MDU (WaterLevIni), shown as missing here.

        Parameters
        ----------
        network : Network
            The network with the 1D mesh, e.g. ``fm.geometry.netfile.network``.
        output_file : Path or str, optional
            Shapefile (.shp) or GeoPackage (.gpkg) to write. Defaults to None.
        crs : optional
            Coordinate reference system. Defaults to the crs of the HyDAMO branches, or
            EPSG:28992 (as written to the model by ``DIMRWriter.add_crs``) if they have none.

        Returns
        -------
        gpd.GeoDataFrame
            One point per node with branchid, chainage, quantity ('waterlevel' or
            'waterdepth'), value and source (data file of the field that sets the value).
        """
        mesh1d = network._mesh1d
        x, y = (
            np.asarray(mesh1d.mesh1d_node_x, dtype=float),
            np.asarray(mesh1d.mesh1d_node_y, dtype=float),
        )
        branch_names = np.asarray(mesh1d.network1d_branch_id, dtype=object)
        mesh_nodes = _Mesh1dNodes(
            x=x,
            y=y,
            branchid=branch_names[np.asarray(mesh1d.mesh1d_node_branch_id, dtype=int)],
            chainage=np.asarray(mesh1d.mesh1d_node_branch_offset, dtype=float),
            points=gpd.points_from_xy(x, y),
        )
        state = _NodeValues(len(x))
        uniform_depth = None

        uniform_fields = iter(self.onedfieldmodels)
        for inifield in self.inifields:
            field = self._inifield_at_nodes(inifield, uniform_fields, mesh_nodes)
            if field is None:
                continue
            kind, values, filename, filetype = field
            state.apply(kind, values, filename, filetype)
            if filetype == "uniform" and kind == "waterdepth":
                uniform_depth = (values, filename)

        if uniform_depth is not None:
            state.apply_uniform_depth(*uniform_depth)

        nodes = gpd.GeoDataFrame(
            {
                "node_id": np.asarray(mesh1d.mesh1d_node_id, dtype=object),
                "branchid": mesh_nodes.branchid,
                "chainage": mesh_nodes.chainage,
                "quantity": state.quantity,
                "value": state.value,
                "source": state.source,
            },
            geometry=mesh_nodes.points,
            crs=self._nodes_crs(crs),
        )
        if (nodes["quantity"].isna()).any():
            logger.info(
                f"{nodes['quantity'].isna().sum()} 1D nodes get no initial value and keep WaterLevIni."
            )
        if output_file is not None:
            nodes.to_file(output_file)
        return nodes

    def _inifield_at_nodes(
        self, inifield: InitialField, uniform_fields: Iterator, nodes: _Mesh1dNodes
    ) -> tuple[str, np.ndarray, str | None, str] | None:
        """Values of an initial field at the 1D nodes, if it sets a water level or depth there.

        Parameters
        ----------
        inifield : InitialField
            The initial field.
        uniform_fields : Iterator
            The [Global] blocks of the uniform values (self.onedfieldmodels); the next one is consumed for
            every uniform value, also when it is skipped.
        nodes : _Mesh1dNodes
            The 1D nodes.

        Returns
        -------
        tuple[str, np.ndarray, str | None, str] | None
            (kind, value per node, data file, filetype), with kind 'waterlevel' or 'waterdepth' and filetype
            'uniform' or that of the spatial data; None if the field gives no water level or depth at the nodes,
            also for 2D-only fields (locationtype '2d').
        """
        filename = (
            inifield.datafile.filepath.name
            if inifield.datafile and inifield.datafile.filepath
            else None
        )
        kind = level_or_depth(inifield.quantity)
        data = None
        if filename is not None:
            data = self.spatial_data.get(filename)
        if data is None and inifield.datafiletype == "1dField":
            onedfield = next(uniform_fields)
            values = self._uniform_values_at_nodes(
                inifield, kind, float(onedfield.value), len(nodes.x)
            )
            filetype = "uniform"
        elif kind is None or data is None or str(inifield.locationtype).lower() == "2d":
            # a 2D-only field does not reach the 1D nodes
            return None
        else:
            values = self._spatial_values_at_nodes(inifield, filename, data, nodes)
            filetype = data["filetype"]
        if values is None or kind is None:
            return None
        return kind, values, filename, filetype

    @staticmethod
    def _uniform_values_at_nodes(
        inifield: InitialField, kind: str | None, value: float, n: int
    ) -> np.ndarray | None:
        """Values of a uniform 1D water level or depth at the nodes.

        Parameters
        ----------
        inifield : InitialField
            The initial field of the uniform value.
        kind : str | None
            'waterlevel', 'waterdepth', or None for other quantities.
        value : float
            The uniform value.
        n : int
            Number of nodes.

        Returns
        -------
        np.ndarray | None
            The value at every node, or None for other quantities and 2D-only fields.
        """
        if kind is None or str(inifield.locationtype).lower() == "2d":
            return None
        return np.full(n, value)

    @staticmethod
    def _spatial_values_at_nodes(
        inifield: InitialField, filename: str | None, data: dict, nodes: _Mesh1dNodes
    ) -> np.ndarray | None:
        """Values of a spatial field at the nodes, as D-Flow FM applied them (D-HYDRO 2026.02).

        - values per branch (1dField) are interpolated along the branch and kept constant beyond the first
          and last chainage;
        - samples are interpolated linearly in triangles, inside their convex hull (at least 3 samples);
        - polygon files give the value of the field inside the polygons.

        Parameters
        ----------
        inifield : InitialField
            The initial field.
        filename : str | None
            Data file of the field, for messages.
        data : dict
            The data of the field in spatial_data.
        nodes : _Mesh1dNodes
            The 1D nodes.

        Returns
        -------
        np.ndarray | None
            Value per node, NaN where the field gives no value; None for rasters, which are not evaluated.
        """
        values = np.full(len(nodes.x), np.nan)
        if data["filetype"] == "branch":
            for bid, (branch_chainage, branch_values) in data["branches"].items():
                on_branch = nodes.branchid == bid
                values[on_branch] = np.interp(
                    nodes.chainage[on_branch], branch_chainage, branch_values
                )
        elif data["filetype"] == "sample":
            if len(data["x"]) >= 3:
                interpolator = LinearNDInterpolator(
                    np.c_[data["x"], data["y"]], data["z"]
                )
                values = interpolator(np.c_[nodes.x, nodes.y])
        elif data["filetype"] == "polygon":
            if inifield.value is None:
                raise ValueError(f"The polygon field {filename} has no value.")
            inside = gpd.GeoSeries(nodes.points).intersects(
                shapely.union_all(data["polygons"])
            )
            values[inside.to_numpy()] = float(inifield.value)
        else:
            logger.warning(f"Raster field {filename} is not evaluated at the nodes.")
            return None
        return values

    def _nodes_crs(self, crs: CRS | str | None) -> CRS | str:
        """Coordinate reference system for the 1D nodes.

        Parameters
        ----------
        crs : optional
            Requested coordinate reference system, or None.

        Returns
        -------
        crs
            The requested crs, otherwise the crs of the HyDAMO branches, otherwise EPSG:28992 (as written to
            the model by DIMRWriter.add_crs).
        """
        if crs is None and getattr(self.hydamo, "branches", None) is not None:
            crs = self.hydamo.branches.crs
        if crs is None:
            # the projection that DIMRWriter.add_crs writes to the model
            crs = "EPSG:28992"
            logger.info(
                "No coordinate system known for the branches; EPSG:28992 is used for the 1D nodes."
            )
        return crs
boundaries_to_dhydro() -> None

Convert the boundaries to [Boundary] blocks and forcings.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def boundaries_to_dhydro(self) -> None:
    """Convert the boundaries to [Boundary] blocks and forcings."""
    for bound in self.hydamo.external_forcings.boundary_nodes.values():
        bnd_bc: ConstantWithInterpolation | TimeSeries | QHTableWithInterpolation
        if bound["vec1"] is None:
            bnd_bc = ConstantWithInterpolation(
                name=bound["nodeid"],
                function="constant",
                quantity=bound["quantity"],
                unit=bound["unit2"],
                datablock=[[bound["vec2"]]],
            )
        elif bound["unit1"].startswith("minutes"):
            bnd_bc = TimeSeries(
                name=bound["nodeid"],
                function="timeseries",
                timeinterpolation="linear",
                quantityunitpair=[
                    QuantityUnitPair(quantity="time", unit=bound["unit1"]),
                    QuantityUnitPair(
                        quantity=bound["quantity"], unit=bound["unit2"]
                    ),
                ],
                datablock=list(map(list, zip(bound["vec1"], bound["vec2"]))),
            )
        else:
            bnd_bc = QHTableWithInterpolation(
                name=bound["nodeid"],
                function="qhtable",
                quantityunitpair=[
                    QuantityUnitPair(
                        quantity="qhbnd waterlevel", unit=bound["unit2"]
                    ),
                    QuantityUnitPair(
                        quantity="qhbnd discharge", unit=bound["unit1"]
                    ),
                ],
                datablock=list(map(list, zip(bound["vec2"], bound["vec1"]))),
            )

        self.forcingmodel.forcing.append(bnd_bc)
    for bound in self.hydamo.external_forcings.boundary_nodes.values():
        bnd_ext = Boundary(
            nodeid=bound["nodeid"],
            quantity=bound["quantity"],
            forcingfile=self.forcingmodel,
        )
        self.forcingmodel.filepath = Path("boundaryconditions.bc")
        self.boundaries_ext.append(bnd_ext)
bridges_to_dhydro() -> None

Convert the bridges to Bridge objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
407
408
409
410
411
412
413
414
415
def bridges_to_dhydro(self) -> None:
    """Convert the bridges to Bridge objects."""
    structs = [
        Bridge(**struc)
        # into=dict: see compounds_to_dhydro
        for struc in self.hydamo.structures.bridges_df.to_dict("records", into=dict)
    ]
    self._clear_comments(structs)
    self.structures += structs
compounds_to_dhydro() -> None

Convert the compound structures to Compound objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def compounds_to_dhydro(self) -> None:
    """Convert the compound structures to Compound objects."""
    structs = [
        Compound(**struc)
        # into=dict only affects the type mypy sees, not the result:
        # - without it, pandas-stubs gives dict[Hashable, Any], which mypy rejects for **struc;
        # - into=dict[str, Any] would be exact, but pandas raises a TypeError on it;
        # - the bare dict gives dict[Any, Any], which is safe: our column names are always strings.
        for struc in self.hydamo.structures.compounds_df.to_dict(
            "records", into=dict
        )
    ]
    self._clear_comments(structs)
    self.structures += structs
crosssection_definitions_to_dhydro() -> None

Convert the cross section definitions to CrossSectionDefinition objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def crosssection_definitions_to_dhydro(self) -> None:
    """Convert the cross section definitions to CrossSectionDefinition objects."""

    def _get_cstype_part_of_dict(cstype: str) -> dict:
        """Return the cross section definitions of one type."""
        return {
            key: dct
            for key, dct in self.hydamo.crosssections.crosssection_def.items()
            if dct["type"] == cstype
        }

    # Circles
    cs_circle = _get_cstype_part_of_dict("circle")
    circles = [CircleCrsDef(**cs) for cs in cs_circle.values()]
    self._clear_comments(circles)
    self.crossdefs += circles

    # YZ
    cs_yz = _get_cstype_part_of_dict("yz")
    yz_profiles = [YZCrsDef(**cs) for cs in cs_yz.values()]
    self._clear_comments(yz_profiles)
    self.crossdefs += yz_profiles

    # Rectangle
    cs_rect = _get_cstype_part_of_dict("rectangle")
    rectangles = [RectangleCrsDef(**cs) for cs in cs_rect.values()]
    self._clear_comments(rectangles)
    self.crossdefs += rectangles

    # Trapezium
    cs_zw = _get_cstype_part_of_dict("zw")
    zw_profiles = [ZWCrsDef(**cs) for cs in cs_zw.values()]
    self._clear_comments(zw_profiles)
    self.crossdefs += zw_profiles
crosssection_locations_to_dhydro() -> None

Convert the cross section locations to CrossSection objects.

With assign_default_profiles, the default definition is first added to the default locations (or else to the branches without a cross section).

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def crosssection_locations_to_dhydro(self) -> None:
    """Convert the cross section locations to CrossSection objects.

    With ``assign_default_profiles``, the default definition is first added to the
    default locations (or else to the branches without a cross section).
    """
    # Check which of the branches do not have a cross section. Add the default one to those
    branchids = {
        dct["branchid"]
        for dct in self.hydamo.crosssections.crosssection_loc.values()
    }

    # check if there locations specified where a default profile should be added
    default_locs: list[str] | pd.Index
    if hasattr(self.hydamo.crosssections, "default_locations"):
        default_locs = self.hydamo.crosssections.default_locations
    else:
        default_locs = self.hydamo.branches.index[
            ~self.hydamo.branches["code"].isin(branchids)
        ]

    # If any are missing, check if a default cross section definition has been defined
    if (len(default_locs) > 0) & (self.assign_default_profiles):
        default_definition = self.hydamo.crosssections.default_definition
        if default_definition is None:
            logger.warning(
                "Not all branches have a cross section appointed to them. We assume D-Hydro can interpolate over these branches, otherwise errors will occur."
            )
        else:
            logger.info(
                f"Adding default cross section definition to branches with ids: {', '.join(list(default_locs))}"
            )
            half_lengths = self.hydamo.branches.geometry.length / 2
            for branchid in default_locs:
                self.hydamo.crosssections.add_crosssection_location(
                    branchid=branchid,
                    chainage=float(half_lengths.loc[branchid]),
                    definition=default_definition,
                    minz=np.nan,
                    shift=self.hydamo.crosssections.default_definition_shift,
                )

    # Add cross sections to dhydro format
    css = [
        CrossSection(**cloc)
        for cloc in self.hydamo.crosssections.crosssection_loc.values()
    ]

    self._clear_comments(css)
    self.crosslocs += css
culverts_to_dhydro() -> None

Convert the culverts to Culvert objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
417
418
419
420
421
422
423
424
425
426
427
def culverts_to_dhydro(self) -> None:
    """Convert the culverts to Culvert objects."""
    structs = [
        Culvert(**struc)
        # into=dict: see compounds_to_dhydro
        for struc in self.hydamo.structures.culverts_df.to_dict(
            "records", into=dict
        )
    ]
    self._clear_comments(structs)
    self.structures += structs
ext_model() -> ExtModel

Return the external forcings model (bnd.ext) with the boundaries and laterals.

Use as fm.external_forcing.extforcefilenew = models.ext_model(). The file version is set to EXT_FILE_VERSION, as D-HYDRO 2026.02 does not read the default version of hydrolib-core 1.6.

Returns

ExtModel The external forcings model, readable by D-HYDRO.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def ext_model(self) -> ExtModel:
    """Return the external forcings model (bnd.ext) with the boundaries and laterals.

    Use as ``fm.external_forcing.extforcefilenew = models.ext_model()``. The file version
    is set to ``EXT_FILE_VERSION``, as D-HYDRO 2026.02 does not read the default version of
    hydrolib-core 1.6.

    Returns
    -------
    ExtModel
        The external forcings model, readable by D-HYDRO.
    """
    extmodel = ExtModel(boundary=self.boundaries_ext, lateral=self.laterals_ext)
    extmodel.general.fileversion = EXT_FILE_VERSION
    return extmodel
friction_definitions_to_dhydro() -> None

Convert the friction definitions to FrictGlobal objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
625
626
627
628
629
630
631
632
def friction_definitions_to_dhydro(self) -> None:
    """Convert the friction definitions to FrictGlobal objects."""
    frictdefs = [
        FrictGlobal(**frictdef)
        for frictdef in self.hydamo.roughness_definitions.values()
    ]
    self._clear_comments(frictdefs)
    self.friction_defs += frictdefs
inifields_to_dhydro() -> None

Convert uniform initial water levels and depths to InitialField objects with a 1dField data file.

The corresponding OneDFieldGlobal objects are stored in self.onedfieldmodels, in the same order as the 1dField entries in self.inifields. Use write_initial_fields() to write them.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def inifields_to_dhydro(self) -> None:
    """Convert uniform initial water levels and depths to InitialField objects with a 1dField data file.

    The corresponding OneDFieldGlobal objects are stored in self.onedfieldmodels, in the same order as the
    1dField entries in self.inifields. Use write_initial_fields() to write them.
    """
    initial = [
        ("waterlevel", self.hydamo.external_forcings.initial_waterlevel_polygons),
        ("waterdepth", self.hydamo.external_forcings.initial_waterdepth_polygons),
    ]
    for quantity, gdf in initial:
        # uniform 1D values are written per branch by spatial_fields_to_dhydro
        if gdf.empty or (gdf["locationtype"] == "1d").all():
            continue
        if gdf.geometry.notna().any() or len(gdf) > 1:
            raise ValueError(
                f"Initial {quantity} with polygons is not supported by set_initial_{quantity}. "
                "Use hydamo.external_forcings.set_spatial_field() for spatially varying values."
            )
        row = gdf.iloc[0]
        # e.g. initialwaterlevel_2d.ini; the 1D files use the names of the GUI (ONEDFIELD_FILES)
        filename = f"initial{quantity}_{row['locationtype']}.ini"
        inifield = InitialField(
            quantity=quantity,
            datafiletype="1dField",
            datafile=filename,
            locationtype=row["locationtype"],
        )
        onedfield = OneDFieldGlobal(
            quantity=quantity,
            unit="m",
            value=str(row[quantity]),
        )
        self._clear_comments(inifield)
        self._clear_comments(onedfield)
        self.inifields.append(inifield)
        self.onedfieldmodels.append(onedfield)
initial_conditions_at_nodes(network: Network, output_file: Path | str | None = None, crs: CRS | str | None = None) -> gpd.GeoDataFrame

Approximate the initial water level or depth at the 1D computational nodes.

A diagnostic to check the initial conditions, e.g. in a GIS, since the D-HYDRO GUI hardly shows them. It is not computed by D-Flow FM: it reproduces how D-Flow FM applied the initial fields in tests with D-HYDRO 2026.02 (1404 to 1421 of the 1421 nodes of the test model matched the water level at t=0; differences at junctions and structures). Other D-Flow FM versions may behave differently. The fields differences at junctions and structures). Other D-Flow FM versions may behave differently. The fields are applied in their order:

  • values per branch (1dField) are interpolated along the branch and kept constant beyond the first and last chainage; uniform values apply everywhere;
  • samples are interpolated linearly in triangles (inside their convex hull), polygon files apply inside the polygons; rasters are not evaluated;
  • where fields overlap the last one applies, also between water level and water depth;
  • a water depth from polygons or samples removes earlier water levels from polygons or samples;
  • a uniform water depth overrides spatial water levels. Nodes without a value keep the default water level of the MDU (WaterLevIni), shown as missing here.
Parameters

network : Network The network with the 1D mesh, e.g. fm.geometry.netfile.network. output_file : Path or str, optional Shapefile (.shp) or GeoPackage (.gpkg) to write. Defaults to None. crs : optional Coordinate reference system. Defaults to the crs of the HyDAMO branches, or EPSG:28992 (as written to the model by DIMRWriter.add_crs) if they have none.

Returns

gpd.GeoDataFrame One point per node with branchid, chainage, quantity ('waterlevel' or 'waterdepth'), value and source (data file of the field that sets the value).

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def initial_conditions_at_nodes(
    self,
    network: Network,
    output_file: Path | str | None = None,
    crs: CRS | str | None = None,
) -> gpd.GeoDataFrame:
    """Approximate the initial water level or depth at the 1D computational nodes.

    A diagnostic to check the initial conditions, e.g. in a GIS, since the D-HYDRO GUI hardly shows them.
    It is not computed by D-Flow FM: it reproduces how D-Flow FM applied the initial fields in tests with
    D-HYDRO 2026.02 (1404 to 1421 of the 1421 nodes of the test model matched the water level at t=0;
    differences at junctions and structures). Other D-Flow FM versions may behave differently. The fields
    differences at junctions and structures). Other D-Flow FM versions may behave differently. The fields
    are applied in their order:

    - values per branch (1dField) are interpolated along the branch and kept constant beyond the first and
      last chainage; uniform values apply everywhere;
    - samples are interpolated linearly in triangles (inside their convex hull), polygon files apply inside
      the polygons; rasters are not evaluated;
    - where fields overlap the last one applies, also between water level and water depth;
    - a water depth from polygons or samples removes earlier water levels from polygons or samples;
    - a uniform water depth overrides spatial water levels.
    Nodes without a value keep the default water level of the MDU (WaterLevIni), shown as missing here.

    Parameters
    ----------
    network : Network
        The network with the 1D mesh, e.g. ``fm.geometry.netfile.network``.
    output_file : Path or str, optional
        Shapefile (.shp) or GeoPackage (.gpkg) to write. Defaults to None.
    crs : optional
        Coordinate reference system. Defaults to the crs of the HyDAMO branches, or
        EPSG:28992 (as written to the model by ``DIMRWriter.add_crs``) if they have none.

    Returns
    -------
    gpd.GeoDataFrame
        One point per node with branchid, chainage, quantity ('waterlevel' or
        'waterdepth'), value and source (data file of the field that sets the value).
    """
    mesh1d = network._mesh1d
    x, y = (
        np.asarray(mesh1d.mesh1d_node_x, dtype=float),
        np.asarray(mesh1d.mesh1d_node_y, dtype=float),
    )
    branch_names = np.asarray(mesh1d.network1d_branch_id, dtype=object)
    mesh_nodes = _Mesh1dNodes(
        x=x,
        y=y,
        branchid=branch_names[np.asarray(mesh1d.mesh1d_node_branch_id, dtype=int)],
        chainage=np.asarray(mesh1d.mesh1d_node_branch_offset, dtype=float),
        points=gpd.points_from_xy(x, y),
    )
    state = _NodeValues(len(x))
    uniform_depth = None

    uniform_fields = iter(self.onedfieldmodels)
    for inifield in self.inifields:
        field = self._inifield_at_nodes(inifield, uniform_fields, mesh_nodes)
        if field is None:
            continue
        kind, values, filename, filetype = field
        state.apply(kind, values, filename, filetype)
        if filetype == "uniform" and kind == "waterdepth":
            uniform_depth = (values, filename)

    if uniform_depth is not None:
        state.apply_uniform_depth(*uniform_depth)

    nodes = gpd.GeoDataFrame(
        {
            "node_id": np.asarray(mesh1d.mesh1d_node_id, dtype=object),
            "branchid": mesh_nodes.branchid,
            "chainage": mesh_nodes.chainage,
            "quantity": state.quantity,
            "value": state.value,
            "source": state.source,
        },
        geometry=mesh_nodes.points,
        crs=self._nodes_crs(crs),
    )
    if (nodes["quantity"].isna()).any():
        logger.info(
            f"{nodes['quantity'].isna().sum()} 1D nodes get no initial value and keep WaterLevIni."
        )
    if output_file is not None:
        nodes.to_file(output_file)
    return nodes
laterals_to_dhydro() -> None

Convert the laterals to [Lateral] blocks and forcings.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def laterals_to_dhydro(self) -> None:
    """Convert the laterals to [Lateral] blocks and forcings."""
    for key, lateral in self.hydamo.external_forcings.lateral_nodes.items():
        if isinstance(lateral["discharge"], str):
            # realtime boundary
            lat_ext = Lateral(
                id=key,
                locationtype="1d",
                branchid=lateral["branchid"],
                chainage=lateral["chainage"],
                discharge=lateral["discharge"],
            )
        else:
            # time series or constant value
            lat_bc: TimeSeries | ConstantWithInterpolation
            if isinstance(lateral["discharge"], pd.Series):
                lat_bc = TimeSeries(
                    name=key,
                    function="timeseries",
                    timeinterpolation="linear",
                    quantityunitpair=[
                        QuantityUnitPair(
                            quantity="time", unit=lateral["time_unit"]
                        ),
                        QuantityUnitPair(quantity="lateral_discharge", unit="m3/s"),
                    ],
                    datablock=list(
                        map(list, zip(lateral["time"], lateral["value"]))
                    ),
                )
                self.laterals_bc.append(lat_bc)
            else:
                # add_lateral validates the discharge as a pd.Series, float or str
                lat_bc = ConstantWithInterpolation(
                    name=key,
                    function="constant",
                    quantity="lateral_discharge",
                    unit="m3/s",
                    datablock=[[lateral["discharge"]]],
                )
            self.forcingmodel.forcing.append(lat_bc)
            lat_ext = Lateral(
                id=key,
                locationtype=lateral["locationtype"],
                branchid=lateral["branchid"],
                chainage=float(lateral["chainage"]),
                discharge=self.forcingmodel,
            )
        self.laterals_ext.append(lat_ext)
observation_points_to_dhydro() -> None

Convert the observation points to ObservationPoint objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
643
644
645
646
647
648
649
650
651
652
653
654
def observation_points_to_dhydro(self) -> None:
    """Convert the observation points to ObservationPoint objects."""
    if hasattr(self.hydamo.observationpoints, "observation_points"):
        obspoints = [
            ObservationPoint(**obs)
            # into=dict: see compounds_to_dhydro
            for obs in self.hydamo.observationpoints.observation_points.drop(
                columns="geometry"
            ).to_dict("records", into=dict)
        ]
        self._clear_comments(obspoints)
        self.obspoints += obspoints
orifices_to_dhydro() -> None

Convert the orifices to Orifice objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
385
386
387
388
389
390
391
392
393
394
395
def orifices_to_dhydro(self) -> None:
    """Convert the orifices to Orifice objects."""
    structs = [
        Orifice(**struc)
        # into=dict: see compounds_to_dhydro
        for struc in self.hydamo.structures.orifices_df.to_dict(
            "records", into=dict
        )
    ]
    self._clear_comments(structs)
    self.structures += structs
pumps_to_dhydro() -> None

Convert the pumps to Pump objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
429
430
431
432
433
434
435
436
437
def pumps_to_dhydro(self) -> None:
    """Convert the pumps to Pump objects."""
    structs = [
        Pump(**struc)
        # into=dict: see compounds_to_dhydro
        for struc in self.hydamo.structures.pumps_df.to_dict("records", into=dict)
    ]
    self._clear_comments(structs)
    self.structures += structs
regular_weirs_to_dhydro() -> None

Convert the regular weirs to Weir objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
375
376
377
378
379
380
381
382
383
def regular_weirs_to_dhydro(self) -> None:
    """Convert the regular weirs to Weir objects."""
    structs = [
        Weir(**struc)
        # into=dict: see compounds_to_dhydro
        for struc in self.hydamo.structures.rweirs_df.to_dict("records", into=dict)
    ]
    self._clear_comments(structs)
    self.structures += structs
spatial_fields_to_dhydro() -> None

Convert spatial fields (branch values, polygons, rasters or samples) to InitialField/ParameterField objects.

Branch values are derived from the HyDAMO branches. All initial water level and water depth fields per branch (including uniform 1D values) are combined into one 1dField file per quantity (ONEDFIELD_FILES), as the D-HYDRO GUI expects. This gives the same result in D-Flow FM: a field per branch fills whole branches and the last field wins, so per branch the values of the last field are kept, and a branch that a later field gives the other quantity is moved to that quantity. The combined block is placed at the position of the last field of that quantity. Polygon files get one .pol file and one block per distinct value. Only the references are created here; the data files themselves are written by write_spatial_fields().

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def spatial_fields_to_dhydro(self) -> None:
    """Convert spatial fields (branch values, polygons, rasters or samples) to InitialField/ParameterField objects.

    Branch values are derived from the HyDAMO branches. All initial water level and water depth fields per
    branch (including uniform 1D values) are combined into one 1dField file per quantity (ONEDFIELD_FILES), as
    the D-HYDRO GUI expects. This gives the same result in D-Flow FM: a field per branch fills whole branches
    and the last field wins, so per branch the values of the last field are kept, and a branch that a later
    field gives the other quantity is moved to that quantity. The combined block is placed at the position of
    the last field of that quantity. Polygon files get one .pol file and one block per distinct value. Only the
    references are created here; the data files themselves are written by write_spatial_fields().
    """
    # footprints of the initial water level and depth fields, to check where both apply
    level_depth_fields = []
    # initial water level and depth per branch, combined into one 1dField file per quantity
    combined = _CombinedOneDFields()
    # order of the blocks: ("combined", kind) or ("blocks", spatial field, [(filename, datafiletype, value)])
    order: list[tuple] = []
    for sf in self.hydamo.external_forcings.spatial_fields:
        kind = None
        if sf["kind"] == "initial":
            kind = level_or_depth(sf["quantity"])
        if sf["filetype"] == "branch" and kind is not None:
            # combined with the other fields of this quantity, at the position of the last one; see the docstring
            branch_values = self._branch_values(sf)
            combined.add(kind, sf["quantity"], branch_values)
            order = [entry for entry in order if entry != ("combined", kind)] + [
                ("combined", kind)
            ]
            data: dict | None = {"branches": branch_values}
        else:
            order.append(("blocks", sf, self._field_blocks(sf)))
            data = self.spatial_data.get(sf["filename"])
        footprint = self._level_depth_footprint(sf, data)
        if footprint is not None:
            level_depth_fields.append(footprint)

    self._add_fields_in_order(order, combined)
    self._check_level_and_depth(level_depth_fields, self.hydamo.branches)
    self._check_uniform_depth(level_depth_fields)
storagenodes_to_dhydro() -> None

Convert the storage nodes to StorageNode objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
634
635
636
637
638
639
640
641
def storagenodes_to_dhydro(self) -> None:
    """Convert the storage nodes to StorageNode objects."""
    stornodes = [
        StorageNode(**stornode)
        for stornode in self.hydamo.storagenodes.storagenodes.values()
    ]
    self._clear_comments(stornodes)
    self.storagenodes += stornodes
universal_weirs_to_dhydro() -> None

Convert the universal weirs to UniversalWeir objects.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
397
398
399
400
401
402
403
404
405
def universal_weirs_to_dhydro(self) -> None:
    """Convert the universal weirs to UniversalWeir objects."""
    structs = [
        UniversalWeir(**struc)
        # into=dict: see compounds_to_dhydro
        for struc in self.hydamo.structures.uweirs_df.to_dict("records", into=dict)
    ]
    self._clear_comments(structs)
    self.structures += structs
write_all() -> None

Convert all objects; called when the object is created.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def write_all(self) -> None:
    """Convert all objects; called when the object is created."""
    self.regular_weirs_to_dhydro()
    self.orifices_to_dhydro()
    self.universal_weirs_to_dhydro()
    self.bridges_to_dhydro()
    self.culverts_to_dhydro()
    self.pumps_to_dhydro()
    self.compounds_to_dhydro()
    self.crosssection_locations_to_dhydro()
    self.crosssection_definitions_to_dhydro()
    self.friction_definitions_to_dhydro()
    self.boundaries_to_dhydro()
    self.laterals_to_dhydro()
    self.observation_points_to_dhydro()
    self.storagenodes_to_dhydro()
    self.inifields_to_dhydro()
    self.spatial_fields_to_dhydro()
write_initial_fields(fm: FMModel, fm_dir: Path | str) -> IniFieldModel

Add all initial fields and parameter fields to the FM model and write their data files.

This writes the 1dField files (uniform values), rasters and sample files to fm_dir, and links them in initialFields.ini, using paths relative to the fm folder. Call this before saving the FM model. It logs a warning when D-Flow FM would use the uniform bed level (BedlevUni) for the whole 2D mesh, see _warn_missing_bedlevel.

Parameters

fm : FMModel The FM model. fm_dir : Path or str Folder where the FM model (mdu file) is written.

Returns

IniFieldModel The initial fields model, also set as fm.geometry.inifieldfile.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def write_initial_fields(self, fm: FMModel, fm_dir: Path | str) -> IniFieldModel:
    """Add all initial fields and parameter fields to the FM model and write their data files.

    This writes the 1dField files (uniform values), rasters and sample files to fm_dir, and links them
    in initialFields.ini, using paths relative to the fm folder. Call this before saving the FM model.
    It logs a warning when D-Flow FM would use the uniform bed level (BedlevUni) for the whole 2D mesh,
    see _warn_missing_bedlevel.

    Parameters
    ----------
    fm : FMModel
        The FM model.
    fm_dir : Path or str
        Folder where the FM model (mdu file) is written.

    Returns
    -------
    IniFieldModel
        The initial fields model, also set as ``fm.geometry.inifieldfile``.
    """
    fm_dir = Path(fm_dir)
    fm_dir.mkdir(parents=True, exist_ok=True)

    onedfield_inifields = [f for f in self.inifields if f.datafiletype == "1dField"]
    for inifield, onedfield in zip(onedfield_inifields, self.onedfieldmodels):
        if inifield.datafile is None or inifield.datafile.filepath is None:
            raise ValueError(
                f"The 1dField initial field for {inifield.quantity} has no data file."
            )
        onedfieldmodel = OneDFieldModel(global_=onedfield)
        onedfieldmodel.save(filepath=fm_dir / inifield.datafile.filepath.name)

    self.write_spatial_fields(fm_dir)
    self._warn_missing_bedlevel(fm)

    inifieldmodel = IniFieldModel(
        initial=self.inifields, parameter=self.parameterfields
    )
    fm.geometry.inifieldfile = inifieldmodel
    return inifieldmodel
write_spatial_fields(output_dir: Path | str) -> None

Write the data files of the spatial fields (1dField files, polygon files, rasters and samples).

The files are referenced relative to initialFields.ini, so output_dir should be the folder where the FMModel (and its initialFields.ini) is saved.

Parameters

output_dir : Path or str The fm folder of the model.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
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
def write_spatial_fields(self, output_dir: Path | str) -> None:
    """Write the data files of the spatial fields (1dField files, polygon files, rasters and samples).

    The files are referenced relative to initialFields.ini, so output_dir should be the
    folder where the FMModel (and its initialFields.ini) is saved.

    Parameters
    ----------
    output_dir : Path or str
        The fm folder of the model.
    """
    output_dir = Path(output_dir)
    for filename, data in self.spatial_data.items():
        path = output_dir / filename
        path.parent.mkdir(parents=True, exist_ok=True)
        if data["filetype"] == "branch":
            # The D-HYDRO GUI requires a [Global] block. D-Flow FM (2026.02) treats the nodata value as no
            # value, so branches without values keep the value of earlier fields or WaterLevIni.
            quantity = data["quantity"]
            unit = (
                "m"
                if quantity.lower().replace("initial", "")
                in ("waterlevel", "waterdepth")
                else "-"
            )
            OneDFieldModel(
                global_=OneDFieldGlobal(
                    quantity=quantity, unit=unit, value=data["nodata"]
                ),
                branch=[
                    OneDFieldBranch(
                        branchid=str(branch_id),
                        numlocations=len(chainage),
                        chainage=chainage,
                        values=values,
                    )
                    for branch_id, (chainage, values) in data["branches"].items()
                ],
            ).save(filepath=path)
        elif data["filetype"] == "polygon":
            objects = []
            for i, polygon in enumerate(data["polygons"]):
                coords = list(polygon.exterior.coords)
                objects.append(
                    PolyObject(
                        metadata=Metadata(
                            name=f"{path.stem}_{i:04d}",
                            n_rows=len(coords),
                            n_columns=2,
                        ),
                        points=[
                            PolyPoint(x=x, y=y, data=[]) for x, y, *_ in coords
                        ],
                    )
                )
            PolyFile(objects=objects).save(filepath=path)
        elif data["filetype"] == "xyz_file":
            shutil.copyfile(data["path"], path)
        elif data["filetype"] == "raster":
            write_raster(
                path,
                data["array"],
                data["transform"],
                crs=data["crs"],
                nodata=data["nodata"],
            )
        else:
            xyz = XYZModel(
                points=[
                    XYZPoint(x=x, y=y, z=z)
                    for x, y, z in zip(data["x"], data["y"], data["z"])
                ]
            )
            xyz.save(filepath=path)

QHTableWithInterpolation

Bases: QHTable

QH-table [Forcing] block that also writes timeInterpolation (same GUI workaround as ConstantWithInterpolation).

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
132
133
134
135
136
137
class QHTableWithInterpolation(QHTable):
    """QH-table [Forcing] block that also writes timeInterpolation (same GUI workaround as ConstantWithInterpolation)."""

    timeinterpolation: TimeInterpolation = Field(
        TimeInterpolation.linear, alias="timeInterpolation"
    )

level_or_depth(quantity: str) -> str | None

Return the initial water level or depth that a D-Flow FM quantity stands for.

Accepts the old and new names of these quantities, case-insensitively: "initialwaterlevel" and "waterlevel" both give "waterlevel".

Parameters

quantity : str D-Flow FM quantity of an initial or parameter field, e.g. "waterlevel", "InitialWaterDepth" or "bedlevel".

Returns

str or None "waterlevel" or "waterdepth", or None for any other quantity.

Source code in hydrolib/dhydamo/converters/df2hydrolibmodel.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def level_or_depth(quantity: str) -> str | None:
    """Return the initial water level or depth that a D-Flow FM quantity stands for.

    Accepts the old and new names of these quantities, case-insensitively: ``"initialwaterlevel"`` and
    ``"waterlevel"`` both give ``"waterlevel"``.

    Parameters
    ----------
    quantity : str
        D-Flow FM quantity of an initial or parameter field, e.g. ``"waterlevel"``, ``"InitialWaterDepth"`` or
        ``"bedlevel"``.

    Returns
    -------
    str or None
        ``"waterlevel"`` or ``"waterdepth"``, or None for any other quantity.
    """
    kind = quantity.lower().replace("initial", "")
    if kind in {"waterlevel", "waterdepth"}:
        return kind
    return None

hydamo2df

Convert HyDAMO (DAMO) tables to the cross sections, structures, forcings and storage nodes of HyDAMO.

CrossSectionsIO

Add cross sections from DAMO tables.

Parameters

crosssections : CrossSections The cross sections of a HyDAMO object, filled in place.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
class CrossSectionsIO:
    """Add cross sections from DAMO tables.

    Parameters
    ----------
    crosssections : CrossSections
        The cross sections of a HyDAMO object, filled in place.
    """

    def __init__(self, crosssections: CrossSections) -> None:
        self.crosssections = crosssections

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def from_datamodel(
        self, crsdefs: pd.DataFrame | None = None, crslocs: pd.DataFrame | None = None
    ) -> None:
        """Add cross sections from parsed data models (legacy from delft3dfmpy, untested)."""
        if crslocs is not None:
            for _, crsloc in crslocs.iterrows():
                # add location
                self.crosssections.add_crosssection_location(
                    branchid=crsloc["branch_id"],
                    chainage=crsloc["branch_offset"],
                    shift=crsloc["shift"],
                    definition=crsloc["crosssectiondefinitionid"],
                )

        if crsdefs is not None:
            crsdefs = crsdefs.drop_duplicates(subset=["crosssectiondefinitionid"])
            for _, crsdef in crsdefs.iterrows():
                # Set roughness value on default if cross-section has non defined (e.g. culverts)
                if isinstance(crsdef["frictionid"], str):
                    roughtype = crsdef["frictionid"].split("_")[0]
                else:
                    roughtype = "Chezy"

                if isinstance(crsdef["frictionid"], str):
                    roughval = float(crsdef["frictionid"].split("_")[-1])
                else:
                    roughval = 45

                # add definition
                if crsdef["type"] == "circle":
                    self.crosssections.add_circle_definition(
                        diameter=crsdef["diameter"],
                        roughnesstype=roughtype,
                        roughnessvalue=roughval,
                        name=crsdef["crosssectiondefinitionid"],
                    )
                elif crsdef["type"] == "rectangle":
                    self.crosssections.add_rectangle_definition(
                        height=crsdef["height"],
                        width=crsdef["width"],
                        closed=crsdef["closed"],
                        roughnesstype=roughtype,
                        roughnessvalue=roughval,
                        name=crsdef["crosssectiondefinitionid"],
                    )
                elif crsdef["type"] == "trapezium":
                    self.crosssections.add_trapezium_definition(
                        slope=(crsdef["t_width"] - crsdef["width"])
                        / 2
                        / crsdef["height"],
                        maximumflowwidth=crsdef["t_width"],
                        bottomwidth=crsdef["width"],
                        closed=crsdef["closed"],
                        roughnesstype=roughtype,
                        roughnessvalue=roughval,
                        name=crsdef["crosssectiondefinitionid"],
                    )
                elif crsdef["type"] == "zw":
                    self.crosssections.add_zw_definition(
                        numLevels=crsdef["numlevels"],
                        levels=crsdef["levels"],
                        flowWidths=crsdef["flowwidths"],
                        totalWidths=crsdef["totalwidths"],
                        roughnesstype=roughtype,
                        roughnessvalue=roughval,
                        name=crsdef["crosssectiondefinitionid"],
                    )

                else:
                    raise NotImplementedError

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def profiles(
        self,
        branches: ExtendedGeoDataFrame,  # = None,
        roughness_variant: RoughnessVariant,  # =None,
        crosssections: ExtendedGeoDataFrame | None = None,
        crosssection_roughness: ExtendedDataFrame | None = None,
        profile_groups: ExtendedDataFrame | None = None,
        profile_lines: ExtendedGeoDataFrame | None = None,
        param_profile: ExtendedDataFrame | None = None,
        param_profile_values: ExtendedDataFrame | None = None,
    ) -> None:
        """Add the cross sections of the measured and the parametrised profiles.

        Measured profiles (dwarsprofiel, with profile groups and lines) come first; branches
        without one get the parametrised profile (normgeparametriseerd profiel), if any.
        Branches without either have no cross section; give them a default profile, see
        ``CrossSections.set_default_definition``.

        Parameters
        ----------
        branches : ExtendedGeoDataFrame
            The branches.
        roughness_variant : RoughnessVariant
            Use the high or the low roughness value of the profiles.
        crosssections : ExtendedGeoDataFrame, optional
            Measured profile points (profielpunt). Defaults to None.
        crosssection_roughness : ExtendedDataFrame, optional
            Roughness of the measured profiles. Defaults to None.
        profile_groups : ExtendedDataFrame, optional
            Profile groups, required with ``crosssections``. Defaults to None.
        profile_lines : ExtendedGeoDataFrame, optional
            Profile lines, required with ``crosssections``. Defaults to None.
        param_profile : ExtendedDataFrame, optional
            Parametrised profiles. Defaults to None.
        param_profile_values : ExtendedDataFrame, optional
            Values of the parametrised profiles. Defaults to None.
        """
        dp_branches = None
        dp_structures = None
        if crosssections is not None and profile_groups is not None:
            if profile_lines is None:
                raise ValueError("profile_lines is required with profile_groups.")
            profile_group_bridge = DamoRelations.PROFILE_GROUP_BRIDGE
            profile_group_weir = DamoRelations.PROFILE_GROUP_WEIR
            # check for profile_groups items with valid brugid or stuwid. They need to be droppped from profiles.
            structure_group_mask = pd.Series(False, index=profile_groups.index)
            for relation in (profile_group_bridge, profile_group_weir):
                if relation.foreign_key in profile_groups.columns:
                    structure_group_mask |= profile_groups[relation.foreign_key].notna()

            structure_groups = profile_groups.loc[structure_group_mask]
            structure_lines = DamoRelations.PROFILE_LINE_GROUP.children_of(
                structure_groups,
                profile_lines,
            )
            structure_profiles = DamoRelations.PROFILE_LINE.children_of(
                structure_lines,
                crosssections,
            )
            # make a copy and drop the profiles corresponding to a structure
            dp_branches = crosssections.drop(structure_profiles.index, axis=0)

            dp_structures = gpd.GeoDataFrame(structure_profiles, copy=True)
        elif crosssections is not None:
            dp_branches = crosssections.copy(deep=True)

        # Assign cross-sections to branches
        nnocross = len(self.crosssections.get_branches_without_crosssection())
        logger.info(
            f"Before adding the number of branches without cross section is: {nnocross}."
        )

        if dp_branches is not None:
            if crosssection_roughness is None:
                raise ValueError(
                    "crosssection_roughness is required with crosssections."
                )
            # 1. Collect cross sections from 'dwarsprofielen'
            yz_profiles = self.crosssections.crosssection_to_yzprofiles(
                dp_branches,
                crosssection_roughness,
                branches,
                roughness_variant=roughness_variant,
            )

            for name, css in yz_profiles.items():
                # Add definition
                self.crosssections.add_yz_definition(
                    yz=css["yz"],
                    thalweg=css["thalweg"],
                    name=name,
                    roughnesstype=css["typeruwheid"],
                    roughnessvalue=css["ruwheid"],
                )
                # Add location
                self.crosssections.add_crosssection_location(
                    branchid=css["branchid"], chainage=css["chainage"], definition=name
                )

        # Check the number of branches with cross sections
        no_crosssection_id = self.crosssections.get_branches_without_crosssection()
        no_crosssection = [
            b for b in branches.itertuples() if b.code in no_crosssection_id
        ]

        nnocross = len(no_crosssection)
        logger.info(
            f"After adding 'dwarsprofielen' the number of branches without cross section is: {nnocross}."
        )
        if nnocross == 0:
            logger.info("No further branches without a profile.")
        elif param_profile is None:
            logger.info("No parametrised crossections available for branches.")
        else:
            if param_profile_values is None:
                raise ValueError("param_profile_values is required with param_profile.")
            # Derive norm cross sections for norm parametrised
            # Resolved against all branches, so that a link matching several split
            # parts always warns; the branches with a cross section get none.
            param_profiles_converted = self.crosssections.parametrised_to_profiles(
                param_profile,
                param_profile_values,
                list(branches.itertuples()),
                roughness_variant=roughness_variant,
                with_crosssection=set(branches.index).difference(no_crosssection_id),
            )
            # Get branch information
            branchdata = self.crosssections.hydamo.branches.loc[
                list(param_profiles_converted.keys())
            ]
            branchdata["chainage_upper"] = 0.05 * branchdata.length
            branchdata["chainage_lower"] = 0.95 * branchdata.length

            # Add cross sections
            for branchid, css in param_profiles_converted.items():
                chainage_upper = float(branchdata.loc[branchid, "chainage_upper"])
                chainage_lower = float(branchdata.loc[branchid, "chainage_lower"])

                if css["type"] == "rectangle":
                    name = self.crosssections.add_rectangle_definition(
                        height=css["height"],
                        width=css["width"],
                        closed=css["closed"],
                        roughnesstype=css["typeruwheid"],
                        roughnessvalue=css["ruwheid"],
                    )

                if css["type"] == "trapezium":
                    name = self.crosssections.add_trapezium_definition(
                        slope=css["slope"],
                        maximumflowwidth=css["maximumflowwidth"],
                        bottomwidth=css["bottomwidth"],
                        closed=css["closed"],
                        roughnesstype=css["typeruwheid"],
                        roughnessvalue=css["ruwheid"],
                    )

                # Add location
                self.crosssections.add_crosssection_location(
                    branchid=branchid,
                    chainage=chainage_upper,
                    definition=name,
                    shift=css["bottomlevel_upper"],
                )

                self.crosssections.add_crosssection_location(
                    branchid=branchid,
                    chainage=chainage_lower,
                    definition=name,
                    shift=css["bottomlevel_lower"],
                )

        nnocross = len(self.crosssections.get_branches_without_crosssection())
        logger.info(
            f"After adding 'normgeparametriseerd' the number of branches without cross section is: {nnocross}."
        )

        if dp_structures is not None:
            if crosssection_roughness is None:
                raise ValueError(
                    "crosssection_roughness is required with crosssections."
                )
            # 1. Collect cross sections from 'dwarsprofielen'
            yz_profiles = self.crosssections.crosssection_to_yzprofiles(
                dp_structures,
                crosssection_roughness,
                None,
                roughness_variant=roughness_variant,
            )

            for name, css in yz_profiles.items():
                # Add definition
                self.crosssections.add_yz_definition(
                    yz=css["yz"],
                    thalweg=css["thalweg"],
                    name=name,
                    roughnesstype=css["typeruwheid"],
                    roughnessvalue=css["ruwheid"],
                )
from_datamodel(crsdefs: pd.DataFrame | None = None, crslocs: pd.DataFrame | None = None) -> None

Add cross sections from parsed data models (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def from_datamodel(
    self, crsdefs: pd.DataFrame | None = None, crslocs: pd.DataFrame | None = None
) -> None:
    """Add cross sections from parsed data models (legacy from delft3dfmpy, untested)."""
    if crslocs is not None:
        for _, crsloc in crslocs.iterrows():
            # add location
            self.crosssections.add_crosssection_location(
                branchid=crsloc["branch_id"],
                chainage=crsloc["branch_offset"],
                shift=crsloc["shift"],
                definition=crsloc["crosssectiondefinitionid"],
            )

    if crsdefs is not None:
        crsdefs = crsdefs.drop_duplicates(subset=["crosssectiondefinitionid"])
        for _, crsdef in crsdefs.iterrows():
            # Set roughness value on default if cross-section has non defined (e.g. culverts)
            if isinstance(crsdef["frictionid"], str):
                roughtype = crsdef["frictionid"].split("_")[0]
            else:
                roughtype = "Chezy"

            if isinstance(crsdef["frictionid"], str):
                roughval = float(crsdef["frictionid"].split("_")[-1])
            else:
                roughval = 45

            # add definition
            if crsdef["type"] == "circle":
                self.crosssections.add_circle_definition(
                    diameter=crsdef["diameter"],
                    roughnesstype=roughtype,
                    roughnessvalue=roughval,
                    name=crsdef["crosssectiondefinitionid"],
                )
            elif crsdef["type"] == "rectangle":
                self.crosssections.add_rectangle_definition(
                    height=crsdef["height"],
                    width=crsdef["width"],
                    closed=crsdef["closed"],
                    roughnesstype=roughtype,
                    roughnessvalue=roughval,
                    name=crsdef["crosssectiondefinitionid"],
                )
            elif crsdef["type"] == "trapezium":
                self.crosssections.add_trapezium_definition(
                    slope=(crsdef["t_width"] - crsdef["width"])
                    / 2
                    / crsdef["height"],
                    maximumflowwidth=crsdef["t_width"],
                    bottomwidth=crsdef["width"],
                    closed=crsdef["closed"],
                    roughnesstype=roughtype,
                    roughnessvalue=roughval,
                    name=crsdef["crosssectiondefinitionid"],
                )
            elif crsdef["type"] == "zw":
                self.crosssections.add_zw_definition(
                    numLevels=crsdef["numlevels"],
                    levels=crsdef["levels"],
                    flowWidths=crsdef["flowwidths"],
                    totalWidths=crsdef["totalwidths"],
                    roughnesstype=roughtype,
                    roughnessvalue=roughval,
                    name=crsdef["crosssectiondefinitionid"],
                )

            else:
                raise NotImplementedError
profiles(branches: ExtendedGeoDataFrame, roughness_variant: RoughnessVariant, crosssections: ExtendedGeoDataFrame | None = None, crosssection_roughness: ExtendedDataFrame | None = None, profile_groups: ExtendedDataFrame | None = None, profile_lines: ExtendedGeoDataFrame | None = None, param_profile: ExtendedDataFrame | None = None, param_profile_values: ExtendedDataFrame | None = None) -> None

Add the cross sections of the measured and the parametrised profiles.

Measured profiles (dwarsprofiel, with profile groups and lines) come first; branches without one get the parametrised profile (normgeparametriseerd profiel), if any. Branches without either have no cross section; give them a default profile, see CrossSections.set_default_definition.

Parameters

branches : ExtendedGeoDataFrame The branches. roughness_variant : RoughnessVariant Use the high or the low roughness value of the profiles. crosssections : ExtendedGeoDataFrame, optional Measured profile points (profielpunt). Defaults to None. crosssection_roughness : ExtendedDataFrame, optional Roughness of the measured profiles. Defaults to None. profile_groups : ExtendedDataFrame, optional Profile groups, required with crosssections. Defaults to None. profile_lines : ExtendedGeoDataFrame, optional Profile lines, required with crosssections. Defaults to None. param_profile : ExtendedDataFrame, optional Parametrised profiles. Defaults to None. param_profile_values : ExtendedDataFrame, optional Values of the parametrised profiles. Defaults to None.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def profiles(
    self,
    branches: ExtendedGeoDataFrame,  # = None,
    roughness_variant: RoughnessVariant,  # =None,
    crosssections: ExtendedGeoDataFrame | None = None,
    crosssection_roughness: ExtendedDataFrame | None = None,
    profile_groups: ExtendedDataFrame | None = None,
    profile_lines: ExtendedGeoDataFrame | None = None,
    param_profile: ExtendedDataFrame | None = None,
    param_profile_values: ExtendedDataFrame | None = None,
) -> None:
    """Add the cross sections of the measured and the parametrised profiles.

    Measured profiles (dwarsprofiel, with profile groups and lines) come first; branches
    without one get the parametrised profile (normgeparametriseerd profiel), if any.
    Branches without either have no cross section; give them a default profile, see
    ``CrossSections.set_default_definition``.

    Parameters
    ----------
    branches : ExtendedGeoDataFrame
        The branches.
    roughness_variant : RoughnessVariant
        Use the high or the low roughness value of the profiles.
    crosssections : ExtendedGeoDataFrame, optional
        Measured profile points (profielpunt). Defaults to None.
    crosssection_roughness : ExtendedDataFrame, optional
        Roughness of the measured profiles. Defaults to None.
    profile_groups : ExtendedDataFrame, optional
        Profile groups, required with ``crosssections``. Defaults to None.
    profile_lines : ExtendedGeoDataFrame, optional
        Profile lines, required with ``crosssections``. Defaults to None.
    param_profile : ExtendedDataFrame, optional
        Parametrised profiles. Defaults to None.
    param_profile_values : ExtendedDataFrame, optional
        Values of the parametrised profiles. Defaults to None.
    """
    dp_branches = None
    dp_structures = None
    if crosssections is not None and profile_groups is not None:
        if profile_lines is None:
            raise ValueError("profile_lines is required with profile_groups.")
        profile_group_bridge = DamoRelations.PROFILE_GROUP_BRIDGE
        profile_group_weir = DamoRelations.PROFILE_GROUP_WEIR
        # check for profile_groups items with valid brugid or stuwid. They need to be droppped from profiles.
        structure_group_mask = pd.Series(False, index=profile_groups.index)
        for relation in (profile_group_bridge, profile_group_weir):
            if relation.foreign_key in profile_groups.columns:
                structure_group_mask |= profile_groups[relation.foreign_key].notna()

        structure_groups = profile_groups.loc[structure_group_mask]
        structure_lines = DamoRelations.PROFILE_LINE_GROUP.children_of(
            structure_groups,
            profile_lines,
        )
        structure_profiles = DamoRelations.PROFILE_LINE.children_of(
            structure_lines,
            crosssections,
        )
        # make a copy and drop the profiles corresponding to a structure
        dp_branches = crosssections.drop(structure_profiles.index, axis=0)

        dp_structures = gpd.GeoDataFrame(structure_profiles, copy=True)
    elif crosssections is not None:
        dp_branches = crosssections.copy(deep=True)

    # Assign cross-sections to branches
    nnocross = len(self.crosssections.get_branches_without_crosssection())
    logger.info(
        f"Before adding the number of branches without cross section is: {nnocross}."
    )

    if dp_branches is not None:
        if crosssection_roughness is None:
            raise ValueError(
                "crosssection_roughness is required with crosssections."
            )
        # 1. Collect cross sections from 'dwarsprofielen'
        yz_profiles = self.crosssections.crosssection_to_yzprofiles(
            dp_branches,
            crosssection_roughness,
            branches,
            roughness_variant=roughness_variant,
        )

        for name, css in yz_profiles.items():
            # Add definition
            self.crosssections.add_yz_definition(
                yz=css["yz"],
                thalweg=css["thalweg"],
                name=name,
                roughnesstype=css["typeruwheid"],
                roughnessvalue=css["ruwheid"],
            )
            # Add location
            self.crosssections.add_crosssection_location(
                branchid=css["branchid"], chainage=css["chainage"], definition=name
            )

    # Check the number of branches with cross sections
    no_crosssection_id = self.crosssections.get_branches_without_crosssection()
    no_crosssection = [
        b for b in branches.itertuples() if b.code in no_crosssection_id
    ]

    nnocross = len(no_crosssection)
    logger.info(
        f"After adding 'dwarsprofielen' the number of branches without cross section is: {nnocross}."
    )
    if nnocross == 0:
        logger.info("No further branches without a profile.")
    elif param_profile is None:
        logger.info("No parametrised crossections available for branches.")
    else:
        if param_profile_values is None:
            raise ValueError("param_profile_values is required with param_profile.")
        # Derive norm cross sections for norm parametrised
        # Resolved against all branches, so that a link matching several split
        # parts always warns; the branches with a cross section get none.
        param_profiles_converted = self.crosssections.parametrised_to_profiles(
            param_profile,
            param_profile_values,
            list(branches.itertuples()),
            roughness_variant=roughness_variant,
            with_crosssection=set(branches.index).difference(no_crosssection_id),
        )
        # Get branch information
        branchdata = self.crosssections.hydamo.branches.loc[
            list(param_profiles_converted.keys())
        ]
        branchdata["chainage_upper"] = 0.05 * branchdata.length
        branchdata["chainage_lower"] = 0.95 * branchdata.length

        # Add cross sections
        for branchid, css in param_profiles_converted.items():
            chainage_upper = float(branchdata.loc[branchid, "chainage_upper"])
            chainage_lower = float(branchdata.loc[branchid, "chainage_lower"])

            if css["type"] == "rectangle":
                name = self.crosssections.add_rectangle_definition(
                    height=css["height"],
                    width=css["width"],
                    closed=css["closed"],
                    roughnesstype=css["typeruwheid"],
                    roughnessvalue=css["ruwheid"],
                )

            if css["type"] == "trapezium":
                name = self.crosssections.add_trapezium_definition(
                    slope=css["slope"],
                    maximumflowwidth=css["maximumflowwidth"],
                    bottomwidth=css["bottomwidth"],
                    closed=css["closed"],
                    roughnesstype=css["typeruwheid"],
                    roughnessvalue=css["ruwheid"],
                )

            # Add location
            self.crosssections.add_crosssection_location(
                branchid=branchid,
                chainage=chainage_upper,
                definition=name,
                shift=css["bottomlevel_upper"],
            )

            self.crosssections.add_crosssection_location(
                branchid=branchid,
                chainage=chainage_lower,
                definition=name,
                shift=css["bottomlevel_lower"],
            )

    nnocross = len(self.crosssections.get_branches_without_crosssection())
    logger.info(
        f"After adding 'normgeparametriseerd' the number of branches without cross section is: {nnocross}."
    )

    if dp_structures is not None:
        if crosssection_roughness is None:
            raise ValueError(
                "crosssection_roughness is required with crosssections."
            )
        # 1. Collect cross sections from 'dwarsprofielen'
        yz_profiles = self.crosssections.crosssection_to_yzprofiles(
            dp_structures,
            crosssection_roughness,
            None,
            roughness_variant=roughness_variant,
        )

        for name, css in yz_profiles.items():
            # Add definition
            self.crosssections.add_yz_definition(
                yz=css["yz"],
                thalweg=css["thalweg"],
                name=name,
                roughnesstype=css["typeruwheid"],
                roughnessvalue=css["ruwheid"],
            )

ExternalForcingsIO

Add boundary conditions and laterals from DAMO tables.

Parameters

external_forcings : ExternalForcings The external forcings of a HyDAMO object, filled in place.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
class ExternalForcingsIO:
    """Add boundary conditions and laterals from DAMO tables.

    Parameters
    ----------
    external_forcings : ExternalForcings
        The external forcings of a HyDAMO object, filled in place.
    """

    def __init__(self, external_forcings: ExternalForcings) -> None:
        self.external_forcings = external_forcings

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def boundaries(
        self, boundary_conditions: ExtendedGeoDataFrame, mesh1d: Network | None = None
    ) -> None:
        """Add constant boundary conditions from the DAMO table randvoorwaarden.

        ``typerandvoorwaarde`` decides the kind: a water level, read from
        ``waterstand``, or a discharge, read from ``debiet``. The table has no time
        series, so a variable or tidal boundary gets its value as a constant, which is
        logged; to add a time series, use ``ExternalForcings.add_boundary_condition``.
        A Q-h relation can't be held by the table either: it is skipped with a
        warning, to be added with ``add_boundary_condition``.

        Parameters
        ----------
        boundary_conditions : ExtendedGeoDataFrame
            Locations and properties of the boundary conditions: ``code``,
            ``typerandvoorwaarde``, ``waterstand`` and ``debiet``. A missing
            ``waterstand`` or ``debiet`` column counts as empty.
        mesh1d : Network, optional
            Network with the 1D mesh, to find the node of each boundary. Defaults to None.

        Raises
        ------
        ValueError
            If a boundary has no or an unknown ``typerandvoorwaarde``, or its value
            is empty. The message names every such boundary by ``code``; none is
            added then.
        """
        empty = pd.Series(None, index=boundary_conditions.index, dtype=object)
        boundary_columns = zip(
            boundary_conditions["code"],
            boundary_conditions["typerandvoorwaarde"],
            boundary_conditions.get("waterstand", empty),
            boundary_conditions.get("debiet", empty),
            boundary_conditions.geometry,
        )
        boundaries = []
        problems = []
        for code, kind, waterstand, debiet, geometry in boundary_columns:
            try:
                read = _read_boundary(code, kind, waterstand, debiet)
            except ValueError as exc:
                problems.append(str(exc))
                continue
            if read is not None:
                boundaries.append((code, geometry, *read))
        if problems:
            raise ValueError(
                f"Cannot convert {len(problems)} boundary condition(s): "
                + "; ".join(problems)
            )

        for code, geometry, quantity, value in boundaries:
            # The boundary_conditions table has Point geometries (data model).
            self.external_forcings.add_boundary_condition(
                code, cast("Point", geometry), quantity, value, mesh1d=mesh1d
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def laterals(
        self,
        locations: ExtendedGeoDataFrame,
        overflows: ExtendedGeoDataFrame | None = None,
        greenhouse_laterals: ExtendedGeoDataFrame | None = None,
        lateral_discharges: pd.DataFrame | pd.Series | None = None,
        rr_boundaries: dict | None = None,
    ) -> None:
        """Add the laterals, with a discharge or coupled to RR.

        Laterals in ``rr_boundaries`` get their discharge from the RR model (``realtime``);
        the others from ``lateral_discharges``. Laterals without either are logged and left
        out.

        Parameters
        ----------
        locations : ExtendedGeoDataFrame
            Lateral points, with the columns ``code``, ``branch_id`` and ``branch_offset``.
        overflows : ExtendedGeoDataFrame, optional
            Overflows, added as laterals as well. Defaults to None.
        greenhouse_laterals : ExtendedGeoDataFrame, optional
            Greenhouse outlets, added as laterals as well. Defaults to None.
        lateral_discharges : pd.DataFrame or pd.Series, optional
            A time series per lateral (columns by code, a time index), or a constant
            discharge per lateral (index by code). Defaults to None.
        rr_boundaries : dict, optional
            Codes of the laterals that are coupled to RR boundary nodes. Defaults to None.
        """
        if rr_boundaries is None:
            rr_boundaries = {}

        locations.geometry = locations.geometry.force_2d()

        latdct: dict = {}
        all_locations: pd.DataFrame = locations
        if overflows is not None:
            all_locations = pd.concat([all_locations, overflows], ignore_index=True)
        if greenhouse_laterals is not None:
            all_locations = pd.concat(
                [all_locations, greenhouse_laterals], ignore_index=True
            )

        # Get time series and add to dictionary
        # for nidx, lateral in zip(nearest_idx, locations.itertuples()):
        lateral_columns = zip(
            all_locations["code"],
            all_locations["branch_id"],
            all_locations["branch_offset"],
        )
        for code, branch_id, branch_offset in lateral_columns:
            # Check if a time is provided for the lateral
            if code in rr_boundaries:
                # Add to dictionary
                latdct[code] = {
                    "branchid": branch_id,
                    "chainage": str(branch_offset),
                    "discharge": "realtime",
                }

            else:
                if lateral_discharges is None:
                    logger.warning(
                        "No lateral_discharges provided. %s expects them. Skipping.",
                        code,
                    )
                else:
                    if isinstance(lateral_discharges, pd.Series):
                        series = lateral_discharges.loc[code]

                        # Add to dictionary
                        latdct[code] = {
                            "branchid": branch_id,
                            "chainage": str(branch_offset),
                            "discharge": series,
                        }

                    else:
                        if code not in lateral_discharges.columns:
                            logger.warning(
                                "No data found for %s. Skipping.",
                                code,
                            )
                            continue

                        # Get timeseries
                        series = lateral_discharges.loc[:, code]

                        # Add to dictionary
                        latdct[code] = {
                            "branchid": branch_id,
                            "chainage": str(branch_offset),
                            "discharge": series,
                        }

        # Add all items
        for key, item in latdct.items():
            self.external_forcings.add_lateral(
                id=key,
                branchid=item["branchid"],
                chainage=item["chainage"],
                discharge=item["discharge"],
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def timeseries_from_other_model(
        self,
        his_file: Path | str,
        location_type: str,
        location_id: str,
        variable: str,
        starttime: str | datetime | None = None,
        endtime: str | datetime | None = None,
    ) -> tuple[Point | None, pd.Series]:
        """Read a time series at a location from the his file of another model.

        Parameters
        ----------
        his_file : Path or str
            The his file (``*_his.nc``) of the other model.
        location_type : str
            Type of location: ``"weir"``, ``"observation_point"``, ``"pump"``, ``"uweir"``,
            ``"bridge"``, ``"culvert"`` or ``"compound"``.
        location_id : str
            Id of the location in the his file.
        variable : str
            ``"discharge"``, ``"waterlevel"``, ``"waterlevel_upstream"`` or
            ``"waterlevel_downstream"``.
        starttime, endtime : str or datetime, optional
            Period of the output. Default to None: the whole period.

        Returns
        -------
        tuple[Point or None, pd.Series]
            The location (if the file has its coordinates) and the time series.

        Raises
        ------
        ValueError
            If the file has no data for the location and variable.
        """
        # if timesteps are strings, convert them to datetime objects
        if starttime is not None:
            if isinstance(starttime, str):
                starttime = pd.to_datetime(starttime)
            if isinstance(endtime, str):
                endtime = pd.to_datetime(endtime)
        # read the contents of the his file
        his = Dataset(his_file, "r")

        his_time = his.variables["time"][:]
        time_unit = his["time"].units.split(" ")
        refdate = pd.to_datetime(time_unit[2] + " " + time_unit[3])
        interval_seconds = his_time[1] - his_time[0]
        times = pd.date_range(
            start=refdate,
            end=refdate + pd.Timedelta(hours=np.max(his_time) / 3600.0),
            freq=f"{interval_seconds}S",
        )

        if location_type == "weir":
            dtype = "weirgen"
            loc_ids = chartostring(his[f"{dtype}_name"][:])
            coord_string_x = "weir_input_geom_node_coordx"
            coord_string_y = "weir_input_geom_node_coordy"

        elif location_type == "observation_point":
            dtype = "station"
            loc_ids = chartostring(his[f"{dtype}_name"][:])
            coord_string_x = "station_x_coordinate"
            coord_string_y = "station_y_coordinate"
        elif location_type == "pump":
            coord_string_x = f"{location_type}_input_geom_node_coordx"
            coord_string_y = f"{location_type}_input_geom_node_coordy"
            loc_ids = chartostring(his[f"{location_type}_name"][:])
            if variable == "discharge":
                dtype = "pump_structure"
            else:
                dtype = location_type
        elif location_type == "uweir":
            dtype = "uniweir"
            loc_ids = chartostring(his[f"{dtype}_name"][:])
            coord_string_x = f"{dtype}_input_geom_node_coordx"
            coord_string_y = f"{dtype}_input_geom_node_coordy"
        elif location_type == "compound":
            dtype = "cmpstru"
            loc_ids = chartostring(his[f"{dtype}_name"][:])
        else:
            dtype = location_type
            loc_ids = chartostring(his[f"{dtype}_name"][:])
            coord_string_x = f"{dtype}_input_geom_node_coordx"
            coord_string_y = f"{dtype}_input_geom_node_coordy"
        try:
            loc_index = np.nonzero(loc_ids == location_id)[0][0]
        except IndexError as err:
            raise ValueError(
                f"Location ID {location_id} of type {location_type} not found in {his_file}. Available IDs: {loc_ids}"
            ) from err

        if variable == "waterlevel_upstream":
            variable = "s1up"
        elif variable == "waterlevel_downstream":
            variable = "s1dn"
        if dtype != "cmpstru":
            loc_x = his[coord_string_x][:][loc_index]
            loc_y = his[coord_string_y][:][loc_index]

            loc_geom = Point(loc_x, loc_y)
        else:
            logger.warning(
                "Geometry for compound structures not supported yet. Get the location of one of its structures."
            )
            loc_geom = None

        if location_type == "observation_point":
            timeseries = his["waterlevel"][:, loc_index]
        else:
            timeseries = his[f"{dtype}_{variable}"][:, loc_index]
        loc_series = pd.Series(timeseries, index=times, name=location_id)
        if starttime is not None:
            loc_series = loc_series.loc[starttime:endtime]
            if loc_series.empty:
                logger.error(
                    f"No data available for {location_id} between {starttime} and {endtime}."
                )
        return loc_geom, loc_series
boundaries(boundary_conditions: ExtendedGeoDataFrame, mesh1d: Network | None = None) -> None

Add constant boundary conditions from the DAMO table randvoorwaarden.

typerandvoorwaarde decides the kind: a water level, read from waterstand, or a discharge, read from debiet. The table has no time series, so a variable or tidal boundary gets its value as a constant, which is logged; to add a time series, use ExternalForcings.add_boundary_condition. A Q-h relation can't be held by the table either: it is skipped with a warning, to be added with add_boundary_condition.

Parameters

boundary_conditions : ExtendedGeoDataFrame Locations and properties of the boundary conditions: code, typerandvoorwaarde, waterstand and debiet. A missing waterstand or debiet column counts as empty. mesh1d : Network, optional Network with the 1D mesh, to find the node of each boundary. Defaults to None.

Raises

ValueError If a boundary has no or an unknown typerandvoorwaarde, or its value is empty. The message names every such boundary by code; none is added then.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def boundaries(
    self, boundary_conditions: ExtendedGeoDataFrame, mesh1d: Network | None = None
) -> None:
    """Add constant boundary conditions from the DAMO table randvoorwaarden.

    ``typerandvoorwaarde`` decides the kind: a water level, read from
    ``waterstand``, or a discharge, read from ``debiet``. The table has no time
    series, so a variable or tidal boundary gets its value as a constant, which is
    logged; to add a time series, use ``ExternalForcings.add_boundary_condition``.
    A Q-h relation can't be held by the table either: it is skipped with a
    warning, to be added with ``add_boundary_condition``.

    Parameters
    ----------
    boundary_conditions : ExtendedGeoDataFrame
        Locations and properties of the boundary conditions: ``code``,
        ``typerandvoorwaarde``, ``waterstand`` and ``debiet``. A missing
        ``waterstand`` or ``debiet`` column counts as empty.
    mesh1d : Network, optional
        Network with the 1D mesh, to find the node of each boundary. Defaults to None.

    Raises
    ------
    ValueError
        If a boundary has no or an unknown ``typerandvoorwaarde``, or its value
        is empty. The message names every such boundary by ``code``; none is
        added then.
    """
    empty = pd.Series(None, index=boundary_conditions.index, dtype=object)
    boundary_columns = zip(
        boundary_conditions["code"],
        boundary_conditions["typerandvoorwaarde"],
        boundary_conditions.get("waterstand", empty),
        boundary_conditions.get("debiet", empty),
        boundary_conditions.geometry,
    )
    boundaries = []
    problems = []
    for code, kind, waterstand, debiet, geometry in boundary_columns:
        try:
            read = _read_boundary(code, kind, waterstand, debiet)
        except ValueError as exc:
            problems.append(str(exc))
            continue
        if read is not None:
            boundaries.append((code, geometry, *read))
    if problems:
        raise ValueError(
            f"Cannot convert {len(problems)} boundary condition(s): "
            + "; ".join(problems)
        )

    for code, geometry, quantity, value in boundaries:
        # The boundary_conditions table has Point geometries (data model).
        self.external_forcings.add_boundary_condition(
            code, cast("Point", geometry), quantity, value, mesh1d=mesh1d
        )
laterals(locations: ExtendedGeoDataFrame, overflows: ExtendedGeoDataFrame | None = None, greenhouse_laterals: ExtendedGeoDataFrame | None = None, lateral_discharges: pd.DataFrame | pd.Series | None = None, rr_boundaries: dict | None = None) -> None

Add the laterals, with a discharge or coupled to RR.

Laterals in rr_boundaries get their discharge from the RR model (realtime); the others from lateral_discharges. Laterals without either are logged and left out.

Parameters

locations : ExtendedGeoDataFrame Lateral points, with the columns code, branch_id and branch_offset. overflows : ExtendedGeoDataFrame, optional Overflows, added as laterals as well. Defaults to None. greenhouse_laterals : ExtendedGeoDataFrame, optional Greenhouse outlets, added as laterals as well. Defaults to None. lateral_discharges : pd.DataFrame or pd.Series, optional A time series per lateral (columns by code, a time index), or a constant discharge per lateral (index by code). Defaults to None. rr_boundaries : dict, optional Codes of the laterals that are coupled to RR boundary nodes. Defaults to None.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def laterals(
    self,
    locations: ExtendedGeoDataFrame,
    overflows: ExtendedGeoDataFrame | None = None,
    greenhouse_laterals: ExtendedGeoDataFrame | None = None,
    lateral_discharges: pd.DataFrame | pd.Series | None = None,
    rr_boundaries: dict | None = None,
) -> None:
    """Add the laterals, with a discharge or coupled to RR.

    Laterals in ``rr_boundaries`` get their discharge from the RR model (``realtime``);
    the others from ``lateral_discharges``. Laterals without either are logged and left
    out.

    Parameters
    ----------
    locations : ExtendedGeoDataFrame
        Lateral points, with the columns ``code``, ``branch_id`` and ``branch_offset``.
    overflows : ExtendedGeoDataFrame, optional
        Overflows, added as laterals as well. Defaults to None.
    greenhouse_laterals : ExtendedGeoDataFrame, optional
        Greenhouse outlets, added as laterals as well. Defaults to None.
    lateral_discharges : pd.DataFrame or pd.Series, optional
        A time series per lateral (columns by code, a time index), or a constant
        discharge per lateral (index by code). Defaults to None.
    rr_boundaries : dict, optional
        Codes of the laterals that are coupled to RR boundary nodes. Defaults to None.
    """
    if rr_boundaries is None:
        rr_boundaries = {}

    locations.geometry = locations.geometry.force_2d()

    latdct: dict = {}
    all_locations: pd.DataFrame = locations
    if overflows is not None:
        all_locations = pd.concat([all_locations, overflows], ignore_index=True)
    if greenhouse_laterals is not None:
        all_locations = pd.concat(
            [all_locations, greenhouse_laterals], ignore_index=True
        )

    # Get time series and add to dictionary
    # for nidx, lateral in zip(nearest_idx, locations.itertuples()):
    lateral_columns = zip(
        all_locations["code"],
        all_locations["branch_id"],
        all_locations["branch_offset"],
    )
    for code, branch_id, branch_offset in lateral_columns:
        # Check if a time is provided for the lateral
        if code in rr_boundaries:
            # Add to dictionary
            latdct[code] = {
                "branchid": branch_id,
                "chainage": str(branch_offset),
                "discharge": "realtime",
            }

        else:
            if lateral_discharges is None:
                logger.warning(
                    "No lateral_discharges provided. %s expects them. Skipping.",
                    code,
                )
            else:
                if isinstance(lateral_discharges, pd.Series):
                    series = lateral_discharges.loc[code]

                    # Add to dictionary
                    latdct[code] = {
                        "branchid": branch_id,
                        "chainage": str(branch_offset),
                        "discharge": series,
                    }

                else:
                    if code not in lateral_discharges.columns:
                        logger.warning(
                            "No data found for %s. Skipping.",
                            code,
                        )
                        continue

                    # Get timeseries
                    series = lateral_discharges.loc[:, code]

                    # Add to dictionary
                    latdct[code] = {
                        "branchid": branch_id,
                        "chainage": str(branch_offset),
                        "discharge": series,
                    }

    # Add all items
    for key, item in latdct.items():
        self.external_forcings.add_lateral(
            id=key,
            branchid=item["branchid"],
            chainage=item["chainage"],
            discharge=item["discharge"],
        )
timeseries_from_other_model(his_file: Path | str, location_type: str, location_id: str, variable: str, starttime: str | datetime | None = None, endtime: str | datetime | None = None) -> tuple[Point | None, pd.Series]

Read a time series at a location from the his file of another model.

Parameters

his_file : Path or str The his file (*_his.nc) of the other model. location_type : str Type of location: "weir", "observation_point", "pump", "uweir", "bridge", "culvert" or "compound". location_id : str Id of the location in the his file. variable : str "discharge", "waterlevel", "waterlevel_upstream" or "waterlevel_downstream". starttime, endtime : str or datetime, optional Period of the output. Default to None: the whole period.

Returns

tuple[Point or None, pd.Series] The location (if the file has its coordinates) and the time series.

Raises

ValueError If the file has no data for the location and variable.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def timeseries_from_other_model(
    self,
    his_file: Path | str,
    location_type: str,
    location_id: str,
    variable: str,
    starttime: str | datetime | None = None,
    endtime: str | datetime | None = None,
) -> tuple[Point | None, pd.Series]:
    """Read a time series at a location from the his file of another model.

    Parameters
    ----------
    his_file : Path or str
        The his file (``*_his.nc``) of the other model.
    location_type : str
        Type of location: ``"weir"``, ``"observation_point"``, ``"pump"``, ``"uweir"``,
        ``"bridge"``, ``"culvert"`` or ``"compound"``.
    location_id : str
        Id of the location in the his file.
    variable : str
        ``"discharge"``, ``"waterlevel"``, ``"waterlevel_upstream"`` or
        ``"waterlevel_downstream"``.
    starttime, endtime : str or datetime, optional
        Period of the output. Default to None: the whole period.

    Returns
    -------
    tuple[Point or None, pd.Series]
        The location (if the file has its coordinates) and the time series.

    Raises
    ------
    ValueError
        If the file has no data for the location and variable.
    """
    # if timesteps are strings, convert them to datetime objects
    if starttime is not None:
        if isinstance(starttime, str):
            starttime = pd.to_datetime(starttime)
        if isinstance(endtime, str):
            endtime = pd.to_datetime(endtime)
    # read the contents of the his file
    his = Dataset(his_file, "r")

    his_time = his.variables["time"][:]
    time_unit = his["time"].units.split(" ")
    refdate = pd.to_datetime(time_unit[2] + " " + time_unit[3])
    interval_seconds = his_time[1] - his_time[0]
    times = pd.date_range(
        start=refdate,
        end=refdate + pd.Timedelta(hours=np.max(his_time) / 3600.0),
        freq=f"{interval_seconds}S",
    )

    if location_type == "weir":
        dtype = "weirgen"
        loc_ids = chartostring(his[f"{dtype}_name"][:])
        coord_string_x = "weir_input_geom_node_coordx"
        coord_string_y = "weir_input_geom_node_coordy"

    elif location_type == "observation_point":
        dtype = "station"
        loc_ids = chartostring(his[f"{dtype}_name"][:])
        coord_string_x = "station_x_coordinate"
        coord_string_y = "station_y_coordinate"
    elif location_type == "pump":
        coord_string_x = f"{location_type}_input_geom_node_coordx"
        coord_string_y = f"{location_type}_input_geom_node_coordy"
        loc_ids = chartostring(his[f"{location_type}_name"][:])
        if variable == "discharge":
            dtype = "pump_structure"
        else:
            dtype = location_type
    elif location_type == "uweir":
        dtype = "uniweir"
        loc_ids = chartostring(his[f"{dtype}_name"][:])
        coord_string_x = f"{dtype}_input_geom_node_coordx"
        coord_string_y = f"{dtype}_input_geom_node_coordy"
    elif location_type == "compound":
        dtype = "cmpstru"
        loc_ids = chartostring(his[f"{dtype}_name"][:])
    else:
        dtype = location_type
        loc_ids = chartostring(his[f"{dtype}_name"][:])
        coord_string_x = f"{dtype}_input_geom_node_coordx"
        coord_string_y = f"{dtype}_input_geom_node_coordy"
    try:
        loc_index = np.nonzero(loc_ids == location_id)[0][0]
    except IndexError as err:
        raise ValueError(
            f"Location ID {location_id} of type {location_type} not found in {his_file}. Available IDs: {loc_ids}"
        ) from err

    if variable == "waterlevel_upstream":
        variable = "s1up"
    elif variable == "waterlevel_downstream":
        variable = "s1dn"
    if dtype != "cmpstru":
        loc_x = his[coord_string_x][:][loc_index]
        loc_y = his[coord_string_y][:][loc_index]

        loc_geom = Point(loc_x, loc_y)
    else:
        logger.warning(
            "Geometry for compound structures not supported yet. Get the location of one of its structures."
        )
        loc_geom = None

    if location_type == "observation_point":
        timeseries = his["waterlevel"][:, loc_index]
    else:
        timeseries = his[f"{dtype}_{variable}"][:, loc_index]
    loc_series = pd.Series(timeseries, index=times, name=location_id)
    if starttime is not None:
        loc_series = loc_series.loc[starttime:endtime]
        if loc_series.empty:
            logger.error(
                f"No data available for {location_id} between {starttime} and {endtime}."
            )
    return loc_geom, loc_series

RoughnessVariant

Bases: Enum

Which roughness value of a DAMO profile to use: the high or the low value.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
34
35
36
37
38
class RoughnessVariant(Enum):
    """Which roughness value of a DAMO profile to use: the high or the low value."""

    HIGH = "High"
    LOW = "Low"

StorageNodesIO

Add storage nodes from tables.

Parameters

storagenodes : StorageNodes The storage nodes of a HyDAMO object, filled in place.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
class StorageNodesIO:
    """Add storage nodes from tables.

    Parameters
    ----------
    storagenodes : StorageNodes
        The storage nodes of a HyDAMO object, filled in place.
    """

    def __init__(self, storagenodes: StorageNodes) -> None:
        self.storagenodes = storagenodes

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    def storagenodes_from_datamodel(self, storagenodes):
        """Add storage nodes from a parsed data model (legacy from delft3dfmpy, untested)."""
        for storagenode_idx, storagenode in storagenodes.iterrows():
            self.add_storagenode(
                id=storagenode.id,
                name=storagenode.name if "name" in storagenode.index else np.nan,
                usestreetstorage=storagenode.usestreetstorage,
                nodetype="unspecified",
                nodeid=storagenode.nodeid,
                usetable="false",
                bedlevel=storagenode.bedlevel,
                area=storagenode.area,
                streetlevel=storagenode.streetlevel,
                streetstoragearea=storagenode.streetstoragearea,
                storagetype=storagenode.storagetype,
            )

    def storagenodes_from_input(
        self,
        storagenodes: gpd.GeoDataFrame | None = None,
        nodeid: str | None = None,
        xy: tuple[float, float] | None = None,
        storagedata: pd.DataFrame | None = None,
        usestreetstorage: bool = True,
        network: Network | None = None,
    ) -> None:
        """Add storage nodes with a level-area table.

        Parameters
        ----------
        storagenodes : gpd.GeoDataFrame
            Storage nodes, indexed by code, with ``branch_id`` and ``branch_offset``. Required.
        nodeid : str, optional
            Node id for all storage nodes. Defaults to None: the node at the chainage.
        xy : tuple[float, float], optional
            Location for all storage nodes. Defaults to None.
        storagedata : pd.DataFrame
            Level-area table, with the columns ``code``, ``level`` and ``area``. Required.
        usestreetstorage : bool, optional
            D-Flow FM keyword ``useStreetStorage``. Defaults to True.
        network : Network, optional
            Network with the 1D mesh, to find the node at the chainage. Defaults to None.

        Raises
        ------
        ValueError
            If ``storagenodes`` or ``storagedata`` is missing.
        """
        if storagenodes is None or storagedata is None:
            raise ValueError("Provide storagenodes and storagedata.")

        for storagenode_idx, storagenode in storagenodes.iterrows():
            data = storagedata[storagedata.code == storagenode_idx]
            # the index label of the row, or the code when that is missing
            name = storagenode.name
            if name is None or (isinstance(name, float) and np.isnan(name)):
                name = storagenode.code
            self.storagenodes.add_storagenode(
                id=str(storagenode_idx),
                name=str(name),
                usestreetstorage=usestreetstorage,
                nodetype="unspecified",
                nodeid=nodeid,
                xy=xy,
                branchid=storagenode.branch_id,
                chainage=storagenode.branch_offset,
                usetable="true",
                storagearea=" ".join(data.area.astype(str)),
                levels=" ".join(data.level.astype(str)),
                network=network,
            )
storagenodes_from_datamodel(storagenodes)

Add storage nodes from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
@no_type_check
def storagenodes_from_datamodel(self, storagenodes):
    """Add storage nodes from a parsed data model (legacy from delft3dfmpy, untested)."""
    for storagenode_idx, storagenode in storagenodes.iterrows():
        self.add_storagenode(
            id=storagenode.id,
            name=storagenode.name if "name" in storagenode.index else np.nan,
            usestreetstorage=storagenode.usestreetstorage,
            nodetype="unspecified",
            nodeid=storagenode.nodeid,
            usetable="false",
            bedlevel=storagenode.bedlevel,
            area=storagenode.area,
            streetlevel=storagenode.streetlevel,
            streetstoragearea=storagenode.streetstoragearea,
            storagetype=storagenode.storagetype,
        )
storagenodes_from_input(storagenodes: gpd.GeoDataFrame | None = None, nodeid: str | None = None, xy: tuple[float, float] | None = None, storagedata: pd.DataFrame | None = None, usestreetstorage: bool = True, network: Network | None = None) -> None

Add storage nodes with a level-area table.

Parameters

storagenodes : gpd.GeoDataFrame Storage nodes, indexed by code, with branch_id and branch_offset. Required. nodeid : str, optional Node id for all storage nodes. Defaults to None: the node at the chainage. xy : tuple[float, float], optional Location for all storage nodes. Defaults to None. storagedata : pd.DataFrame Level-area table, with the columns code, level and area. Required. usestreetstorage : bool, optional D-Flow FM keyword useStreetStorage. Defaults to True. network : Network, optional Network with the 1D mesh, to find the node at the chainage. Defaults to None.

Raises

ValueError If storagenodes or storagedata is missing.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
def storagenodes_from_input(
    self,
    storagenodes: gpd.GeoDataFrame | None = None,
    nodeid: str | None = None,
    xy: tuple[float, float] | None = None,
    storagedata: pd.DataFrame | None = None,
    usestreetstorage: bool = True,
    network: Network | None = None,
) -> None:
    """Add storage nodes with a level-area table.

    Parameters
    ----------
    storagenodes : gpd.GeoDataFrame
        Storage nodes, indexed by code, with ``branch_id`` and ``branch_offset``. Required.
    nodeid : str, optional
        Node id for all storage nodes. Defaults to None: the node at the chainage.
    xy : tuple[float, float], optional
        Location for all storage nodes. Defaults to None.
    storagedata : pd.DataFrame
        Level-area table, with the columns ``code``, ``level`` and ``area``. Required.
    usestreetstorage : bool, optional
        D-Flow FM keyword ``useStreetStorage``. Defaults to True.
    network : Network, optional
        Network with the 1D mesh, to find the node at the chainage. Defaults to None.

    Raises
    ------
    ValueError
        If ``storagenodes`` or ``storagedata`` is missing.
    """
    if storagenodes is None or storagedata is None:
        raise ValueError("Provide storagenodes and storagedata.")

    for storagenode_idx, storagenode in storagenodes.iterrows():
        data = storagedata[storagedata.code == storagenode_idx]
        # the index label of the row, or the code when that is missing
        name = storagenode.name
        if name is None or (isinstance(name, float) and np.isnan(name)):
            name = storagenode.code
        self.storagenodes.add_storagenode(
            id=str(storagenode_idx),
            name=str(name),
            usestreetstorage=usestreetstorage,
            nodetype="unspecified",
            nodeid=nodeid,
            xy=xy,
            branchid=storagenode.branch_id,
            chainage=storagenode.branch_offset,
            usetable="true",
            storagearea=" ".join(data.area.astype(str)),
            levels=" ".join(data.level.astype(str)),
            network=network,
        )

StructuresIO

Add structures from DAMO tables.

Parameters

structures : Structures The structures of a HyDAMO object, filled in place.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
 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
class StructuresIO:
    """Add structures from DAMO tables.

    Parameters
    ----------
    structures : Structures
        The structures of a HyDAMO object, filled in place.
    """

    def __init__(self, structures: Structures) -> None:
        self.structures = structures

    @staticmethod
    def _claim_weir_id(owners: dict[str, str], weir_id: str, owner: str) -> None:
        """Record that *owner* uses structure id *weir_id*, or raise if it is taken.

        Parameters
        ----------
        owners : dict[str, str]
            The owner of each structure id claimed so far, updated in place.
        weir_id : str
            The D-Flow FM structure id.
        owner : str
            What the id belongs to, e.g. ``"opening 1 of weir ST2"`` or ``"weir ST3"``.

        Raises
        ------
        ValueError
            If another weir or opening already has *weir_id*.
        """
        if weir_id in owners:
            raise ValueError(
                f"Structure id {weir_id} of {owner} is also the id of "
                f"{owners[weir_id]}. D-Flow FM needs unique structure ids: give "
                "these weirs unique codes in the GeoPackage. A code ending in _<n> "
                "may have been added by HYDROLIB for a duplicate code; see the "
                "duplicates warning."
            )
        owners[weir_id] = owner

    def _name_or_nan(self, row: pd.Series) -> Hashable:
        """Return the index label of the row if it has a name column, otherwise NaN."""
        return row.name if "name" in row.index else np.nan

    def _common_structure_kwargs(
        self, row: pd.Series, id_attr: str = "id"
    ) -> dict[str, object]:
        """Return the id, name, branch id and chainage of a structure row."""
        return {
            "id": getattr(row, id_attr),
            "name": self._name_or_nan(row),
            "branchid": row.branch_id,
            "chainage": row.branch_offset,
        }

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def generalstructures_from_datamodel(self, generalstructures: pd.DataFrame) -> None:
        """Add general structures from a parsed data model (legacy from delft3dfmpy, untested)."""
        for generalstructure_idx, generalstructure in generalstructures.iterrows():
            base = self._common_structure_kwargs(generalstructure)
            self.structures.add_generalstructure(
                **base,
                allowedflowdir="both",
                upstream1width=generalstructure.upstream1width
                if "upstream1width" in generalstructure.index
                else np.nan,
                upstream1level=generalstructure.upstream1level
                if "upstream1level" in generalstructure.index
                else np.nan,
                upstream2width=generalstructure.upstream2width
                if "upstream2width" in generalstructure.index
                else np.nan,
                upstream2level=generalstructure.upstream2level
                if "upstream2level" in generalstructure.index
                else np.nan,
                crestwidth=generalstructure.crestwidth
                if "crestwidth" in generalstructure.index
                else np.nan,
                crestlevel=generalstructure.crestlevel
                if "crestlevel" in generalstructure.index
                else np.nan,
                crestlength=generalstructure.crestlength
                if "crestlength" in generalstructure.index
                else np.nan,
                downstream1width=generalstructure.downstream1width
                if "downstream1width" in generalstructure.index
                else np.nan,
                downstream1level=generalstructure.downstream1level
                if "downstream1level" in generalstructure.index
                else np.nan,
                downstream2width=generalstructure.downstream2width
                if "downstream2width" in generalstructure.index
                else np.nan,
                downstream2level=generalstructure.downstream2level
                if "downstream2level" in generalstructure.index
                else np.nan,
                gateloweredgelevel=generalstructure.gateloweredgelevel
                if "gateloweredgelevel" in generalstructure.index
                else np.nan,
                posfreegateflowcoeff=generalstructure.posfreegateflowcoeff
                if "posfreegateflowcoeff" in generalstructure.index
                else np.nan,
                posdrowngateflowcoeff=generalstructure.posdrowngateflowcoeff
                if "posdrowngateflowcoeff" in generalstructure.index
                else np.nan,
                posfreeweirflowcoeff=generalstructure.posfreeweirflowcoeff
                if "posfreeweirflowcoeff" in generalstructure.index
                else np.nan,
                posdrownweirflowcoeff=generalstructure.posdrownweirflowcoeff
                if "posdrownweirflowcoeff" in generalstructure.index
                else np.nan,
                poscontrcoeffreegate=generalstructure.poscontrcoeffreegate
                if "poscontrcoeffreegate" in generalstructure.index
                else np.nan,
                negfreegateflowcoeff=generalstructure.negfreegateflowcoeff
                if "negfreegateflowcoeff" in generalstructure.index
                else np.nan,
                negdrowngateflowcoeff=generalstructure.negdrowngateflowcoeff
                if "negdrowngateflowcoeff" in generalstructure.index
                else np.nan,
                negfreeweirflowcoeff=generalstructure.negfreeweirflowcoeff
                if "negfreeweirflowcoeff" in generalstructure.index
                else np.nan,
                negdrownweirflowcoeff=generalstructure.negdrownweirflowcoeff
                if "negdrownweirflowcoeff" in generalstructure.index
                else np.nan,
                negcontrcoeffreegate=generalstructure.negcontrcoeffreegate
                if "negcontrcoeffreegate" in generalstructure.index
                else np.nan,
                extraresistance=generalstructure.extraresistance
                if "extraresistance" in generalstructure.index
                else np.nan,
                gateheight=generalstructure.gateheight
                if "gateheight" in generalstructure.index
                else np.nan,
                gateopeningwidth=generalstructure.gateopeningwidth
                if "gateopeningwidth" in generalstructure.index
                else np.nan,
                gateopeninghorizontaldirection=generalstructure.gateopeninghorizontaldirection
                if "gateopeninghorizontaldirection" in generalstructure.index
                else np.nan,
                usevelocityheight=generalstructure.usevelocityheight
                if "usevelocityheight" in generalstructure.index
                else np.nan,
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def weirs(
        self,
        weirs: ExtendedGeoDataFrame | None = None,
        profile_groups: ExtendedDataFrame | None = None,
        profile_lines: ExtendedGeoDataFrame | None = None,
        profiles: ExtendedGeoDataFrame | None = None,
        opening: ExtendedDataFrame | None = None,
        management_device: ExtendedDataFrame | None = None,
        usevelocityheight: bool = True,
    ) -> None:
        """Add the DAMO weirs as regular weirs, orifices or universal weirs.

        A weir with a profile group (``stuwid``) becomes a universal weir. A weir whose
        management device has ``overlaatonderlaat`` set to ``"onderlaat"`` becomes an
        orifice. Other weirs become regular (rectangular) weirs. A weir with more than one
        opening becomes a compound structure.

        Parameters
        ----------
        weirs : ExtendedGeoDataFrame, optional
            DAMO weirs (stuw). Defaults to None.
        profile_groups, profile_lines, profiles : optional
            DAMO profile groups, lines and points, for universal weirs. Default to None.
        opening : ExtendedDataFrame, optional
            DAMO openings (kunstwerkopening). Defaults to None.
        management_device : ExtendedDataFrame, optional
            DAMO management devices (regelmiddel). Defaults to None.
        usevelocityheight : bool, optional
            D-Flow FM keyword ``usevelocityheight``. Defaults to True.
        """
        opening_weir = DamoRelations.OPENING_WEIR
        management_device_opening = DamoRelations.MANAGEMENT_DEVICE_OPENING
        profile_group_weir = DamoRelations.PROFILE_GROUP_WEIR
        profile_line_group = DamoRelations.PROFILE_LINE_GROUP
        profile_line = DamoRelations.PROFILE_LINE
        if weirs is None or opening is None or management_device is None:
            raise ValueError("weirs, opening and management_device are required.")
        index = np.zeros(len(weirs.code))
        if (
            profile_groups is not None
            and profile_group_weir.foreign_key in profile_groups
        ):
            index[
                np.isin(
                    weirs[opening_weir.parent_key],
                    np.asarray(profile_groups[profile_group_weir.foreign_key]),
                )
            ] = 1

        # The owner of each structure id. The id of an opening of a compound weir,
        # weir.code_N, can be the code of another weir.
        owners: dict[str, str] = {}
        rweirs = weirs[index == 0]
        for weir in rweirs.itertuples():
            weir_rows = rweirs.loc[[weir.Index]]
            weir_opening = opening_weir.children_of(weir_rows, opening)

            # the name, or the code when there is none
            if "naam" in weirs.columns and pd.notna(weir.naam):
                name = str(weir.naam)
            else:
                name = str(weir.code)

            if weir_opening.shape[0] > 1:
                logger.info(
                    "Weir %s contains %d openings. Creating a compound structure with a fictional weir for each one.",
                    weir.code,
                    weir_opening.shape[0],
                )
                cmp_list = []
                for num_op, (op_index, op_row) in enumerate(weir_opening.iterrows()):
                    opening_rows = weir_opening.loc[[op_index]]
                    weir_mandev = management_device_opening.children_of(
                        opening_rows,
                        management_device,
                    )

                    if weir_mandev.empty:
                        logger.warning(
                            "Skipping opening %s (weir %s) because there is no associated management device.",
                            op_row.globalid,
                            weir.code,
                        )
                        continue
                    if weir_mandev.shape[0] > 1:
                        logger.warning(
                            "Multiple management devices associated to opening %s (weir %s). Taking the first one.",
                            op_row.globalid,
                            weir.code,
                        )
                        weir_mandev = weir_mandev.iloc[[0]]

                    # This weir has multiple openings, so its structure id gets an
                    # enumeration suffix that is invented right here and is not
                    # present anywhere in the HyDAMO data. Record it so DRTCModel
                    # can later resolve a management record's regelmiddelid to
                    # this structure id; see Structures.compound_weir_structure_ids
                    # in core/hydamo.py.
                    weir_id = f"{weir.code}_{num_op + 1}"
                    self._claim_weir_id(
                        owners, weir_id, f"opening {num_op + 1} of weir {weir.code}"
                    )
                    self.structures.compound_weir_structure_ids[
                        str(weir_mandev["globalid"].iloc[0])
                    ] = weir_id
                    overlaatonderlaat = _overlaatonderlaat(weir_mandev)
                    kind = (overlaatonderlaat or "").lower()
                    if kind == "overlaat":
                        cmp_list.append(weir_id)
                        self.structures.add_rweir(
                            id=weir_id,
                            name=name,
                            branchid=weir.branch_id,
                            chainage=weir.branch_offset,
                            crestlevel=op_row.laagstedoorstroomhoogte,
                            crestwidth=op_row.laagstedoorstroombreedte,
                            corrcoeff=weir.afvoercoefficient,
                            allowedflowdir="both",
                            usevelocityheight=usevelocityheight,
                        )
                    elif kind == "onderlaat":
                        if self._add_orifice(
                            weir_id,
                            name,
                            weir,
                            op_row,
                            weir_mandev,
                            usevelocityheight,
                            f"opening {num_op + 1} of weir {weir.code}",
                        ):
                            cmp_list.append(weir_id)
                    else:
                        _warn_unknown_weir_kind(
                            f"opening {num_op + 1} of weir {weir.code}",
                            weir_mandev,
                            overlaatonderlaat,
                        )
                self.structures.add_compound(
                    id=f"cmp_{weir.code}", structureids=cmp_list
                )
                # self.structures.rweirs_df.drop(weir.code)
            else:
                if weir_opening.empty:
                    logger.warning(
                        "Skipping weir %s because there is no associated opening.",
                        weir.code,
                    )
                    continue

                weir_id = weir.code
                self._claim_weir_id(owners, weir_id, f"weir {weir.code}")
                # Unlike the compound case above, no need to record this id in
                # compound_weir_structure_ids: this weir has a single opening, so
                # its structure id is just weir.code, which
                # DRTCModel._resolve_weir_via_opening derives directly from
                # HyDAMO's static relations.
                weir_mandev = management_device_opening.children_of(
                    weir_opening,
                    management_device,
                )

                if weir_mandev.empty:
                    logger.warning(
                        "Skipping opening %s (weir %s) because there is no associated management device.",
                        weir_opening.globalid.squeeze(),
                        weir_id,
                    )
                    continue
                if weir_mandev.shape[0] > 1:
                    logger.warning(
                        "Multiple management devices associated to opening %s (weir %s). Taking the first one.",
                        weir_opening.globalid.squeeze(),
                        weir_id,
                    )
                    weir_mandev = weir_mandev.iloc[[0]]

                overlaatonderlaat = _overlaatonderlaat(weir_mandev)
                kind = (overlaatonderlaat or "").lower()

                if kind == "overlaat":
                    self.structures.add_rweir(
                        id=weir_id,
                        name=name,
                        branchid=weir.branch_id,
                        chainage=weir.branch_offset,
                        crestlevel=weir_opening.laagstedoorstroomhoogte.to_numpy()[0],
                        crestwidth=weir_opening.laagstedoorstroombreedte.to_numpy()[0],
                        corrcoeff=weir.afvoercoefficient,
                        allowedflowdir="both",
                        usevelocityheight=usevelocityheight,
                    )

                elif kind == "onderlaat":
                    self._add_orifice(
                        weir_id,
                        name,
                        weir,
                        weir_opening.iloc[0],
                        weir_mandev,
                        usevelocityheight,
                        f"weir {weir.code}",
                    )
                else:
                    _warn_unknown_weir_kind(
                        f"weir {weir.code}", weir_mandev, overlaatonderlaat
                    )

        uweirs = weirs[index == 1]
        for uweir in uweirs.itertuples():
            self._claim_weir_id(owners, str(uweir.code), f"weir {uweir.code}")
            uweir_rows = uweirs.loc[[uweir.Index]]
            # the name, or the code when there is none
            if "naam" in uweirs.columns and pd.notna(uweir.naam):
                name = str(uweir.naam)
            else:
                name = str(uweir.code)

            prof = pd.DataFrame()
            if (
                profiles is not None
                and profile_groups is not None
                and profile_lines is not None
                and profile_group_weir.foreign_key in profile_groups
            ):
                group = profile_group_weir.children_of(uweir_rows, profile_groups)
                line = profile_line_group.children_of(group, profile_lines)
                prof = profile_line.children_of(line, profiles)
                if not prof.empty:
                    counts = len(prof.geometry.iloc[0].coords[:])
                    xyz = np.vstack(prof.geometry.iloc[0].coords[:])
                    length = np.r_[
                        0,
                        np.cumsum(np.hypot(np.diff(xyz[:, 0]), np.diff(xyz[:, 1]))),
                    ]
                    yzvalues = np.c_[length, xyz[:, -1] - np.min(xyz[:, -1])]

            if len(prof) == 0:
                # return an error it is still not found
                raise ValueError(f"{uweir.code} is not found in any cross-section.")

            if not hasattr(uweir, "laagstedoorstroomhoogte") or pd.isna(
                uweir.laagstedoorstroomhoogte
            ):
                kruinhoogte = np.min(xyz[:, -1])
            else:
                kruinhoogte = uweir.laagstedoorstroomhoogte
            self.structures.add_uweir(
                id=uweir.code,
                name=name,
                branchid=uweir.branch_id,
                chainage=uweir.branch_offset,
                crestlevel=kruinhoogte,
                dischargecoeff=uweir.afvoercoefficient,
                allowedflowdir="both",
                numlevels=counts,
                yvalues=" ".join([f"{yz[0]:7.3f}" for yz in yzvalues]),
                zvalues=" ".join([f"{yz[1]:7.3f}" for yz in yzvalues]),
            )

    def _add_orifice(
        self,
        orifice_id: str,
        name: str,
        weir: Any,
        opening: pd.Series,
        device: pd.DataFrame,
        usevelocityheight: bool,
        structure: str,
    ) -> bool:
        """Add the orifice of a weir *opening* whose *device* is an underflow.

        The gate's lower edge is the opening's crest plus the device's
        ``hoogteopening``. Without a gate height the orifice is skipped with a
        warning naming *structure*.

        Parameters
        ----------
        orifice_id : str
            Id of the orifice.
        name : str
            Name of the orifice.
        weir : Any
            The weir, a row of ``itertuples``: its branch, chainage and
            ``afvoercoefficient``.
        opening : pd.Series
            The opening: its crest level and width.
        device : pd.DataFrame
            The opening's management device, one row.
        usevelocityheight : bool
            D-Flow FM keyword ``usevelocityheight``.
        structure : str
            The structure in the warning, e.g. ``"weir ST1"``.

        Returns
        -------
        bool
            Whether the orifice was added.
        """
        height = device["hoogteopening"].iloc[0] if "hoogteopening" in device else None
        if height is None or pd.isna(height):
            logger.warning(
                "Skipping %s: its management device %s has no gate height "
                '("hoogteopening"; from DAMO 2.5 "maximalehoogteonderkant").',
                structure,
                _device_name(device.iloc[0]),
            )
            return False
        if "maximaaldebiet" not in device or pd.isna(device.maximaaldebiet.iloc[0]):
            limitflow = False
            maxq = 0.0
        else:
            limitflow = True
            maxq = float(device.maximaaldebiet.iloc[0])
        crest = float(opening.laagstedoorstroomhoogte)
        self.structures.add_orifice(
            id=orifice_id,
            name=name,
            branchid=weir.branch_id,
            chainage=weir.branch_offset,
            crestlevel=crest,
            crestwidth=float(opening.laagstedoorstroombreedte),
            corrcoeff=weir.afvoercoefficient,
            allowedflowdir="both",
            usevelocityheight=usevelocityheight,
            gateloweredgelevel=crest + float(height),
            uselimitflowpos=limitflow,
            limitflowpos=maxq,
            uselimitflowneg=limitflow,
            limitflowneg=maxq,
        )
        return True

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def weirs_from_datamodel(self, weirs: pd.DataFrame) -> None:
        """Add weirs from a parsed data model (legacy from delft3dfmpy, untested)."""
        for weir_idx, weir in weirs.iterrows():
            base = self._common_structure_kwargs(weir)
            self.structures.add_weir(
                **base,
                crestlevel=weir.crestlevel,
                crestwidth=weir.crestwidth,
                corrcoeff=weir.corrcoeff,
            )

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def orifices_from_datamodel(self, orifices: pd.DataFrame) -> None:
        """Add orifices from a parsed data model (legacy from delft3dfmpy, untested)."""
        for orifice_idx, orifice in orifices.iterrows():
            base = self._common_structure_kwargs(orifice)
            self.structures.add_orifice(
                **base,
                allowedflowdir="both",
                crestlevel=orifice.crestlevel,
                crestwidth=orifice.crestwidth,
                gateloweredgelevel=orifice.gateloweredgelevel,
                corrcoeff=orifice.corrcoef,
                uselimitflowpos=orifice.uselimitflowpos,
                limitflowpos=orifice.limitflowpos,
                uselimitflowneg=orifice.uselimitflowneg,
                limitflowneg=orifice.limitflowneg,
            )

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def uweirs_from_datamodel(self, uweirs: pd.DataFrame) -> None:
        """Add universal weirs from a parsed data model (legacy from delft3dfmpy, untested)."""
        for uweir_idx, uweir in uweirs.iterrows():
            base = self._common_structure_kwargs(uweir)
            self.structures.add_uweir(
                **base,
                crestlevel=uweir.crestlevel,
                yvalues=uweir.yvalues,
                zvalues=uweir.zvalues,
                allowedflowdir="both",
                dischargecoeff=uweir.dischargecoeff,
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def bridges(
        self,
        bridges: ExtendedGeoDataFrame,
        profile_groups: ExtendedDataFrame | None = None,
        profile_lines: ExtendedGeoDataFrame | None = None,
        profiles: ExtendedGeoDataFrame | None = None,
    ) -> None:
        """Add the DAMO bridges.

        Every bridge needs a YZ profile, through ``profile_groups`` (``brugid``),
        ``profile_lines`` and ``profiles``.

        Parameters
        ----------
        bridges : ExtendedGeoDataFrame
            DAMO bridges (brug).
        profile_groups, profile_lines, profiles : optional
            DAMO profile groups, lines and points. Default to None.
        """
        profile_group_bridge = DamoRelations.PROFILE_GROUP_BRIDGE
        profile_line_group = DamoRelations.PROFILE_LINE_GROUP
        profile_line = DamoRelations.PROFILE_LINE
        if profile_groups is None or profile_lines is None or profiles is None:
            raise ValueError(
                "profile_groups, profile_lines and profiles are required for bridges."
            )
        for bridge in bridges.itertuples():
            bridge_rows = bridges.loc[[bridge.Index]]
            # first search in yz-profiles
            group = profile_group_bridge.children_of(bridge_rows, profile_groups)
            line = profile_line_group.children_of(group, profile_lines)
            prof = profile_line.children_of(line, profiles)

            if len(prof) == 0:
                raise ValueError(f"{bridge.code} is not found in any cross-section.")

            # the name, if present, otherwise the code
            name = str(bridge.code)
            if "naam" in bridges and pd.notna(bridge.naam):
                name = str(bridge.naam)

            profile_id = prof.code.to_numpy()[0]
            self.structures.add_bridge(
                id=str(bridge.code),
                name=name,
                branchid=str(bridge.branch_id),
                chainage=pd.to_numeric(bridge.branch_offset),
                csdefid=profile_id,
                shift=0.0,
                allowedflowdir="both",
                inletlosscoeff=pd.to_numeric(bridge.intreeverlies),
                outletlosscoeff=pd.to_numeric(bridge.uittreeverlies),
                length=pd.to_numeric(bridge.lengte),
                frictiontype=str(bridge.typeruwheid),
                friction=pd.to_numeric(bridge.ruwheid),
            )

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def bridges_from_datamodel(self, bridges: pd.DataFrame) -> None:
        """Add bridges from a parsed data model (legacy from delft3dfmpy, untested)."""
        for bridge_idx, bridge in bridges.iterrows():
            base = self._common_structure_kwargs(bridge, id_attr="code")
            self.structures.add_bridge(
                **base,
                csdefid=bridge.csdefid,
                shift=0.0,
                allowedflowdir="both",
                inletlosscoeff=bridge.intreeverlies,
                outletlosscoeff=bridge.uittreeverlies,
                length=bridge.lengte,
                frictiontype=bridge.typeruwheid,
                friction=bridge.ruwheid,
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def culverts(
        self,
        culverts: ExtendedGeoDataFrame,
        management_device: ExtendedDataFrame | None = None,
    ) -> None:
        """Add the DAMO culverts.

        A non-return valve (``terugslagklep``) or a gate (``schuif``) is schematized
        from the culvert's management devices. A gate without a height gives no
        valve, and a device of another type is ignored, each with a warning.

        Parameters
        ----------
        culverts : ExtendedGeoDataFrame
            DAMO culverts (duikersifonhevel).
        management_device : ExtendedDataFrame, optional
            DAMO management devices (regelmiddel; afsluitmiddel from DAMO 2.5).
            Defaults to None.
        """
        management_device_culvert = DamoRelations.MANAGEMENT_DEVICE_CULVERT

        for culvert in culverts.itertuples():
            culvert_rows = culverts.loc[[culvert.Index]]
            # Generate cross section definition name
            vormkoker = str(culvert.vormkoker).lower()
            if vormkoker in {"rond", "ellipsvormig"}:
                crosssection = {"shape": "circle", "diameter": culvert.hoogteopening}
            elif vormkoker in {
                "rechthoekig",
                "onbekend",
                "eivormig",
                "muilprofiel",
                "heulprofiel",
            }:
                crosssection = {
                    "shape": "rectangle",
                    "height": culvert.hoogteopening,
                    "width": culvert.breedteopening,
                    "closed": 1,
                }
            else:
                crosssection = {"shape": "circle", "diameter": 0.40}
                logger.info(
                    f"Culvert {culvert.code} has an unknown shape: {culvert.vormkoker}. Applying a default profile (round - 40cm)"
                )

            # check whether an afsluitmiddel is present and take action dependent on its settings
            if management_device is not None:
                mandev = management_device_culvert.children_of(
                    culvert_rows,
                    management_device,
                )
            else:
                mandev = pd.DataFrame()

            # default settings
            allowedflowdir = "both"
            valveonoff = 0
            numlosscoeff = None
            valveopeningheight: float = 0
            relopening = None
            losscoeff = None
            for _, device in mandev.iterrows():
                device_type = device.get("soortregelmiddel")
                if device_type == "terugslagklep":
                    allowedflowdir = _non_return_direction(device, str(culvert.code))
                elif device_type == "schuif":
                    height = device.get("hoogteopening")
                    if height is None or pd.isna(height):
                        logger.warning(
                            "Building culvert %s without a valve: its management "
                            'device %s has no gate height ("hoogteopening"; from '
                            'DAMO 2.5 "maximalehoogteonderkant").',
                            culvert.code,
                            _device_name(device),
                        )
                        continue
                    valveonoff = 1
                    valveopeningheight = float(height)
                    numlosscoeff = 1
                    relopening = [
                        float(height)
                        / float(culvert_rows["hoogteopening"].to_numpy()[0])
                    ]
                    losscoeff = [float(device["afvoercoefficient"])]
                else:
                    logger.warning(
                        'Ignoring management device %s of type "%s" on culvert %s: '
                        'only "schuif" and "terugslagklep" are modelled.',
                        _device_name(device),
                        device_type,
                        culvert.code,
                    )

            # check if a separate name field is present
            # the name, if present, otherwise the code
            name = str(culvert.code)
            if "naam" in culverts and pd.notna(culvert.naam):
                name = str(culvert.naam)

            self.structures.add_culvert(
                id=str(culvert.code),
                name=name,
                branchid=str(culvert.branch_id),
                chainage=pd.to_numeric(culvert.branch_offset),
                leftlevel=pd.to_numeric(culvert.hoogtebinnenonderkantbov),
                rightlevel=pd.to_numeric(culvert.hoogtebinnenonderkantbene),
                length=pd.to_numeric(culvert.lengte),
                inletlosscoeff=pd.to_numeric(culvert.intreeverlies),
                outletlosscoeff=pd.to_numeric(culvert.uittreeverlies),
                crosssection=crosssection,
                allowedflowdir=allowedflowdir,
                valveonoff=valveonoff,
                numlosscoeff=numlosscoeff,
                valveopeningheight=valveopeningheight,
                relopening=relopening,
                losscoeff=losscoeff,
                bedfrictiontype=str(culvert.typeruwheid),
                bedfriction=pd.to_numeric(culvert.ruwheid),
            )

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def culverts_from_datamodel(self, culverts: pd.DataFrame) -> None:
        """Add culverts from a parsed data model (legacy from delft3dfmpy, untested)."""
        # Add to dict
        for culvert_idx, culvert in culverts.iterrows():
            base = self._common_structure_kwargs(culvert)
            self.structures.add_culvert(
                **base,
                leftlevel=culvert.leftlevel,
                rightlevel=culvert.rightlevel,
                crosssection=culvert.crosssectiondefinitionid,
                length=culvert.geometry.length
                if "geometry" in culvert.index
                else culvert.length,
                inletlosscoeff=culvert.inletlosscoeff,
                outletlosscoeff=culvert.outletlosscoeff,
                allowedflowdir="both",
                valveonoff=0,
                numlosscoeff=0,
                valveopeningheight=np.nan,
                relopening=np.nan,
                losscoeff=np.nan,
                frictiontype=culvert.frictiontype,
                frictionvalue=culvert.frictionvalue,
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def pumps(
        self,
        pumpstations: ExtendedGeoDataFrame,
        pumps: ExtendedDataFrame | None = None,
        management: ExtendedDataFrame | None = None,
    ) -> None:
        """Add the DAMO pumps.

        A pump station with more than one pump becomes a compound structure.

        Parameters
        ----------
        pumpstations : ExtendedGeoDataFrame
            DAMO pump stations (gemaal).
        pumps : ExtendedDataFrame
            DAMO pumps (pomp). Required.
        management : ExtendedDataFrame
            DAMO control (sturing). Required.

        Raises
        ------
        ValueError
            If ``pumps`` or ``management`` is missing.
        """
        pump_pumpstation = DamoRelations.PUMP_PUMPSTATION
        management_pump = DamoRelations.MANAGEMENT_PUMP
        if pumps is None or management is None:
            raise ValueError("pumps and management are required.")

        # Add sturing to pumps
        for pumpstation in pumpstations.itertuples():
            pumpstation_rows = pumpstations.loc[[pumpstation.Index]]

            # find pumps for gemaal
            pumps_subset = pump_pumpstation.children_of(pumpstation_rows, pumps)
            if pumps_subset.empty:
                logger.warning(
                    "Skipping %s because there is no associated pump.",
                    pumpstation.code,
                )
                continue

            # the name, or the code when there is none
            if "naam" in pumpstations.columns and pd.notna(pumpstation.naam):
                name = str(pumpstation.naam)
            else:
                name = str(pumpstation.code)
            is_compound = len(pumps_subset) > 1
            cmp_list = []
            if is_compound:
                logger.info(
                    "Pumpstation %s contains %d openings. Creating a compound structure with a fictional pump for each one.",
                    pumpstation.code,
                    pumps_subset.shape[0],
                )

            for ipump, (pump_index, pump) in enumerate(pumps_subset.iterrows()):
                pump_rows = pumps_subset.loc[[pump_index]]
                pump_control = management_pump.children_of(
                    pump_rows,
                    management,
                )
                if pump_control.empty:
                    if is_compound:
                        logger.warning("No management found for %s", pump.code)
                    else:
                        logger.warning(
                            "Skipping %s because there is no associated management.",
                            pumpstation.code,
                        )
                    continue
                if len(pump_control) > 1:
                    raise ValueError(
                        f"Pump station {pumpstation.code}: expected one management row "
                        f"per pump, found {len(pump_control)}."
                    )
                startlevelsuctionside = [pump_control["bovengrens"].iloc[0]]
                stoplevelsuctionside = [pump_control["ondergrens"].iloc[0]]

                if is_compound:
                    pumpid = f"{pumpstation.code}_{ipump + 1}"
                else:
                    pumpid = str(pumpstation.code)
                cmp_list.append(pumpid)
                self.structures.add_pump(
                    id=pumpid,
                    name=str(name),
                    branchid=str(pumpstation.branch_id),
                    chainage=pd.to_numeric(pumpstation.branch_offset),
                    orientation="positive",
                    numstages=1,
                    controlside="suctionside",
                    capacity=pump.maximalecapaciteit / 60.0,
                    startlevelsuctionside=startlevelsuctionside,
                    stoplevelsuctionside=stoplevelsuctionside,
                    startleveldeliveryside=startlevelsuctionside,
                    stopleveldeliveryside=stoplevelsuctionside,
                )

            if is_compound:
                self.structures.add_compound(
                    id=f"cmp_{pumpstation.code}", structureids=cmp_list
                )

    # legacy from delft3dfmpy, not used or tested here (some are broken): mypy skips it
    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def pumps_from_datamodel(self, pumps: pd.DataFrame) -> None:
        """Add pumps from a parsed data model (legacy from delft3dfmpy, untested)."""
        for pump_idx, pump in pumps.iterrows():
            base = self._common_structure_kwargs(pump)
            self.structures.add_pump(
                **base,
                orientation="positive",
                numstages=1,
                controlside=pump.controlside,
                capacity=pump.maximumcapacity,
                startlevelsuctionside=pump.startlevelsuctionside,
                stoplevelsuctionside=pump.stoplevelsuctionside,
                startleveldeliveryside=pump.startleveldeliveryside,
                stopleveldeliveryside=pump.stopleveldeliveryside,
            )

    @staticmethod
    def move_structure(
        struc: str,
        struc_dict: dict[str, dict[str, str | float]],
        branch: str,
        offset: float,
    ) -> dict[str, dict[str, str | float]]:
        """Move a structure to the location of the first structure of its compound, in place.

        Parameters
        ----------
        struc : str
            Id of the structure to move.
        struc_dict : dict
            All structures of one type, by id.
        branch : str
            Branch id of the first structure in the compound.
        offset : float
            Chainage of the first structure in the compound.

        Returns
        -------
        dict
            ``struc_dict``, with the moved structure.
        """
        branch2 = struc_dict[struc]["branchid"]
        if branch2 != branch:
            logger.warning(
                f"Structures of not on the same branche. Moving structure {struc} to branch {branch}."
            )
        struc_dict[struc]["branchid"] = branch
        struc_dict[struc]["chainage"] = offset
        return struc_dict

    def _structure_frames(self) -> tuple[pd.DataFrame, ...]:
        """Return the tables of all structure types that can be part of a compound."""
        return (
            self.structures.pumps_df,
            self.structures.rweirs_df,
            self.structures.uweirs_df,
            self.structures.culverts_df,
            self.structures.bridges_df,
            self.structures.orifices_df,
        )

    def _get_structure_location(
        self, structure_id: str
    ) -> tuple[str | None, float | None]:
        """Return the branch id and chainage of a structure, or None if it is not found."""
        branch = None
        offset = None
        for df in self._structure_frames():
            if df.empty:
                continue
            match = df[df.id == structure_id]
            if not match.empty:
                branch = match.branchid.to_numpy()[0]
                offset = match.chainage.to_numpy()[0]
        return branch, offset

    def _set_structure_location(
        self, structure_id: str, branch: str, offset: float
    ) -> None:
        """Set the branch id and chainage of a structure, in place."""
        for df in self._structure_frames():
            if df.empty:
                continue
            idx = df.index[df.id == structure_id]
            if not idx.empty:
                df.loc[idx, "branchid"] = branch
                df.loc[idx, "chainage"] = offset

    def compound_structures(
        self, idlist: list[str], structurelist: list[list[str]]
    ) -> None:
        """Add compound structures, and move their structures to the location of the first.

        Parameters
        ----------
        idlist : list[str]
            Id of each compound structure.
        structurelist : list[list[str]]
            Ids of the structures of each compound structure.
        """
        # probably the coordinates should all be set to those of the first structure (still to do)
        for c_i, c_id in enumerate(idlist):
            branch = None
            offset = None
            # check the substructure coordinates. If they do not coincide, move subsequent structures to the coordinates of the first
            for s_i, struc in enumerate(structurelist[c_i]):
                if s_i == 0:
                    # find out what type the first structure it is and get its coordinates
                    branch, offset = self._get_structure_location(struc)
                else:
                    # move a subsequent structure to the location of the first
                    if branch is not None and offset is not None:
                        self._set_structure_location(struc, branch, offset)

            self.structures.add_compound(id=c_id, structureids=structurelist[c_i])
bridges(bridges: ExtendedGeoDataFrame, profile_groups: ExtendedDataFrame | None = None, profile_lines: ExtendedGeoDataFrame | None = None, profiles: ExtendedGeoDataFrame | None = None) -> None

Add the DAMO bridges.

Every bridge needs a YZ profile, through profile_groups (brugid), profile_lines and profiles.

Parameters

bridges : ExtendedGeoDataFrame DAMO bridges (brug). profile_groups, profile_lines, profiles : optional DAMO profile groups, lines and points. Default to None.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def bridges(
    self,
    bridges: ExtendedGeoDataFrame,
    profile_groups: ExtendedDataFrame | None = None,
    profile_lines: ExtendedGeoDataFrame | None = None,
    profiles: ExtendedGeoDataFrame | None = None,
) -> None:
    """Add the DAMO bridges.

    Every bridge needs a YZ profile, through ``profile_groups`` (``brugid``),
    ``profile_lines`` and ``profiles``.

    Parameters
    ----------
    bridges : ExtendedGeoDataFrame
        DAMO bridges (brug).
    profile_groups, profile_lines, profiles : optional
        DAMO profile groups, lines and points. Default to None.
    """
    profile_group_bridge = DamoRelations.PROFILE_GROUP_BRIDGE
    profile_line_group = DamoRelations.PROFILE_LINE_GROUP
    profile_line = DamoRelations.PROFILE_LINE
    if profile_groups is None or profile_lines is None or profiles is None:
        raise ValueError(
            "profile_groups, profile_lines and profiles are required for bridges."
        )
    for bridge in bridges.itertuples():
        bridge_rows = bridges.loc[[bridge.Index]]
        # first search in yz-profiles
        group = profile_group_bridge.children_of(bridge_rows, profile_groups)
        line = profile_line_group.children_of(group, profile_lines)
        prof = profile_line.children_of(line, profiles)

        if len(prof) == 0:
            raise ValueError(f"{bridge.code} is not found in any cross-section.")

        # the name, if present, otherwise the code
        name = str(bridge.code)
        if "naam" in bridges and pd.notna(bridge.naam):
            name = str(bridge.naam)

        profile_id = prof.code.to_numpy()[0]
        self.structures.add_bridge(
            id=str(bridge.code),
            name=name,
            branchid=str(bridge.branch_id),
            chainage=pd.to_numeric(bridge.branch_offset),
            csdefid=profile_id,
            shift=0.0,
            allowedflowdir="both",
            inletlosscoeff=pd.to_numeric(bridge.intreeverlies),
            outletlosscoeff=pd.to_numeric(bridge.uittreeverlies),
            length=pd.to_numeric(bridge.lengte),
            frictiontype=str(bridge.typeruwheid),
            friction=pd.to_numeric(bridge.ruwheid),
        )
bridges_from_datamodel(bridges: pd.DataFrame) -> None

Add bridges from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def bridges_from_datamodel(self, bridges: pd.DataFrame) -> None:
    """Add bridges from a parsed data model (legacy from delft3dfmpy, untested)."""
    for bridge_idx, bridge in bridges.iterrows():
        base = self._common_structure_kwargs(bridge, id_attr="code")
        self.structures.add_bridge(
            **base,
            csdefid=bridge.csdefid,
            shift=0.0,
            allowedflowdir="both",
            inletlosscoeff=bridge.intreeverlies,
            outletlosscoeff=bridge.uittreeverlies,
            length=bridge.lengte,
            frictiontype=bridge.typeruwheid,
            friction=bridge.ruwheid,
        )
compound_structures(idlist: list[str], structurelist: list[list[str]]) -> None

Add compound structures, and move their structures to the location of the first.

Parameters

idlist : list[str] Id of each compound structure. structurelist : list[list[str]] Ids of the structures of each compound structure.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
def compound_structures(
    self, idlist: list[str], structurelist: list[list[str]]
) -> None:
    """Add compound structures, and move their structures to the location of the first.

    Parameters
    ----------
    idlist : list[str]
        Id of each compound structure.
    structurelist : list[list[str]]
        Ids of the structures of each compound structure.
    """
    # probably the coordinates should all be set to those of the first structure (still to do)
    for c_i, c_id in enumerate(idlist):
        branch = None
        offset = None
        # check the substructure coordinates. If they do not coincide, move subsequent structures to the coordinates of the first
        for s_i, struc in enumerate(structurelist[c_i]):
            if s_i == 0:
                # find out what type the first structure it is and get its coordinates
                branch, offset = self._get_structure_location(struc)
            else:
                # move a subsequent structure to the location of the first
                if branch is not None and offset is not None:
                    self._set_structure_location(struc, branch, offset)

        self.structures.add_compound(id=c_id, structureids=structurelist[c_i])
culverts(culverts: ExtendedGeoDataFrame, management_device: ExtendedDataFrame | None = None) -> None

Add the DAMO culverts.

A non-return valve (terugslagklep) or a gate (schuif) is schematized from the culvert's management devices. A gate without a height gives no valve, and a device of another type is ignored, each with a warning.

Parameters

culverts : ExtendedGeoDataFrame DAMO culverts (duikersifonhevel). management_device : ExtendedDataFrame, optional DAMO management devices (regelmiddel; afsluitmiddel from DAMO 2.5). Defaults to None.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def culverts(
    self,
    culverts: ExtendedGeoDataFrame,
    management_device: ExtendedDataFrame | None = None,
) -> None:
    """Add the DAMO culverts.

    A non-return valve (``terugslagklep``) or a gate (``schuif``) is schematized
    from the culvert's management devices. A gate without a height gives no
    valve, and a device of another type is ignored, each with a warning.

    Parameters
    ----------
    culverts : ExtendedGeoDataFrame
        DAMO culverts (duikersifonhevel).
    management_device : ExtendedDataFrame, optional
        DAMO management devices (regelmiddel; afsluitmiddel from DAMO 2.5).
        Defaults to None.
    """
    management_device_culvert = DamoRelations.MANAGEMENT_DEVICE_CULVERT

    for culvert in culverts.itertuples():
        culvert_rows = culverts.loc[[culvert.Index]]
        # Generate cross section definition name
        vormkoker = str(culvert.vormkoker).lower()
        if vormkoker in {"rond", "ellipsvormig"}:
            crosssection = {"shape": "circle", "diameter": culvert.hoogteopening}
        elif vormkoker in {
            "rechthoekig",
            "onbekend",
            "eivormig",
            "muilprofiel",
            "heulprofiel",
        }:
            crosssection = {
                "shape": "rectangle",
                "height": culvert.hoogteopening,
                "width": culvert.breedteopening,
                "closed": 1,
            }
        else:
            crosssection = {"shape": "circle", "diameter": 0.40}
            logger.info(
                f"Culvert {culvert.code} has an unknown shape: {culvert.vormkoker}. Applying a default profile (round - 40cm)"
            )

        # check whether an afsluitmiddel is present and take action dependent on its settings
        if management_device is not None:
            mandev = management_device_culvert.children_of(
                culvert_rows,
                management_device,
            )
        else:
            mandev = pd.DataFrame()

        # default settings
        allowedflowdir = "both"
        valveonoff = 0
        numlosscoeff = None
        valveopeningheight: float = 0
        relopening = None
        losscoeff = None
        for _, device in mandev.iterrows():
            device_type = device.get("soortregelmiddel")
            if device_type == "terugslagklep":
                allowedflowdir = _non_return_direction(device, str(culvert.code))
            elif device_type == "schuif":
                height = device.get("hoogteopening")
                if height is None or pd.isna(height):
                    logger.warning(
                        "Building culvert %s without a valve: its management "
                        'device %s has no gate height ("hoogteopening"; from '
                        'DAMO 2.5 "maximalehoogteonderkant").',
                        culvert.code,
                        _device_name(device),
                    )
                    continue
                valveonoff = 1
                valveopeningheight = float(height)
                numlosscoeff = 1
                relopening = [
                    float(height)
                    / float(culvert_rows["hoogteopening"].to_numpy()[0])
                ]
                losscoeff = [float(device["afvoercoefficient"])]
            else:
                logger.warning(
                    'Ignoring management device %s of type "%s" on culvert %s: '
                    'only "schuif" and "terugslagklep" are modelled.',
                    _device_name(device),
                    device_type,
                    culvert.code,
                )

        # check if a separate name field is present
        # the name, if present, otherwise the code
        name = str(culvert.code)
        if "naam" in culverts and pd.notna(culvert.naam):
            name = str(culvert.naam)

        self.structures.add_culvert(
            id=str(culvert.code),
            name=name,
            branchid=str(culvert.branch_id),
            chainage=pd.to_numeric(culvert.branch_offset),
            leftlevel=pd.to_numeric(culvert.hoogtebinnenonderkantbov),
            rightlevel=pd.to_numeric(culvert.hoogtebinnenonderkantbene),
            length=pd.to_numeric(culvert.lengte),
            inletlosscoeff=pd.to_numeric(culvert.intreeverlies),
            outletlosscoeff=pd.to_numeric(culvert.uittreeverlies),
            crosssection=crosssection,
            allowedflowdir=allowedflowdir,
            valveonoff=valveonoff,
            numlosscoeff=numlosscoeff,
            valveopeningheight=valveopeningheight,
            relopening=relopening,
            losscoeff=losscoeff,
            bedfrictiontype=str(culvert.typeruwheid),
            bedfriction=pd.to_numeric(culvert.ruwheid),
        )
culverts_from_datamodel(culverts: pd.DataFrame) -> None

Add culverts from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def culverts_from_datamodel(self, culverts: pd.DataFrame) -> None:
    """Add culverts from a parsed data model (legacy from delft3dfmpy, untested)."""
    # Add to dict
    for culvert_idx, culvert in culverts.iterrows():
        base = self._common_structure_kwargs(culvert)
        self.structures.add_culvert(
            **base,
            leftlevel=culvert.leftlevel,
            rightlevel=culvert.rightlevel,
            crosssection=culvert.crosssectiondefinitionid,
            length=culvert.geometry.length
            if "geometry" in culvert.index
            else culvert.length,
            inletlosscoeff=culvert.inletlosscoeff,
            outletlosscoeff=culvert.outletlosscoeff,
            allowedflowdir="both",
            valveonoff=0,
            numlosscoeff=0,
            valveopeningheight=np.nan,
            relopening=np.nan,
            losscoeff=np.nan,
            frictiontype=culvert.frictiontype,
            frictionvalue=culvert.frictionvalue,
        )
generalstructures_from_datamodel(generalstructures: pd.DataFrame) -> None

Add general structures from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def generalstructures_from_datamodel(self, generalstructures: pd.DataFrame) -> None:
    """Add general structures from a parsed data model (legacy from delft3dfmpy, untested)."""
    for generalstructure_idx, generalstructure in generalstructures.iterrows():
        base = self._common_structure_kwargs(generalstructure)
        self.structures.add_generalstructure(
            **base,
            allowedflowdir="both",
            upstream1width=generalstructure.upstream1width
            if "upstream1width" in generalstructure.index
            else np.nan,
            upstream1level=generalstructure.upstream1level
            if "upstream1level" in generalstructure.index
            else np.nan,
            upstream2width=generalstructure.upstream2width
            if "upstream2width" in generalstructure.index
            else np.nan,
            upstream2level=generalstructure.upstream2level
            if "upstream2level" in generalstructure.index
            else np.nan,
            crestwidth=generalstructure.crestwidth
            if "crestwidth" in generalstructure.index
            else np.nan,
            crestlevel=generalstructure.crestlevel
            if "crestlevel" in generalstructure.index
            else np.nan,
            crestlength=generalstructure.crestlength
            if "crestlength" in generalstructure.index
            else np.nan,
            downstream1width=generalstructure.downstream1width
            if "downstream1width" in generalstructure.index
            else np.nan,
            downstream1level=generalstructure.downstream1level
            if "downstream1level" in generalstructure.index
            else np.nan,
            downstream2width=generalstructure.downstream2width
            if "downstream2width" in generalstructure.index
            else np.nan,
            downstream2level=generalstructure.downstream2level
            if "downstream2level" in generalstructure.index
            else np.nan,
            gateloweredgelevel=generalstructure.gateloweredgelevel
            if "gateloweredgelevel" in generalstructure.index
            else np.nan,
            posfreegateflowcoeff=generalstructure.posfreegateflowcoeff
            if "posfreegateflowcoeff" in generalstructure.index
            else np.nan,
            posdrowngateflowcoeff=generalstructure.posdrowngateflowcoeff
            if "posdrowngateflowcoeff" in generalstructure.index
            else np.nan,
            posfreeweirflowcoeff=generalstructure.posfreeweirflowcoeff
            if "posfreeweirflowcoeff" in generalstructure.index
            else np.nan,
            posdrownweirflowcoeff=generalstructure.posdrownweirflowcoeff
            if "posdrownweirflowcoeff" in generalstructure.index
            else np.nan,
            poscontrcoeffreegate=generalstructure.poscontrcoeffreegate
            if "poscontrcoeffreegate" in generalstructure.index
            else np.nan,
            negfreegateflowcoeff=generalstructure.negfreegateflowcoeff
            if "negfreegateflowcoeff" in generalstructure.index
            else np.nan,
            negdrowngateflowcoeff=generalstructure.negdrowngateflowcoeff
            if "negdrowngateflowcoeff" in generalstructure.index
            else np.nan,
            negfreeweirflowcoeff=generalstructure.negfreeweirflowcoeff
            if "negfreeweirflowcoeff" in generalstructure.index
            else np.nan,
            negdrownweirflowcoeff=generalstructure.negdrownweirflowcoeff
            if "negdrownweirflowcoeff" in generalstructure.index
            else np.nan,
            negcontrcoeffreegate=generalstructure.negcontrcoeffreegate
            if "negcontrcoeffreegate" in generalstructure.index
            else np.nan,
            extraresistance=generalstructure.extraresistance
            if "extraresistance" in generalstructure.index
            else np.nan,
            gateheight=generalstructure.gateheight
            if "gateheight" in generalstructure.index
            else np.nan,
            gateopeningwidth=generalstructure.gateopeningwidth
            if "gateopeningwidth" in generalstructure.index
            else np.nan,
            gateopeninghorizontaldirection=generalstructure.gateopeninghorizontaldirection
            if "gateopeninghorizontaldirection" in generalstructure.index
            else np.nan,
            usevelocityheight=generalstructure.usevelocityheight
            if "usevelocityheight" in generalstructure.index
            else np.nan,
        )
move_structure(struc: str, struc_dict: dict[str, dict[str, str | float]], branch: str, offset: float) -> dict[str, dict[str, str | float]] staticmethod

Move a structure to the location of the first structure of its compound, in place.

Parameters

struc : str Id of the structure to move. struc_dict : dict All structures of one type, by id. branch : str Branch id of the first structure in the compound. offset : float Chainage of the first structure in the compound.

Returns

dict struc_dict, with the moved structure.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@staticmethod
def move_structure(
    struc: str,
    struc_dict: dict[str, dict[str, str | float]],
    branch: str,
    offset: float,
) -> dict[str, dict[str, str | float]]:
    """Move a structure to the location of the first structure of its compound, in place.

    Parameters
    ----------
    struc : str
        Id of the structure to move.
    struc_dict : dict
        All structures of one type, by id.
    branch : str
        Branch id of the first structure in the compound.
    offset : float
        Chainage of the first structure in the compound.

    Returns
    -------
    dict
        ``struc_dict``, with the moved structure.
    """
    branch2 = struc_dict[struc]["branchid"]
    if branch2 != branch:
        logger.warning(
            f"Structures of not on the same branche. Moving structure {struc} to branch {branch}."
        )
    struc_dict[struc]["branchid"] = branch
    struc_dict[struc]["chainage"] = offset
    return struc_dict
orifices_from_datamodel(orifices: pd.DataFrame) -> None

Add orifices from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def orifices_from_datamodel(self, orifices: pd.DataFrame) -> None:
    """Add orifices from a parsed data model (legacy from delft3dfmpy, untested)."""
    for orifice_idx, orifice in orifices.iterrows():
        base = self._common_structure_kwargs(orifice)
        self.structures.add_orifice(
            **base,
            allowedflowdir="both",
            crestlevel=orifice.crestlevel,
            crestwidth=orifice.crestwidth,
            gateloweredgelevel=orifice.gateloweredgelevel,
            corrcoeff=orifice.corrcoef,
            uselimitflowpos=orifice.uselimitflowpos,
            limitflowpos=orifice.limitflowpos,
            uselimitflowneg=orifice.uselimitflowneg,
            limitflowneg=orifice.limitflowneg,
        )
pumps(pumpstations: ExtendedGeoDataFrame, pumps: ExtendedDataFrame | None = None, management: ExtendedDataFrame | None = None) -> None

Add the DAMO pumps.

A pump station with more than one pump becomes a compound structure.

Parameters

pumpstations : ExtendedGeoDataFrame DAMO pump stations (gemaal). pumps : ExtendedDataFrame DAMO pumps (pomp). Required. management : ExtendedDataFrame DAMO control (sturing). Required.

Raises

ValueError If pumps or management is missing.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def pumps(
    self,
    pumpstations: ExtendedGeoDataFrame,
    pumps: ExtendedDataFrame | None = None,
    management: ExtendedDataFrame | None = None,
) -> None:
    """Add the DAMO pumps.

    A pump station with more than one pump becomes a compound structure.

    Parameters
    ----------
    pumpstations : ExtendedGeoDataFrame
        DAMO pump stations (gemaal).
    pumps : ExtendedDataFrame
        DAMO pumps (pomp). Required.
    management : ExtendedDataFrame
        DAMO control (sturing). Required.

    Raises
    ------
    ValueError
        If ``pumps`` or ``management`` is missing.
    """
    pump_pumpstation = DamoRelations.PUMP_PUMPSTATION
    management_pump = DamoRelations.MANAGEMENT_PUMP
    if pumps is None or management is None:
        raise ValueError("pumps and management are required.")

    # Add sturing to pumps
    for pumpstation in pumpstations.itertuples():
        pumpstation_rows = pumpstations.loc[[pumpstation.Index]]

        # find pumps for gemaal
        pumps_subset = pump_pumpstation.children_of(pumpstation_rows, pumps)
        if pumps_subset.empty:
            logger.warning(
                "Skipping %s because there is no associated pump.",
                pumpstation.code,
            )
            continue

        # the name, or the code when there is none
        if "naam" in pumpstations.columns and pd.notna(pumpstation.naam):
            name = str(pumpstation.naam)
        else:
            name = str(pumpstation.code)
        is_compound = len(pumps_subset) > 1
        cmp_list = []
        if is_compound:
            logger.info(
                "Pumpstation %s contains %d openings. Creating a compound structure with a fictional pump for each one.",
                pumpstation.code,
                pumps_subset.shape[0],
            )

        for ipump, (pump_index, pump) in enumerate(pumps_subset.iterrows()):
            pump_rows = pumps_subset.loc[[pump_index]]
            pump_control = management_pump.children_of(
                pump_rows,
                management,
            )
            if pump_control.empty:
                if is_compound:
                    logger.warning("No management found for %s", pump.code)
                else:
                    logger.warning(
                        "Skipping %s because there is no associated management.",
                        pumpstation.code,
                    )
                continue
            if len(pump_control) > 1:
                raise ValueError(
                    f"Pump station {pumpstation.code}: expected one management row "
                    f"per pump, found {len(pump_control)}."
                )
            startlevelsuctionside = [pump_control["bovengrens"].iloc[0]]
            stoplevelsuctionside = [pump_control["ondergrens"].iloc[0]]

            if is_compound:
                pumpid = f"{pumpstation.code}_{ipump + 1}"
            else:
                pumpid = str(pumpstation.code)
            cmp_list.append(pumpid)
            self.structures.add_pump(
                id=pumpid,
                name=str(name),
                branchid=str(pumpstation.branch_id),
                chainage=pd.to_numeric(pumpstation.branch_offset),
                orientation="positive",
                numstages=1,
                controlside="suctionside",
                capacity=pump.maximalecapaciteit / 60.0,
                startlevelsuctionside=startlevelsuctionside,
                stoplevelsuctionside=stoplevelsuctionside,
                startleveldeliveryside=startlevelsuctionside,
                stopleveldeliveryside=stoplevelsuctionside,
            )

        if is_compound:
            self.structures.add_compound(
                id=f"cmp_{pumpstation.code}", structureids=cmp_list
            )
pumps_from_datamodel(pumps: pd.DataFrame) -> None

Add pumps from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def pumps_from_datamodel(self, pumps: pd.DataFrame) -> None:
    """Add pumps from a parsed data model (legacy from delft3dfmpy, untested)."""
    for pump_idx, pump in pumps.iterrows():
        base = self._common_structure_kwargs(pump)
        self.structures.add_pump(
            **base,
            orientation="positive",
            numstages=1,
            controlside=pump.controlside,
            capacity=pump.maximumcapacity,
            startlevelsuctionside=pump.startlevelsuctionside,
            stoplevelsuctionside=pump.stoplevelsuctionside,
            startleveldeliveryside=pump.startleveldeliveryside,
            stopleveldeliveryside=pump.stopleveldeliveryside,
        )
uweirs_from_datamodel(uweirs: pd.DataFrame) -> None

Add universal weirs from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def uweirs_from_datamodel(self, uweirs: pd.DataFrame) -> None:
    """Add universal weirs from a parsed data model (legacy from delft3dfmpy, untested)."""
    for uweir_idx, uweir in uweirs.iterrows():
        base = self._common_structure_kwargs(uweir)
        self.structures.add_uweir(
            **base,
            crestlevel=uweir.crestlevel,
            yvalues=uweir.yvalues,
            zvalues=uweir.zvalues,
            allowedflowdir="both",
            dischargecoeff=uweir.dischargecoeff,
        )
weirs(weirs: ExtendedGeoDataFrame | None = None, profile_groups: ExtendedDataFrame | None = None, profile_lines: ExtendedGeoDataFrame | None = None, profiles: ExtendedGeoDataFrame | None = None, opening: ExtendedDataFrame | None = None, management_device: ExtendedDataFrame | None = None, usevelocityheight: bool = True) -> None

Add the DAMO weirs as regular weirs, orifices or universal weirs.

A weir with a profile group (stuwid) becomes a universal weir. A weir whose management device has overlaatonderlaat set to "onderlaat" becomes an orifice. Other weirs become regular (rectangular) weirs. A weir with more than one opening becomes a compound structure.

Parameters

weirs : ExtendedGeoDataFrame, optional DAMO weirs (stuw). Defaults to None. profile_groups, profile_lines, profiles : optional DAMO profile groups, lines and points, for universal weirs. Default to None. opening : ExtendedDataFrame, optional DAMO openings (kunstwerkopening). Defaults to None. management_device : ExtendedDataFrame, optional DAMO management devices (regelmiddel). Defaults to None. usevelocityheight : bool, optional D-Flow FM keyword usevelocityheight. Defaults to True.

Source code in hydrolib/dhydamo/converters/hydamo2df.py
 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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def weirs(
    self,
    weirs: ExtendedGeoDataFrame | None = None,
    profile_groups: ExtendedDataFrame | None = None,
    profile_lines: ExtendedGeoDataFrame | None = None,
    profiles: ExtendedGeoDataFrame | None = None,
    opening: ExtendedDataFrame | None = None,
    management_device: ExtendedDataFrame | None = None,
    usevelocityheight: bool = True,
) -> None:
    """Add the DAMO weirs as regular weirs, orifices or universal weirs.

    A weir with a profile group (``stuwid``) becomes a universal weir. A weir whose
    management device has ``overlaatonderlaat`` set to ``"onderlaat"`` becomes an
    orifice. Other weirs become regular (rectangular) weirs. A weir with more than one
    opening becomes a compound structure.

    Parameters
    ----------
    weirs : ExtendedGeoDataFrame, optional
        DAMO weirs (stuw). Defaults to None.
    profile_groups, profile_lines, profiles : optional
        DAMO profile groups, lines and points, for universal weirs. Default to None.
    opening : ExtendedDataFrame, optional
        DAMO openings (kunstwerkopening). Defaults to None.
    management_device : ExtendedDataFrame, optional
        DAMO management devices (regelmiddel). Defaults to None.
    usevelocityheight : bool, optional
        D-Flow FM keyword ``usevelocityheight``. Defaults to True.
    """
    opening_weir = DamoRelations.OPENING_WEIR
    management_device_opening = DamoRelations.MANAGEMENT_DEVICE_OPENING
    profile_group_weir = DamoRelations.PROFILE_GROUP_WEIR
    profile_line_group = DamoRelations.PROFILE_LINE_GROUP
    profile_line = DamoRelations.PROFILE_LINE
    if weirs is None or opening is None or management_device is None:
        raise ValueError("weirs, opening and management_device are required.")
    index = np.zeros(len(weirs.code))
    if (
        profile_groups is not None
        and profile_group_weir.foreign_key in profile_groups
    ):
        index[
            np.isin(
                weirs[opening_weir.parent_key],
                np.asarray(profile_groups[profile_group_weir.foreign_key]),
            )
        ] = 1

    # The owner of each structure id. The id of an opening of a compound weir,
    # weir.code_N, can be the code of another weir.
    owners: dict[str, str] = {}
    rweirs = weirs[index == 0]
    for weir in rweirs.itertuples():
        weir_rows = rweirs.loc[[weir.Index]]
        weir_opening = opening_weir.children_of(weir_rows, opening)

        # the name, or the code when there is none
        if "naam" in weirs.columns and pd.notna(weir.naam):
            name = str(weir.naam)
        else:
            name = str(weir.code)

        if weir_opening.shape[0] > 1:
            logger.info(
                "Weir %s contains %d openings. Creating a compound structure with a fictional weir for each one.",
                weir.code,
                weir_opening.shape[0],
            )
            cmp_list = []
            for num_op, (op_index, op_row) in enumerate(weir_opening.iterrows()):
                opening_rows = weir_opening.loc[[op_index]]
                weir_mandev = management_device_opening.children_of(
                    opening_rows,
                    management_device,
                )

                if weir_mandev.empty:
                    logger.warning(
                        "Skipping opening %s (weir %s) because there is no associated management device.",
                        op_row.globalid,
                        weir.code,
                    )
                    continue
                if weir_mandev.shape[0] > 1:
                    logger.warning(
                        "Multiple management devices associated to opening %s (weir %s). Taking the first one.",
                        op_row.globalid,
                        weir.code,
                    )
                    weir_mandev = weir_mandev.iloc[[0]]

                # This weir has multiple openings, so its structure id gets an
                # enumeration suffix that is invented right here and is not
                # present anywhere in the HyDAMO data. Record it so DRTCModel
                # can later resolve a management record's regelmiddelid to
                # this structure id; see Structures.compound_weir_structure_ids
                # in core/hydamo.py.
                weir_id = f"{weir.code}_{num_op + 1}"
                self._claim_weir_id(
                    owners, weir_id, f"opening {num_op + 1} of weir {weir.code}"
                )
                self.structures.compound_weir_structure_ids[
                    str(weir_mandev["globalid"].iloc[0])
                ] = weir_id
                overlaatonderlaat = _overlaatonderlaat(weir_mandev)
                kind = (overlaatonderlaat or "").lower()
                if kind == "overlaat":
                    cmp_list.append(weir_id)
                    self.structures.add_rweir(
                        id=weir_id,
                        name=name,
                        branchid=weir.branch_id,
                        chainage=weir.branch_offset,
                        crestlevel=op_row.laagstedoorstroomhoogte,
                        crestwidth=op_row.laagstedoorstroombreedte,
                        corrcoeff=weir.afvoercoefficient,
                        allowedflowdir="both",
                        usevelocityheight=usevelocityheight,
                    )
                elif kind == "onderlaat":
                    if self._add_orifice(
                        weir_id,
                        name,
                        weir,
                        op_row,
                        weir_mandev,
                        usevelocityheight,
                        f"opening {num_op + 1} of weir {weir.code}",
                    ):
                        cmp_list.append(weir_id)
                else:
                    _warn_unknown_weir_kind(
                        f"opening {num_op + 1} of weir {weir.code}",
                        weir_mandev,
                        overlaatonderlaat,
                    )
            self.structures.add_compound(
                id=f"cmp_{weir.code}", structureids=cmp_list
            )
            # self.structures.rweirs_df.drop(weir.code)
        else:
            if weir_opening.empty:
                logger.warning(
                    "Skipping weir %s because there is no associated opening.",
                    weir.code,
                )
                continue

            weir_id = weir.code
            self._claim_weir_id(owners, weir_id, f"weir {weir.code}")
            # Unlike the compound case above, no need to record this id in
            # compound_weir_structure_ids: this weir has a single opening, so
            # its structure id is just weir.code, which
            # DRTCModel._resolve_weir_via_opening derives directly from
            # HyDAMO's static relations.
            weir_mandev = management_device_opening.children_of(
                weir_opening,
                management_device,
            )

            if weir_mandev.empty:
                logger.warning(
                    "Skipping opening %s (weir %s) because there is no associated management device.",
                    weir_opening.globalid.squeeze(),
                    weir_id,
                )
                continue
            if weir_mandev.shape[0] > 1:
                logger.warning(
                    "Multiple management devices associated to opening %s (weir %s). Taking the first one.",
                    weir_opening.globalid.squeeze(),
                    weir_id,
                )
                weir_mandev = weir_mandev.iloc[[0]]

            overlaatonderlaat = _overlaatonderlaat(weir_mandev)
            kind = (overlaatonderlaat or "").lower()

            if kind == "overlaat":
                self.structures.add_rweir(
                    id=weir_id,
                    name=name,
                    branchid=weir.branch_id,
                    chainage=weir.branch_offset,
                    crestlevel=weir_opening.laagstedoorstroomhoogte.to_numpy()[0],
                    crestwidth=weir_opening.laagstedoorstroombreedte.to_numpy()[0],
                    corrcoeff=weir.afvoercoefficient,
                    allowedflowdir="both",
                    usevelocityheight=usevelocityheight,
                )

            elif kind == "onderlaat":
                self._add_orifice(
                    weir_id,
                    name,
                    weir,
                    weir_opening.iloc[0],
                    weir_mandev,
                    usevelocityheight,
                    f"weir {weir.code}",
                )
            else:
                _warn_unknown_weir_kind(
                    f"weir {weir.code}", weir_mandev, overlaatonderlaat
                )

    uweirs = weirs[index == 1]
    for uweir in uweirs.itertuples():
        self._claim_weir_id(owners, str(uweir.code), f"weir {uweir.code}")
        uweir_rows = uweirs.loc[[uweir.Index]]
        # the name, or the code when there is none
        if "naam" in uweirs.columns and pd.notna(uweir.naam):
            name = str(uweir.naam)
        else:
            name = str(uweir.code)

        prof = pd.DataFrame()
        if (
            profiles is not None
            and profile_groups is not None
            and profile_lines is not None
            and profile_group_weir.foreign_key in profile_groups
        ):
            group = profile_group_weir.children_of(uweir_rows, profile_groups)
            line = profile_line_group.children_of(group, profile_lines)
            prof = profile_line.children_of(line, profiles)
            if not prof.empty:
                counts = len(prof.geometry.iloc[0].coords[:])
                xyz = np.vstack(prof.geometry.iloc[0].coords[:])
                length = np.r_[
                    0,
                    np.cumsum(np.hypot(np.diff(xyz[:, 0]), np.diff(xyz[:, 1]))),
                ]
                yzvalues = np.c_[length, xyz[:, -1] - np.min(xyz[:, -1])]

        if len(prof) == 0:
            # return an error it is still not found
            raise ValueError(f"{uweir.code} is not found in any cross-section.")

        if not hasattr(uweir, "laagstedoorstroomhoogte") or pd.isna(
            uweir.laagstedoorstroomhoogte
        ):
            kruinhoogte = np.min(xyz[:, -1])
        else:
            kruinhoogte = uweir.laagstedoorstroomhoogte
        self.structures.add_uweir(
            id=uweir.code,
            name=name,
            branchid=uweir.branch_id,
            chainage=uweir.branch_offset,
            crestlevel=kruinhoogte,
            dischargecoeff=uweir.afvoercoefficient,
            allowedflowdir="both",
            numlevels=counts,
            yvalues=" ".join([f"{yz[0]:7.3f}" for yz in yzvalues]),
            zvalues=" ".join([f"{yz[1]:7.3f}" for yz in yzvalues]),
        )
weirs_from_datamodel(weirs: pd.DataFrame) -> None

Add weirs from a parsed data model (legacy from delft3dfmpy, untested).

Source code in hydrolib/dhydamo/converters/hydamo2df.py
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def weirs_from_datamodel(self, weirs: pd.DataFrame) -> None:
    """Add weirs from a parsed data model (legacy from delft3dfmpy, untested)."""
    for weir_idx, weir in weirs.iterrows():
        base = self._common_structure_kwargs(weir)
        self.structures.add_weir(
            **base,
            crestlevel=weir.crestlevel,
            crestwidth=weir.crestwidth,
            corrcoeff=weir.corrcoeff,
        )