Skip to content

Structure .ini files

Structure .ini files contain the definition of hydraulic structures for a D-Flow FM model.

Generic parsing and serializing functionality comes from the generic hydrolib.core.dflowfm.ini modules.

A structures.ini file is described by the classes below.

Models

Structure models for D-Flow FM.

structure namespace for storing the contents of an FMModel's structure file.

Bridge

Bases: Structure

Bridge structure.

Hydraulic structure with type=bridge, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Bridge input as described in UM Sec.C.14.5.

Source code in hydrolib/core/dflowfm/structure/models.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
class Bridge(Structure):
    """Bridge structure.

    Hydraulic structure with `type=bridge`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Bridge input as described in
    [UM Sec.C.14.5](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.5).
    """

    class Comments(Structure.Comments):
        """Comments for the Bridge section fields."""

        type: Optional[str] = Field("Structure type; must read bridge", alias="type")
        allowedflowdir: Optional[str] = Field(
            FlowDirection.allowedvaluestext, alias="allowedFlowdir"
        )

        csdefid: Optional[str] = Field(
            "Id of Cross-Section Definition.", alias="csDefId"
        )
        shift: Optional[str] = Field(
            "Vertical shift of the cross section definition [m]. Defined positive upwards."
        )
        inletlosscoeff: Optional[str] = Field(
            "Inlet loss coefficient [-], ξ_i.",
            alias="inletLossCoeff",
        )
        outletlosscoeff: Optional[str] = Field(
            "Outlet loss coefficient [-], k.",
            alias="outletLossCoeff",
        )
        frictiontype: Optional[str] = Field(
            "Friction type, possible values are: Chezy, Manning, wallLawNikuradse, WhiteColebrook, StricklerNikuradse, Strickler, deBosBijkerk.",
            alias="frictionType",
        )
        friction: Optional[str] = Field(
            "Friction value, used in friction loss.",
            alias="friction",
        )
        length: Optional[str] = Field("Length [m], L.")

    comments: Comments = Comments()

    type: Literal["bridge"] = Field("bridge", alias="type")
    allowedflowdir: FlowDirection = Field(alias="allowedFlowdir")

    csdefid: str = Field(alias="csDefId")
    shift: float
    inletlosscoeff: float = Field(alias="inletLossCoeff")
    outletlosscoeff: float = Field(alias="outletLossCoeff")
    frictiontype: FrictionType = Field(alias="frictionType")
    friction: float
    length: float

    @field_validator("frictiontype", mode="before")
    @classmethod
    def _frictiontype_validator(cls, v) -> FrictionType:
        return enum_value_parser(v, FrictionType)

Comments

Bases: Comments

Comments for the Bridge section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Comments(Structure.Comments):
    """Comments for the Bridge section fields."""

    type: Optional[str] = Field("Structure type; must read bridge", alias="type")
    allowedflowdir: Optional[str] = Field(
        FlowDirection.allowedvaluestext, alias="allowedFlowdir"
    )

    csdefid: Optional[str] = Field(
        "Id of Cross-Section Definition.", alias="csDefId"
    )
    shift: Optional[str] = Field(
        "Vertical shift of the cross section definition [m]. Defined positive upwards."
    )
    inletlosscoeff: Optional[str] = Field(
        "Inlet loss coefficient [-], ξ_i.",
        alias="inletLossCoeff",
    )
    outletlosscoeff: Optional[str] = Field(
        "Outlet loss coefficient [-], k.",
        alias="outletLossCoeff",
    )
    frictiontype: Optional[str] = Field(
        "Friction type, possible values are: Chezy, Manning, wallLawNikuradse, WhiteColebrook, StricklerNikuradse, Strickler, deBosBijkerk.",
        alias="frictionType",
    )
    friction: Optional[str] = Field(
        "Friction value, used in friction loss.",
        alias="friction",
    )
    length: Optional[str] = Field("Length [m], L.")

Compound

Bases: Structure

Compound structure.

Hydraulic structure with type=compound, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Comput Structure input as described in UM Sec.C.14.11.

Source code in hydrolib/core/dflowfm/structure/models.py
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
class Compound(Structure):
    """Compound structure.

    Hydraulic structure with `type=compound`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Comput Structure input as described in
    [UM Sec.C.14.11](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.11).
    """

    type: Literal["compound"] = Field("compound", alias="type")
    numstructures: int = Field(alias="numStructures")
    structureids: List[str] = Field(
        alias="structureIds", json_schema_extra={"delimiter": ";"}
    )

    @field_validator("structureids", mode="before")
    @classmethod
    def _split_to_list(cls, v, info: ValidationInfo) -> List[str]:
        """Split the string on the delimiter and return a list of strings."""
        return cls.split_string_on_delimiter(v, info)

CrestWidthValidator

Bases: ABC

Validator mixin for structures with a crest width and a gate opening width.

A plain validator mixin (not an INIBasedModel itself); the concrete structures bring in Structure. Holds the shared after-validator enforcing gateOpeningWidth <= crestWidth. The fields stay declared on each concrete structure, so every structure keeps control of its own keyword order; the validator reads them via getattr so it is inert on any subclass that does not declare both fields.

Intended to be combined with a concrete structure model, e.g. class Gate(CrestWidthValidator, Structure): ....

Source code in hydrolib/core/dflowfm/structure/models.py
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
class CrestWidthValidator(ABC):
    """Validator mixin for structures with a crest width and a gate opening width.

    A plain validator mixin (not an `INIBasedModel` itself); the concrete structures
    bring in `Structure`. Holds the shared after-validator enforcing
    ``gateOpeningWidth <= crestWidth``. The fields stay declared on each concrete
    structure, so every structure keeps control of its own keyword order; the
    validator reads them via `getattr` so it is inert on any subclass that does not
    declare both fields.

    Intended to be combined with a concrete structure model, e.g.
    ``class Gate(CrestWidthValidator, Structure): ...``.
    """

    @model_validator(mode="after")
    def _validate_crestwidth_larger_than_gateopeningwidth(self):
        """Validate that gateopeningwidth <= crestwidth.

        Skips the check when either value is None or a time series.
        """
        gateopeningwidth = getattr(self, "gateopeningwidth", None)
        crestwidth = getattr(self, "crestwidth", None)

        if (
            gateopeningwidth is not None
            and crestwidth is not None
            and not isinstance(gateopeningwidth, (TimModel, ForcingModel))
            and gateopeningwidth > crestwidth
        ):
            raise ValueError(
                "`gateOpeningWidth` should be smaller than or equal to `crestWidth`."
            )
        return self

Culvert

Bases: Structure

Culvert structure.

Hydraulic structure with type=culvert, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Culvert input as described in UM Sec.C.14.3.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Culvert(Structure):
    """Culvert structure.

    Hydraulic structure with `type=culvert`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Culvert input as described in
    [UM Sec.C.14.3](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.3).
    """

    type: Literal["culvert"] = Field("culvert", alias="type")
    allowedflowdir: FlowDirection = Field(alias="allowedFlowDir")

    leftlevel: float = Field(alias="leftLevel")
    rightlevel: float = Field(alias="rightLevel")
    csdefid: str = Field(alias="csDefId")
    length: float = Field(alias="length")
    inletlosscoeff: float = Field(alias="inletLossCoeff")
    outletlosscoeff: float = Field(alias="outletLossCoeff")
    valveonoff: bool = Field(alias="valveOnOff")
    valveopeningheight: Optional[ForcingDataUnion] = Field(
        None, alias="valveOpeningHeight"
    )
    numlosscoeff: Optional[int] = Field(None, alias="numLossCoeff")
    relopening: Optional[List[float]] = Field(None, alias="relOpening")
    losscoeff: Optional[List[float]] = Field(None, alias="lossCoeff")
    bedfrictiontype: Optional[FrictionType] = Field(None, alias="bedFrictionType")
    bedfriction: Optional[float] = Field(None, alias="bedFriction")
    subtype: Optional[CulvertSubType] = Field(
        CulvertSubType.culvert.value, alias="subType"
    )
    bendlosscoeff: Optional[float] = Field(None, alias="bendLossCoeff")

    @field_validator("relopening", "losscoeff", mode="before")
    @classmethod
    def _split_to_list(cls, v, info: ValidationInfo) -> List[float]:
        return cls.split_string_on_delimiter(v, info)

    @field_validator("allowedflowdir", mode="before")
    @classmethod
    def _flowdirection_validator(cls, v) -> FlowDirection:
        return enum_value_parser(v, FlowDirection)

    @field_validator("subtype", mode="before")
    @classmethod
    def _subtype_validator(cls, v) -> CulvertSubType:
        return enum_value_parser(v, CulvertSubType)

    @field_validator("bedfrictiontype", mode="before")
    @classmethod
    def _frictiontype_validator(cls, v) -> FrictionType:
        return enum_value_parser(v, FrictionType)

    @model_validator(mode="after")
    def validate_that_valve_related_fields_are_present_for_culverts_with_valves(self):
        """Validates that valve-related fields are present when there is a valve present."""
        validate_required_fields(
            self.model_dump(),
            "valveopeningheight",
            "numlosscoeff",
            "relopening",
            "losscoeff",
            conditional_field_name="valveonoff",
            conditional_value=True,
        )
        return self

    @model_validator(mode="after")
    def validate_that_bendlosscoeff_field_is_present_for_invertedsyphons(self):
        """Validates that the bendlosscoeff value is present when dealing with inverted syphons."""
        validate_required_fields(
            self.model_dump(),
            "bendlosscoeff",
            conditional_field_name="subtype",
            conditional_value=CulvertSubType.invertedSiphon,
        )
        return self

    @model_validator(mode="after")
    def check_list_lengths(self):
        """Validates that the length of the relopening and losscoeff fields are as expected."""
        validate_correct_length(
            self.model_dump(),
            "relopening",
            "losscoeff",
            length_name="numlosscoeff",
            list_required_with_length=True,
        )
        return self

    @model_validator(mode="after")
    def validate_that_bendlosscoeff_is_not_provided_for_culverts(self):
        """Validates that the bendlosscoeff field is not provided when the subtype is a culvert."""
        validate_forbidden_fields(
            self.model_dump(),
            "bendlosscoeff",
            conditional_field_name="subtype",
            conditional_value=CulvertSubType.culvert,
        )
        return self

check_list_lengths()

Validates that the length of the relopening and losscoeff fields are as expected.

Source code in hydrolib/core/dflowfm/structure/models.py
629
630
631
632
633
634
635
636
637
638
639
@model_validator(mode="after")
def check_list_lengths(self):
    """Validates that the length of the relopening and losscoeff fields are as expected."""
    validate_correct_length(
        self.model_dump(),
        "relopening",
        "losscoeff",
        length_name="numlosscoeff",
        list_required_with_length=True,
    )
    return self

validate_that_bendlosscoeff_field_is_present_for_invertedsyphons()

Validates that the bendlosscoeff value is present when dealing with inverted syphons.

Source code in hydrolib/core/dflowfm/structure/models.py
618
619
620
621
622
623
624
625
626
627
@model_validator(mode="after")
def validate_that_bendlosscoeff_field_is_present_for_invertedsyphons(self):
    """Validates that the bendlosscoeff value is present when dealing with inverted syphons."""
    validate_required_fields(
        self.model_dump(),
        "bendlosscoeff",
        conditional_field_name="subtype",
        conditional_value=CulvertSubType.invertedSiphon,
    )
    return self

validate_that_bendlosscoeff_is_not_provided_for_culverts()

Validates that the bendlosscoeff field is not provided when the subtype is a culvert.

Source code in hydrolib/core/dflowfm/structure/models.py
641
642
643
644
645
646
647
648
649
650
@model_validator(mode="after")
def validate_that_bendlosscoeff_is_not_provided_for_culverts(self):
    """Validates that the bendlosscoeff field is not provided when the subtype is a culvert."""
    validate_forbidden_fields(
        self.model_dump(),
        "bendlosscoeff",
        conditional_field_name="subtype",
        conditional_value=CulvertSubType.culvert,
    )
    return self

Validates that valve-related fields are present when there is a valve present.

Source code in hydrolib/core/dflowfm/structure/models.py
604
605
606
607
608
609
610
611
612
613
614
615
616
@model_validator(mode="after")
def validate_that_valve_related_fields_are_present_for_culverts_with_valves(self):
    """Validates that valve-related fields are present when there is a valve present."""
    validate_required_fields(
        self.model_dump(),
        "valveopeningheight",
        "numlosscoeff",
        "relopening",
        "losscoeff",
        conditional_field_name="valveonoff",
        conditional_value=True,
    )
    return self

CulvertSubType

Bases: StrEnum

Enum class to store a Culvert's subType.

Source code in hydrolib/core/dflowfm/structure/models.py
544
545
546
547
548
class CulvertSubType(StrEnum):
    """Enum class to store a [Culvert][hydrolib.core.dflowfm.structure.models.Culvert]'s subType."""

    culvert = "culvert"
    invertedSiphon = "invertedSiphon"

Dambreak

Bases: Structure

Dambreak structure.

Hydraulic structure with type=dambreak, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Dambreak input as described in UM Sec.C.14.10.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Dambreak(Structure):
    """Dambreak structure.

    Hydraulic structure with `type=dambreak`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Dambreak input as described in
    [UM Sec.C.14.10](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.10).
    """

    class Comments(Structure.Comments):
        """Comments for the Dambreak section fields."""

        type: Optional[str] = Field("Structure type; must read dambreak", alias="type")
        startlocationx: Optional[str] = Field(
            "x-coordinate of breach starting point.", alias="startLocationX"
        )
        startlocationy: Optional[str] = Field(
            "y-coordinate of breach starting point.", alias="startLocationY"
        )
        algorithm: Optional[str] = Field(
            "Breach growth algorithm. Possible values are: 1 (van der Knaap (2000)), 2 (Verheij–van der Knaap (2002)), 3: Predefined time series, see dambreakLevelsAndWidths",
            alias="algorithm",
        )
        crestlevelini: Optional[str] = Field(
            "Initial breach level zcrest level [m AD].", alias="crestLevelIni"
        )
        breachwidthini: Optional[str] = Field(
            "Initial breach width B0 [m].", alias="breachWidthIni"
        )
        crestlevelmin: Optional[str] = Field(
            "Minimal breach level zmin [m AD].", alias="crestLevelMin"
        )
        t0: Optional[str] = Field("Breach start time Tstart [s].", alias="t0")
        timetobreachtomaximumdepth: Optional[str] = Field(
            "tPhase 1 [s].", alias="timeToBreachToMaximumDepth"
        )
        f1: Optional[str] = Field("Factor f1 [-]", alias="f1")
        f2: Optional[str] = Field("Factor f2 [-]", alias="f2")
        ucrit: Optional[str] = Field(
            "Critical flow velocity uc for erosion [m/s].", alias="uCrit"
        )
        waterlevelupstreamlocationx: Optional[str] = Field(
            "(optional) x-coordinate of custom upstream water level point.",
            alias="waterLevelUpstreamLocationX",
        )
        waterlevelupstreamlocationy: Optional[str] = Field(
            "(optional) y-coordinate of custom upstream water level point.",
            alias="waterLevelUpstreamLocationY",
        )
        waterleveldownstreamlocationx: Optional[str] = Field(
            "(optional) x-coordinate of custom downstream water level point.",
            alias="waterLevelDownstreamLocationX",
        )
        waterleveldownstreamlocationy: Optional[str] = Field(
            "(optional) y-coordinate of custom downstream water level point.",
            alias="waterLevelDownstreamLocationY",
        )
        waterlevelupstreamnodeid: Optional[str] = Field(
            "(optional) Node Id of custom upstream water level point.",
            alias="waterLevelUpstreamNodeId",
        )
        waterleveldownstreamnodeid: Optional[str] = Field(
            "(optional) Node Id of custom downstream water level point.",
            alias="waterLevelDownstreamNodeId",
        )
        dambreaklevelsandwidths: Optional[str] = Field(
            "(only when algorithm=3) Filename of <*.tim> file (Section C.4) containing the breach levels and widths.",
            alias="dambreakLevelsAndWidths",
        )

    comments: Comments = Comments()
    type: Literal["dambreak"] = Field("dambreak", alias="type")
    startlocationx: float = Field(alias="startLocationX")
    startlocationy: float = Field(alias="startLocationY")
    algorithm: DambreakAlgorithm = Field(alias="algorithm")

    crestlevelini: float = Field(alias="crestLevelIni")
    breachwidthini: float = Field(alias="breachWidthIni")
    crestlevelmin: float = Field(alias="crestLevelMin")
    t0: float = Field(alias="t0")
    timetobreachtomaximumdepth: float = Field(alias="timeToBreachToMaximumDepth")
    f1: float = Field(alias="f1")
    f2: float = Field(alias="f2")
    ucrit: float = Field(alias="uCrit")
    waterlevelupstreamlocationx: Optional[float] = Field(
        None, alias="waterLevelUpstreamLocationX"
    )
    waterlevelupstreamlocationy: Optional[float] = Field(
        None, alias="waterLevelUpstreamLocationY"
    )
    waterleveldownstreamlocationx: Optional[float] = Field(
        None, alias="waterLevelDownstreamLocationX"
    )
    waterleveldownstreamlocationy: Optional[float] = Field(
        None, alias="waterLevelDownstreamLocationY"
    )
    waterlevelupstreamnodeid: Optional[str] = Field(
        None, alias="waterLevelUpstreamNodeId"
    )
    waterleveldownstreamnodeid: Optional[str] = Field(
        None, alias="waterLevelDownstreamNodeId"
    )
    dambreaklevelsandwidths: Optional[ForcingDataUnion] = Field(
        None, alias="dambreakLevelsAndWidths"
    )

    @field_validator("algorithm", mode="after")
    @classmethod
    def validate_algorithm(cls, value: str) -> DambreakAlgorithm:
        """
        Validates the algorithm parameter for the dambreak structure.

        Args:
            value (int): algorithm value read from the user's input.

        Raises:
            ValueError: When the value given is not of type int.
            ValueError: When the value given is not in the range [1,3]

        Returns:
            int: Validated value.
        """
        try:
            int_value = int(value)
        except Exception:
            raise ValueError("Dambreak algorithm value should be of type int.")

        if not (0 < int_value <= 3):
            raise ValueError("Dambreak algorithm value should be 1, 2 or 3.")
        return DambreakAlgorithm(int_value)

    @field_validator("dambreaklevelsandwidths", mode="after")
    @classmethod
    def validate_dambreak_levels_and_widths(
        cls, field_value: Optional[Union[TimModel, ForcingModel]], info: ValidationInfo
    ) -> Optional[Union[TimModel, ForcingModel]]:
        """Validate dambreak levels and widths.

        Validates whether a dambreak can be created with the given dambreakLevelsAndWidths
        property. This property should be given when the algorithm value is 3.

        Args:
            field_value (Optional[Union[TimModel, ForcingModel]]): Value given for dambreakLevelsAndWidths.
            values (dict): Dictionary of values already validated (assuming algorithm is in it).

        Raises:
            ValueError: When algorithm value is not 3 and field_value has a value.

        Returns:
            Optional[Union[TimModel, ForcingModel]]: The value given for dambreakLevelsAndwidths.
        """
        # Retrieve the algorithm value (if not found use 0).
        if isinstance(info, dict):
            algorithm_value = info.get("algorithm", 0)
        else:
            algorithm_value = info.data.get("algorithm", 0)
        if field_value is not None and algorithm_value != 3:
            # dambreakLevelsAndWidths can only be set when algorithm = 3
            raise ValueError(
                f"Dambreak field dambreakLevelsAndWidths can only be set when algorithm = 3, current value: {algorithm_value}."
            )
        return field_value

    @model_validator(mode="after")
    def check_location_dambreak(self) -> "Dambreak":
        """Check location dambreak.

            - Verifies whether the location for this structure contains valid values for numCoordinates, xCoordinates and
                yCoordinates or instead is using a polyline file.
            - Verifies whether de water level location specifications are valid.

        Raises:
            ValueError: When the values dictionary does not contain valid coordinates or polyline file or when the water level location specifications are not valid.

        Returns:
            dict: Dictionary of validated values.
        """
        self._validate_waterlevel_location(
            self.model_dump(),
            "waterLevelUpstreamLocationX",
            "waterLevelUpstreamLocationY",
            "waterLevelUpstreamNodeId",
        )
        self._validate_waterlevel_location(
            self.model_dump(),
            "waterLevelDownstreamLocationX",
            "waterLevelDownstreamLocationY",
            "waterLevelDownstreamNodeId",
        )

        return self

    @staticmethod
    def _validate_waterlevel_location(values, x_key: str, y_key: str, node_key: str):
        x_is_given = values.get(x_key.lower()) is not None
        y_is_given = values.get(y_key.lower()) is not None
        node_is_given = values.get(node_key.lower()) is not None

        if not (
            (x_is_given and y_is_given and not node_is_given)
            or (node_is_given and not x_is_given and not y_is_given)
        ):
            raise ValueError(
                f"Either `{node_key}` should be specified or `{x_key}` and `{y_key}`."
            )

Comments

Bases: Comments

Comments for the Dambreak section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Comments(Structure.Comments):
    """Comments for the Dambreak section fields."""

    type: Optional[str] = Field("Structure type; must read dambreak", alias="type")
    startlocationx: Optional[str] = Field(
        "x-coordinate of breach starting point.", alias="startLocationX"
    )
    startlocationy: Optional[str] = Field(
        "y-coordinate of breach starting point.", alias="startLocationY"
    )
    algorithm: Optional[str] = Field(
        "Breach growth algorithm. Possible values are: 1 (van der Knaap (2000)), 2 (Verheij–van der Knaap (2002)), 3: Predefined time series, see dambreakLevelsAndWidths",
        alias="algorithm",
    )
    crestlevelini: Optional[str] = Field(
        "Initial breach level zcrest level [m AD].", alias="crestLevelIni"
    )
    breachwidthini: Optional[str] = Field(
        "Initial breach width B0 [m].", alias="breachWidthIni"
    )
    crestlevelmin: Optional[str] = Field(
        "Minimal breach level zmin [m AD].", alias="crestLevelMin"
    )
    t0: Optional[str] = Field("Breach start time Tstart [s].", alias="t0")
    timetobreachtomaximumdepth: Optional[str] = Field(
        "tPhase 1 [s].", alias="timeToBreachToMaximumDepth"
    )
    f1: Optional[str] = Field("Factor f1 [-]", alias="f1")
    f2: Optional[str] = Field("Factor f2 [-]", alias="f2")
    ucrit: Optional[str] = Field(
        "Critical flow velocity uc for erosion [m/s].", alias="uCrit"
    )
    waterlevelupstreamlocationx: Optional[str] = Field(
        "(optional) x-coordinate of custom upstream water level point.",
        alias="waterLevelUpstreamLocationX",
    )
    waterlevelupstreamlocationy: Optional[str] = Field(
        "(optional) y-coordinate of custom upstream water level point.",
        alias="waterLevelUpstreamLocationY",
    )
    waterleveldownstreamlocationx: Optional[str] = Field(
        "(optional) x-coordinate of custom downstream water level point.",
        alias="waterLevelDownstreamLocationX",
    )
    waterleveldownstreamlocationy: Optional[str] = Field(
        "(optional) y-coordinate of custom downstream water level point.",
        alias="waterLevelDownstreamLocationY",
    )
    waterlevelupstreamnodeid: Optional[str] = Field(
        "(optional) Node Id of custom upstream water level point.",
        alias="waterLevelUpstreamNodeId",
    )
    waterleveldownstreamnodeid: Optional[str] = Field(
        "(optional) Node Id of custom downstream water level point.",
        alias="waterLevelDownstreamNodeId",
    )
    dambreaklevelsandwidths: Optional[str] = Field(
        "(only when algorithm=3) Filename of <*.tim> file (Section C.4) containing the breach levels and widths.",
        alias="dambreakLevelsAndWidths",
    )

check_location_dambreak()

Check location dambreak.

- Verifies whether the location for this structure contains valid values for numCoordinates, xCoordinates and
    yCoordinates or instead is using a polyline file.
- Verifies whether de water level location specifications are valid.

Raises:

Type Description
ValueError

When the values dictionary does not contain valid coordinates or polyline file or when the water level location specifications are not valid.

Returns:

Name Type Description
dict Dambreak

Dictionary of validated values.

Source code in hydrolib/core/dflowfm/structure/models.py
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
@model_validator(mode="after")
def check_location_dambreak(self) -> "Dambreak":
    """Check location dambreak.

        - Verifies whether the location for this structure contains valid values for numCoordinates, xCoordinates and
            yCoordinates or instead is using a polyline file.
        - Verifies whether de water level location specifications are valid.

    Raises:
        ValueError: When the values dictionary does not contain valid coordinates or polyline file or when the water level location specifications are not valid.

    Returns:
        dict: Dictionary of validated values.
    """
    self._validate_waterlevel_location(
        self.model_dump(),
        "waterLevelUpstreamLocationX",
        "waterLevelUpstreamLocationY",
        "waterLevelUpstreamNodeId",
    )
    self._validate_waterlevel_location(
        self.model_dump(),
        "waterLevelDownstreamLocationX",
        "waterLevelDownstreamLocationY",
        "waterLevelDownstreamNodeId",
    )

    return self

validate_algorithm(value) classmethod

Validates the algorithm parameter for the dambreak structure.

Parameters:

Name Type Description Default
value int

algorithm value read from the user's input.

required

Raises:

Type Description
ValueError

When the value given is not of type int.

ValueError

When the value given is not in the range [1,3]

Returns:

Name Type Description
int DambreakAlgorithm

Validated value.

Source code in hydrolib/core/dflowfm/structure/models.py
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
@field_validator("algorithm", mode="after")
@classmethod
def validate_algorithm(cls, value: str) -> DambreakAlgorithm:
    """
    Validates the algorithm parameter for the dambreak structure.

    Args:
        value (int): algorithm value read from the user's input.

    Raises:
        ValueError: When the value given is not of type int.
        ValueError: When the value given is not in the range [1,3]

    Returns:
        int: Validated value.
    """
    try:
        int_value = int(value)
    except Exception:
        raise ValueError("Dambreak algorithm value should be of type int.")

    if not (0 < int_value <= 3):
        raise ValueError("Dambreak algorithm value should be 1, 2 or 3.")
    return DambreakAlgorithm(int_value)

validate_dambreak_levels_and_widths(field_value, info) classmethod

Validate dambreak levels and widths.

Validates whether a dambreak can be created with the given dambreakLevelsAndWidths property. This property should be given when the algorithm value is 3.

Parameters:

Name Type Description Default
field_value Optional[Union[TimModel, ForcingModel]]

Value given for dambreakLevelsAndWidths.

required
values dict

Dictionary of values already validated (assuming algorithm is in it).

required

Raises:

Type Description
ValueError

When algorithm value is not 3 and field_value has a value.

Returns:

Type Description
Optional[Union[TimModel, ForcingModel]]

Optional[Union[TimModel, ForcingModel]]: The value given for dambreakLevelsAndwidths.

Source code in hydrolib/core/dflowfm/structure/models.py
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
@field_validator("dambreaklevelsandwidths", mode="after")
@classmethod
def validate_dambreak_levels_and_widths(
    cls, field_value: Optional[Union[TimModel, ForcingModel]], info: ValidationInfo
) -> Optional[Union[TimModel, ForcingModel]]:
    """Validate dambreak levels and widths.

    Validates whether a dambreak can be created with the given dambreakLevelsAndWidths
    property. This property should be given when the algorithm value is 3.

    Args:
        field_value (Optional[Union[TimModel, ForcingModel]]): Value given for dambreakLevelsAndWidths.
        values (dict): Dictionary of values already validated (assuming algorithm is in it).

    Raises:
        ValueError: When algorithm value is not 3 and field_value has a value.

    Returns:
        Optional[Union[TimModel, ForcingModel]]: The value given for dambreakLevelsAndwidths.
    """
    # Retrieve the algorithm value (if not found use 0).
    if isinstance(info, dict):
        algorithm_value = info.get("algorithm", 0)
    else:
        algorithm_value = info.data.get("algorithm", 0)
    if field_value is not None and algorithm_value != 3:
        # dambreakLevelsAndWidths can only be set when algorithm = 3
        raise ValueError(
            f"Dambreak field dambreakLevelsAndWidths can only be set when algorithm = 3, current value: {algorithm_value}."
        )
    return field_value

DambreakAlgorithm

Bases: int, Enum

Dambreak algorithm options.

Source code in hydrolib/core/dflowfm/structure/models.py
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
class DambreakAlgorithm(int, Enum):
    """Dambreak algorithm options."""

    van_der_knaap = 1  # "van der Knaap, 2000"
    verheij_van_der_knaap = 2  # "Verheij-van der Knaap, 2002"
    timeseries = 3  # "Predefined time series, dambreakLevelsAndWidths."

    @property
    def description(self) -> str:
        """Description.

        Property to return the description of the enums defined above.
        Useful for comments in output files.

        Returns:
            str: Description for the current enum.
        """
        description_dict = dict(
            van_der_knaap="van der Knaap, 2000",
            verheij_van_der_knaap="Verheij-van der Knaap, 2002",
            timeseries="Predefined time series, dambreakLevelsAndWidths",
        )
        return description_dict[self.name]

description property

Description.

Property to return the description of the enums defined above. Useful for comments in output files.

Returns:

Name Type Description
str str

Description for the current enum.

FlowDirection

Bases: StrEnum

Flow direction of a structure.

Enum class containing the valid values for the allowedFlowDirection attribute in several subclasses of Structure.

Source code in hydrolib/core/dflowfm/structure/models.py
393
394
395
396
397
398
399
400
401
402
403
404
class FlowDirection(StrEnum):
    """Flow direction of a structure.

    Enum class containing the valid values for the allowedFlowDirection
    attribute in several subclasses of Structure.
    """

    none = "none"
    positive = "positive"
    negative = "negative"
    both = "both"
    allowedvaluestext = "Possible values: both, positive, negative, none."

Gate

Bases: CrestWidthValidator, Structure

Gate structure.

Hydraulic structure with type=gate, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Gate input as described in UM Sec.C.14.8.

Source code in hydrolib/core/dflowfm/structure/models.py
 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
class Gate(CrestWidthValidator, Structure):
    """Gate structure.

    Hydraulic structure with `type=gate`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Gate input as described in
    [UM Sec.C.14.8](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.8).
    """

    class Comments(Structure.Comments):
        """Comments for the Gate section fields."""

        type: str | None = Field("Structure type; must read gate", alias="type")
        crestwidth: str | None = Field("w_s [m].", alias="crestWidth")
        crestlevel: str | None = Field("z_s [m AD].", alias="crestLevel")
        gateloweredgelevel: str | None = Field(
            "Position of gate door’s lower edge [m AD].", alias="gateLowerEdgeLevel"
        )
        gateheight: str | None = Field(
            "Height of the gate door [m].", alias="gateHeight"
        )
        gateopeningwidth: str | None = Field(
            "Width of the gate opening [m].", alias="gateOpeningWidth"
        )
        gateopeninghorizontaldirection: str | None = Field(
            GateOpeningHorizontalDirection.allowedvaluestext,
            alias="gateOpeningHorizontalDirection",
        )

    comments: Comments = Comments()

    type: Literal["gate"] = Field("gate", alias="type")

    crestwidth: CrestWidthField = None
    crestlevel: ForcingDataUnion = Field(alias="crestLevel")

    gateloweredgelevel: ForcingDataUnion = Field(alias="gateLowerEdgeLevel")
    gateheight: ForcingDataUnion = Field(alias="gateHeight")
    gateopeningwidth: ForcingDataUnion | None = Field(0.0, alias="gateOpeningWidth")
    gateopeninghorizontaldirection: GateOpeningHorizontalDirection | None = Field(
        GateOpeningHorizontalDirection.symmetric.value,
        alias="gateOpeningHorizontalDirection",
    )

Comments

Bases: Comments

Comments for the Gate section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
class Comments(Structure.Comments):
    """Comments for the Gate section fields."""

    type: str | None = Field("Structure type; must read gate", alias="type")
    crestwidth: str | None = Field("w_s [m].", alias="crestWidth")
    crestlevel: str | None = Field("z_s [m AD].", alias="crestLevel")
    gateloweredgelevel: str | None = Field(
        "Position of gate door’s lower edge [m AD].", alias="gateLowerEdgeLevel"
    )
    gateheight: str | None = Field(
        "Height of the gate door [m].", alias="gateHeight"
    )
    gateopeningwidth: str | None = Field(
        "Width of the gate opening [m].", alias="gateOpeningWidth"
    )
    gateopeninghorizontaldirection: str | None = Field(
        GateOpeningHorizontalDirection.allowedvaluestext,
        alias="gateOpeningHorizontalDirection",
    )

GateOpeningHorizontalDirection

Bases: StrEnum

Horizontal opening direction of gate door[s].

Source code in hydrolib/core/dflowfm/structure/models.py
901
902
903
904
905
906
907
class GateOpeningHorizontalDirection(StrEnum):
    """Horizontal opening direction of gate door[s]."""

    symmetric = "symmetric"
    from_left = "fromLeft"
    from_right = "fromRight"
    allowedvaluestext = "Possible values: symmetric, fromLeft, fromRight."

GeneralStructure

Bases: CrestWidthValidator, Structure

General Structure.

Hydraulic structure with type=generalStructure, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the General Structure input as described in UM Sec.C.14.9.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class GeneralStructure(CrestWidthValidator, Structure):
    """General Structure.

    Hydraulic structure with `type=generalStructure`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the General Structure input as described in
    [UM Sec.C.14.9](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.9).
    """

    class Comments(Structure.Comments):
        """Comments for the GeneralStructure section fields."""

        type: Optional[str] = Field(
            "Structure type; must read generalStructure", alias="type"
        )
        allowedflowdir: str | None = Field(
            FlowDirection.allowedvaluestext, alias="allowedFlowDir"
        )

        upstream1width: str | None = Field("w_u1 [m]", alias="upstream1Width")
        upstream1level: str | None = Field("z_u1 [m AD]", alias="upstream1Level")
        upstream2width: str | None = Field("w_u2 [m]", alias="upstream2Width")
        upstream2level: str | None = Field("z_u2 [m D]", alias="upstream2Level")

        crestwidth: str | None = Field("w_s [m]", alias="crestWidth")
        crestlevel: str | None = Field("z_s [m AD]", alias="crestLevel")
        crestlength: str | None = Field(
            "The crest length across the general structure [m]. When the crest length > 0, the extra resistance for this structure will be ls * g/(C2 * waterdepth)",
            alias="crestLength",
        )

        downstream1width: str | None = Field("w_d1 [m]", alias="downstream1Width")
        downstream1level: str | None = Field("z_d1 [m AD]", alias="downstream1Level")
        downstream2width: str | None = Field("w_d2 [m]", alias="downstream2Width")
        downstream2level: str | None = Field("z_d2 [m AD]", alias="downstream2Level")

        gateloweredgelevel: str | None = Field(
            "Position of gate door’s lower edge [m AD]", alias="gateLowerEdgeLevel"
        )
        posfreegateflowcoeff: str | None = Field(
            "Positive free gate flow corr.coeff. cgf [-]", alias="posFreeGateFlowCoeff"
        )
        posdrowngateflowcoeff: str | None = Field(
            "Positive drowned gate flow corr.coeff. cgd [-]",
            alias="posDrownGateFlowCoeff",
        )
        posfreeweirflowcoeff: str | None = Field(
            "Positive free weir flow corr.coeff. cwf [-]", alias="posFreeWeirFlowCoeff"
        )
        posdrownweirflowcoeff: str | None = Field(
            "Positive drowned weir flow corr.coeff. cwd [-]",
            alias="posDrownWeirFlowCoeff",
        )
        poscontrcoeffreegate: str | None = Field(
            "Positive gate flow contraction coefficient µgf [-]",
            alias="posContrCoefFreeGate",
        )
        negfreegateflowcoeff: str | None = Field(
            "Negative free gate flow corr.coeff. cgf [-]", alias="negFreeGateFlowCoeff"
        )
        negdrowngateflowcoeff: str | None = Field(
            "Negative drowned gate flow corr.coeff. cgd [-]",
            alias="negDrownGateFlowCoeff",
        )
        negfreeweirflowcoeff: str | None = Field(
            "Negative free weir flow corr.coeff. cwf [-]", alias="negFreeWeirFlowCoeff"
        )
        negdrownweirflowcoeff: str | None = Field(
            "Negative drowned weir flow corr.coeff. cwd [-]",
            alias="negDrownWeirFlowCoeff",
        )
        negcontrcoeffreegate: str | None = Field(
            "Negative gate flow contraction coefficient mu gf [-]",
            alias="negContrCoefFreeGate",
        )
        extraresistance: str | None = Field(
            "Extra resistance [-]", alias="extraResistance"
        )
        gateheightintervalcntrl: str | None = Field(
            "Legacy general structure keyword, read and stored by the kernel but not used in the computation.",
            alias="gateheightintervalcntrl",
        )
        dynstructext: str | None = Field(
            "Legacy general structure keyword scaling the dynamic structure time step; kernel default is 1.0.",
            alias="dynstructext",
        )
        gateheight: str | None = Field(None, alias="gateHeight")
        gateopeningwidth: str | None = Field(
            "Opening width between gate doors [m], should be smaller than (or equal to) crestWidth",
            alias="gateOpeningWidth"
        )
        gateopeninghorizontaldirection: str | None = Field(
            GateOpeningHorizontalDirection.allowedvaluestext,
            alias="gateOpeningHorizontalDirection",
        )
        usevelocityheight: str | None = Field(
            "Flag indicates whether the velocity height is to be calculated or not",
            alias="useVelocityHeight",
        )

    comments: Comments | None = Comments()

    type: Literal["generalStructure"] = Field("generalStructure", alias="type")
    allowedflowdir: FlowDirection | None = Field(
        FlowDirection.both.value, alias="allowedFlowDir"
    )

    upstream1width: float | None = Field(10.0, alias="upstream1Width")
    upstream1level: float | None = Field(0.0, alias="upstream1Level")
    upstream2width: float | None = Field(10.0, alias="upstream2Width")
    upstream2level: float | None = Field(0.0, alias="upstream2Level")

    crestwidth: CrestWidthField = 10.0
    crestlevel: ForcingDataUnion | None = Field(0.0, alias="crestLevel")
    crestlength: float | None = Field(0.0, alias="crestLength")

    downstream1width: float | None = Field(10.0, alias="downstream1Width")
    downstream1level: float | None = Field(0.0, alias="downstream1Level")
    downstream2width: float | None = Field(10.0, alias="downstream2Width")
    downstream2level: float | None = Field(0.0, alias="downstream2Level")

    posfreegateflowcoeff: float | None = Field(1.0, alias="posFreeGateFlowCoeff")
    posdrowngateflowcoeff: float | None = Field(1.0, alias="posDrownGateFlowCoeff")
    posfreeweirflowcoeff: float | None = Field(1.0, alias="posFreeWeirFlowCoeff")
    posdrownweirflowcoeff: float | None = Field(1.0, alias="posDrownWeirFlowCoeff")
    poscontrcoeffreegate: float | None = Field(1.0, alias="posContrCoefFreeGate")
    negfreegateflowcoeff: float | None = Field(1.0, alias="negFreeGateFlowCoeff")
    negdrowngateflowcoeff: float | None = Field(1.0, alias="negDrownGateFlowCoeff")
    negfreeweirflowcoeff: float | None = Field(1.0, alias="negFreeWeirFlowCoeff")
    negdrownweirflowcoeff: float | None = Field(1.0, alias="negDrownWeirFlowCoeff")
    negcontrcoeffreegate: float | None = Field(1.0, alias="negContrCoefFreeGate")
    extraresistance: float | None = Field(0.0, alias="extraResistance")
    dynstructext: float | None = Field(None, alias="dynstructext")

    gateloweredgelevel: ForcingDataUnion | None = Field(11.0, alias="gateLowerEdgeLevel")
    gateheightintervalcntrl: float | None = Field(
        None, alias="gateheightintervalcntrl"
    )
    gateheight: float | None = Field(1e10, alias="gateHeight")
    gateopeningwidth: ForcingDataUnion | None = Field(0.0, alias="gateOpeningWidth")
    gateopeninghorizontaldirection: GateOpeningHorizontalDirection | None = Field(
        GateOpeningHorizontalDirection.symmetric.value,
        alias="gateOpeningHorizontalDirection",
    )
    usevelocityheight: bool | None = Field(True, alias="useVelocityHeight")

    @model_validator(mode="before")
    @classmethod
    def _rename_legacy_coefficients(cls, values: Any) -> Any:
        """Accept the legacy underscored spelling of the flow coefficient keywords.

        Older structure files separate the `pos`/`neg` prefix of the general structure
        flow coefficients with an underscore (e.g. `pos_freegateflowcoeff`,
        `neg_contrcoeffreegate`), while the current D-Flow FM input specification
        spells them without one (`posFreeGateFlowCoeff`, `negContrCoefFreeGate`).

        Args:
            values (Any): The raw input for this structure block, normally the
                flattened `[Structure]` section as a dict.

        Returns:
            Any: The input with the coefficient keywords, and their comments, renamed.
        """
        values = cls._convert_section_to_dict(values)
        return cls._rename_legacy_keys(values, _LEGACY_COEFFICIENT_KEYWORDS)

Comments

Bases: Comments

Comments for the GeneralStructure section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Comments(Structure.Comments):
    """Comments for the GeneralStructure section fields."""

    type: Optional[str] = Field(
        "Structure type; must read generalStructure", alias="type"
    )
    allowedflowdir: str | None = Field(
        FlowDirection.allowedvaluestext, alias="allowedFlowDir"
    )

    upstream1width: str | None = Field("w_u1 [m]", alias="upstream1Width")
    upstream1level: str | None = Field("z_u1 [m AD]", alias="upstream1Level")
    upstream2width: str | None = Field("w_u2 [m]", alias="upstream2Width")
    upstream2level: str | None = Field("z_u2 [m D]", alias="upstream2Level")

    crestwidth: str | None = Field("w_s [m]", alias="crestWidth")
    crestlevel: str | None = Field("z_s [m AD]", alias="crestLevel")
    crestlength: str | None = Field(
        "The crest length across the general structure [m]. When the crest length > 0, the extra resistance for this structure will be ls * g/(C2 * waterdepth)",
        alias="crestLength",
    )

    downstream1width: str | None = Field("w_d1 [m]", alias="downstream1Width")
    downstream1level: str | None = Field("z_d1 [m AD]", alias="downstream1Level")
    downstream2width: str | None = Field("w_d2 [m]", alias="downstream2Width")
    downstream2level: str | None = Field("z_d2 [m AD]", alias="downstream2Level")

    gateloweredgelevel: str | None = Field(
        "Position of gate door’s lower edge [m AD]", alias="gateLowerEdgeLevel"
    )
    posfreegateflowcoeff: str | None = Field(
        "Positive free gate flow corr.coeff. cgf [-]", alias="posFreeGateFlowCoeff"
    )
    posdrowngateflowcoeff: str | None = Field(
        "Positive drowned gate flow corr.coeff. cgd [-]",
        alias="posDrownGateFlowCoeff",
    )
    posfreeweirflowcoeff: str | None = Field(
        "Positive free weir flow corr.coeff. cwf [-]", alias="posFreeWeirFlowCoeff"
    )
    posdrownweirflowcoeff: str | None = Field(
        "Positive drowned weir flow corr.coeff. cwd [-]",
        alias="posDrownWeirFlowCoeff",
    )
    poscontrcoeffreegate: str | None = Field(
        "Positive gate flow contraction coefficient µgf [-]",
        alias="posContrCoefFreeGate",
    )
    negfreegateflowcoeff: str | None = Field(
        "Negative free gate flow corr.coeff. cgf [-]", alias="negFreeGateFlowCoeff"
    )
    negdrowngateflowcoeff: str | None = Field(
        "Negative drowned gate flow corr.coeff. cgd [-]",
        alias="negDrownGateFlowCoeff",
    )
    negfreeweirflowcoeff: str | None = Field(
        "Negative free weir flow corr.coeff. cwf [-]", alias="negFreeWeirFlowCoeff"
    )
    negdrownweirflowcoeff: str | None = Field(
        "Negative drowned weir flow corr.coeff. cwd [-]",
        alias="negDrownWeirFlowCoeff",
    )
    negcontrcoeffreegate: str | None = Field(
        "Negative gate flow contraction coefficient mu gf [-]",
        alias="negContrCoefFreeGate",
    )
    extraresistance: str | None = Field(
        "Extra resistance [-]", alias="extraResistance"
    )
    gateheightintervalcntrl: str | None = Field(
        "Legacy general structure keyword, read and stored by the kernel but not used in the computation.",
        alias="gateheightintervalcntrl",
    )
    dynstructext: str | None = Field(
        "Legacy general structure keyword scaling the dynamic structure time step; kernel default is 1.0.",
        alias="dynstructext",
    )
    gateheight: str | None = Field(None, alias="gateHeight")
    gateopeningwidth: str | None = Field(
        "Opening width between gate doors [m], should be smaller than (or equal to) crestWidth",
        alias="gateOpeningWidth"
    )
    gateopeninghorizontaldirection: str | None = Field(
        GateOpeningHorizontalDirection.allowedvaluestext,
        alias="gateOpeningHorizontalDirection",
    )
    usevelocityheight: str | None = Field(
        "Flag indicates whether the velocity height is to be calculated or not",
        alias="useVelocityHeight",
    )

LongCulvert

Bases: Structure

Long Culvert structure.

Hydraulic structure with type=longCulvert, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Long Culvert input as described in UM Sec.C.14.4.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class LongCulvert(Structure):
    """Long Culvert structure.

    Hydraulic structure with `type=longCulvert`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Long Culvert input as described in
    [UM Sec.C.14.4](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.4).
    """

    type: Literal["longCulvert"] = Field("longCulvert", alias="type")
    allowedflowdir: Optional[FlowDirection] = Field(None, alias="allowedFlowDir")
    zcoordinates: Optional[List[float]] = Field(None, alias="zCoordinates")

    width: float = Field(alias="width")
    height: float = Field(alias="height")
    frictiontype: FrictionType = Field(alias="frictionType")
    frictionvalue: float = Field(alias="frictionValue")
    valverelativeopening: float = Field(alias="valveRelativeOpening")
    csdefid: Optional[str] = Field(None, alias="csDefId")

    @field_validator("frictiontype", mode="before")
    @classmethod
    def _frictiontype_validator(cls, v) -> FrictionType:
        return enum_value_parser(v, FrictionType)

    @field_validator("allowedflowdir", mode="before")
    @classmethod
    def _flowdirection_validator(cls, v) -> FlowDirection:
        return enum_value_parser(v, FlowDirection)

    @field_validator("zcoordinates", mode="before")
    @classmethod
    def _split_to_list(cls, v, info: ValidationInfo) -> List[float]:
        return cls.split_string_on_delimiter(v, info)

    @field_validator("zcoordinates", mode="after")
    @classmethod
    def _validate_zcoordinates(cls, v, values: ValidationInfo):
        if v is None:
            return v
        num_coordinates = values.data.get("numcoordinates")
        if len(v) != num_coordinates:
            raise ValueError(
                f"Expected {num_coordinates} z-coordinates, but got {len(v)}."
            )

        return v

Orientation

Bases: StrEnum

Orientation of a structure.

Enum class containing the valid values for the orientation attribute in several subclasses of Structure.

Source code in hydrolib/core/dflowfm/structure/models.py
407
408
409
410
411
412
413
414
415
416
class Orientation(StrEnum):
    """Orientation of a structure.

    Enum class containing the valid values for the orientation
    attribute in several subclasses of Structure.
    """

    positive = "positive"
    negative = "negative"
    allowedvaluestext = "Possible values: positive, negative."

Orifice

Bases: Structure

Orifice structure.

Hydraulic structure with type=orifice, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Orifice input as described in UM Sec.C.14.7.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Orifice(Structure):
    """Orifice structure.

    Hydraulic structure with `type=orifice`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Orifice input as described in
    [UM Sec.C.14.7](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.7).
    """

    type: Literal["orifice"] = Field("orifice", alias="type")
    allowedflowdir: Optional[FlowDirection] = Field(
        FlowDirection.both.value, alias="allowedFlowDir"
    )

    crestlevel: ForcingDataUnion = Field(alias="crestLevel")
    crestwidth: CrestWidthField = None
    gateloweredgelevel: ForcingDataUnion = Field(alias="gateLowerEdgeLevel")
    corrcoeff: float = Field(1.0, alias="corrCoeff")
    usevelocityheight: bool = Field(True, alias="useVelocityHeight")

    uselimitflowpos: Optional[bool] = Field(False, alias="useLimitFlowPos")
    limitflowpos: Optional[float] = Field(None, alias="limitFlowPos")

    uselimitflowneg: Optional[bool] = Field(False, alias="useLimitFlowNeg")
    limitflowneg: Optional[float] = Field(None, alias="limitFlowNeg")

    @field_validator("allowedflowdir", mode="before")
    @classmethod
    def _flowdirection_validator(cls, v) -> FlowDirection:
        return enum_value_parser(v, FlowDirection)

    @model_validator(mode="after")
    def _validate_limitflowpos(self):
        if self.limitflowpos is None and self.uselimitflowpos:
            raise ValueError(
                "`limitFlowPos` should be defined when `useLimitFlowPos` is True."
            )
        if self.limitflowneg is None and self.uselimitflowneg:
            raise ValueError(
                "`limitFlowNeg` should be defined when `useLimitFlowNeg` is True."
            )
        return self

Pump

Bases: Structure

Pump structure.

Hydraulic structure with type=pump, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Pump input as described in UM Sec.C.14.6.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Pump(Structure):
    """Pump structure.

    Hydraulic structure with `type=pump`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Pump input as described in
    [UM Sec.C.14.6](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.6).
    """

    type: Literal["pump"] = Field("pump", alias="type")

    orientation: Optional[Orientation] = Field(None, alias="orientation")
    controlside: Optional[str] = Field(None, alias="controlSide")
    numstages: Optional[int] = Field(None, alias="numStages")
    capacity: ForcingDataUnion = Field(alias="capacity")

    startlevelsuctionside: Optional[List[float]] = Field(
        None, alias="startLevelSuctionSide"
    )
    stoplevelsuctionside: Optional[List[float]] = Field(
        None, alias="stopLevelSuctionSide"
    )
    startleveldeliveryside: Optional[List[float]] = Field(
        None, alias="startLevelDeliverySide"
    )
    stopleveldeliveryside: Optional[List[float]] = Field(
        None, alias="stopLevelDeliverySide"
    )
    numreductionlevels: Optional[int] = Field(None, alias="numReductionLevels")
    head: Optional[List[float]] = Field(None, alias="head")
    reductionfactor: Optional[List[float]] = Field(None, alias="reductionFactor")

    @field_validator(
        "startlevelsuctionside",
        "stoplevelsuctionside",
        "startleveldeliveryside",
        "stopleveldeliveryside",
        "head",
        "reductionfactor",
        mode="before",
    )
    @classmethod
    def _split_to_list(cls, v, info: ValidationInfo) -> List[float]:
        """Split the string on the delimiter and return a list of floats."""
        return cls.split_string_on_delimiter(v, info)

    @field_validator("orientation", mode="before")
    @classmethod
    def _orientation_validator(cls, v) -> Orientation:
        return enum_value_parser(v, Orientation)

    @model_validator(mode="after")
    def validate_that_controlside_is_provided_when_numstages_is_provided(self):
        validate_required_fields(
            self.model_dump(),
            "controlside",
            conditional_field_name="numstages",
            conditional_value=0,
            comparison_func=gt,
        )
        return self

    @classmethod
    def _check_list_lengths_suctionside(cls, values: Dict):
        """Validates that the length of the startlevelsuctionside and stoplevelsuctionside fields are as expected."""
        validate_correct_length(
            values,
            "startlevelsuctionside",
            "stoplevelsuctionside",
            length_name="numstages",
            list_required_with_length=True,
        )

    @model_validator(mode="after")
    def conditionally_check_list_lengths_suctionside(self) -> Dict:
        """Check the length of suction side list.

        Validates the length of the suction side fields, but only if there is a controlside value
        present in the values and the controlside is not equal to the deliverySide.
        """
        validate_conditionally(
            self.model_dump(),
            Pump._check_list_lengths_suctionside,
            "controlside",
            "deliverySide",
            ne,
        )
        return self

    @staticmethod
    def _check_list_lengths_deliveryside(values: Dict) -> Dict:
        """Validates that the length of the startleveldeliveryside and stopleveldeliveryside fields are as expected."""
        validate_correct_length(
            values,
            "startleveldeliveryside",
            "stopleveldeliveryside",
            length_name="numstages",
            list_required_with_length=True,
        )

    @model_validator(mode="after")
    def conditionally_check_list_lengths_deliveryside(self):
        """Check the length of deliveryside list.

        Validates the length of the delivery side fields, but only if there is a controlside value
        present in the values and the controlside is not equal to the suctionSide.
        """
        validate_conditionally(
            self.model_dump(),
            Pump._check_list_lengths_deliveryside,
            "controlside",
            "suctionSide",
            ne,
        )
        return self

    @model_validator(mode="after")
    def check_list_lengths_head_and_reductionfactor(self):
        """Validates that the lengths of the head and reductionfactor fields are as expected."""
        validate_correct_length(
            self.model_dump(),
            "head",
            "reductionfactor",
            length_name="numreductionlevels",
            list_required_with_length=True,
        )
        return self

check_list_lengths_head_and_reductionfactor()

Validates that the lengths of the head and reductionfactor fields are as expected.

Source code in hydrolib/core/dflowfm/structure/models.py
820
821
822
823
824
825
826
827
828
829
830
@model_validator(mode="after")
def check_list_lengths_head_and_reductionfactor(self):
    """Validates that the lengths of the head and reductionfactor fields are as expected."""
    validate_correct_length(
        self.model_dump(),
        "head",
        "reductionfactor",
        length_name="numreductionlevels",
        list_required_with_length=True,
    )
    return self

conditionally_check_list_lengths_deliveryside()

Check the length of deliveryside list.

Validates the length of the delivery side fields, but only if there is a controlside value present in the values and the controlside is not equal to the suctionSide.

Source code in hydrolib/core/dflowfm/structure/models.py
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
@model_validator(mode="after")
def conditionally_check_list_lengths_deliveryside(self):
    """Check the length of deliveryside list.

    Validates the length of the delivery side fields, but only if there is a controlside value
    present in the values and the controlside is not equal to the suctionSide.
    """
    validate_conditionally(
        self.model_dump(),
        Pump._check_list_lengths_deliveryside,
        "controlside",
        "suctionSide",
        ne,
    )
    return self

conditionally_check_list_lengths_suctionside()

Check the length of suction side list.

Validates the length of the suction side fields, but only if there is a controlside value present in the values and the controlside is not equal to the deliverySide.

Source code in hydrolib/core/dflowfm/structure/models.py
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
@model_validator(mode="after")
def conditionally_check_list_lengths_suctionside(self) -> Dict:
    """Check the length of suction side list.

    Validates the length of the suction side fields, but only if there is a controlside value
    present in the values and the controlside is not equal to the deliverySide.
    """
    validate_conditionally(
        self.model_dump(),
        Pump._check_list_lengths_suctionside,
        "controlside",
        "deliverySide",
        ne,
    )
    return self

Structure

Bases: CoordinateValidator, INIBasedModel

Structure model.

Source code in hydrolib/core/dflowfm/structure/models.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
class Structure(CoordinateValidator, INIBasedModel):
    """Structure model."""

    class Comments(INIBasedModel.Comments):
        """Comments for the Structure section fields."""

        id: Optional[str] = "Unique structure id (max. 256 characters)."
        name: Optional[str] = "Given name in the user interface."
        locationfile: Optional[str] = Field(
            "*.pli; Polyline geometry definition for 2D structure.",
            alias="locationFile",
        )
        branchid: Optional[str] = Field(
            "Branch on which the structure is located.", alias="branchId"
        )
        chainage: Optional[str] = "Chainage on the branch (m)."

        numcoordinates: Optional[str] = Field(
            "Number of values in xCoordinates and yCoordinates", alias="numCoordinates"
        )
        xcoordinates: Optional[str] = Field(
            "x-coordinates of the location of the structure. (number of values = numCoordinates)",
            alias="xCoordinates",
        )
        ycoordinates: Optional[str] = Field(
            "y-coordinates of the location of the structure. (number of values = numCoordinates)",
            alias="yCoordinates",
        )

    comments: Comments = Comments()

    _header: Literal["Structure"] = "Structure"

    id: str = Field("id", max_length=256, alias="id")
    name: str = Field("id", alias="name")
    type: str = Field(alias="type")

    locationfile: Optional[DiskOnlyFileModel] = Field(None, alias="locationFile")

    branchid: Optional[str] = Field(None, alias="branchId")
    chainage: Optional[float] = Field(None, alias="chainage")

    numcoordinates: Optional[int] = Field(None, alias="numCoordinates")
    xcoordinates: Optional[List[float]] = Field(None, alias="xCoordinates")
    ycoordinates: Optional[List[float]] = Field(None, alias="yCoordinates")

    _loc_coord_fields = {"numcoordinates", "xcoordinates", "ycoordinates"}
    _loc_branch_fields = {"branchid", "chainage"}
    _loc_all_fields = _loc_coord_fields | _loc_branch_fields

    @classmethod
    def _get_unknown_keyword_error_manager(cls) -> Optional[UnknownKeywordErrorManager]:
        """Get the UnknownKeywordErrorManager for this model.

        Unknown keywords are reported, so a misspelled keyword is not silently
        replaced by its default value.

        Returns:
            Optional[UnknownKeywordErrorManager]: The error manager that reports unknown keywords.
        """
        return UnknownKeywordErrorManager()

    @classmethod
    def _rename_legacy_keys(
        cls, values: Any, rename_mapping: Dict[str, List[str]]
    ) -> Any:
        """Renames old keywords, and their comments, to the currently supported keywords.

        Args:
            values (Any): The raw input for this structure block.
            rename_mapping (Dict[str, List[str]]): The current keyword with the old
                keywords that are renamed to it.

        Returns:
            Any: The input with the old keywords renamed.
        """
        values = rename_keys_for_backwards_compatibility(values, rename_mapping)
        if isinstance(values, dict):
            # The helper does not rename an unset legacy keyword, so drop it here.
            # It is not a field anymore and would be reported as an unknown keyword.
            for old_keywords in rename_mapping.values():
                for old_keyword in old_keywords:
                    if values.get(old_keyword, "") is None:
                        values.pop(old_keyword)
        if isinstance(values, dict) and isinstance(values.get("comments"), dict):
            values["comments"] = rename_keys_for_backwards_compatibility(
                values["comments"], rename_mapping
            )
        return values

    @model_validator(mode="before")
    @classmethod
    def rename_keys(cls, values: Any) -> Any:
        """Renames some old keywords to the currently supported keywords."""
        values = cls._convert_section_to_dict(values)
        return cls._rename_legacy_keys(values, {"locationfile": ["polylinefile"]})

    @model_validator(mode="after")
    def check_location(self):
        """Check location of the structure.

        Validates the location of the structure based on the given parameters for the following cases:
            - if a branchid is given, then it is expected also the chainage, otherwise numcoordinates xcoordinates
            and ycoordinates shall be expected.

        Raises:
            ValueError: When branchid or chainage values are not valid (empty strings).
            ValueError: When the number of xcoordinates and ycoordinates do not match numcoordinates.

        Returns:
            dict: Dictionary of values validated for the new structure.
        """
        values_dict = self.model_dump()

        filtered_values = {k: v for k, v in values_dict.items() if v is not None}
        structype = filtered_values.get("type", "").lower()

        if structype == "compound" or issubclass(self.__class__, Compound):
            # Compound structure does not require a location specification.
            return self

        # Backwards compatibility for old-style polylinefile input field, now
        # called locationFile (instead of num/x/yCoordinates):
        polyline_compatible_structures = dict(
            pump="Pump",
            dambreak="Dambreak",
            gate="Gate",
            weir="Weir",
            generalstructure="GeneralStructure",
        )
        locationfile_in_model = (
            structype in polyline_compatible_structures.keys()
            and filtered_values.get("locationfile") is not None
        )

        # No branchId+chainage for some structures:
        only_coordinates_structures = dict(
            longculvert="LongCulvert", dambreak="Dambreak"
        )
        coordinates_in_model = Structure.validate_coordinates_in_model(filtered_values)

        # Error: do not allow both x/y and polyline file:
        if locationfile_in_model and coordinates_in_model:
            raise ValueError(
                "Specify location either by `num/x/yCoordinates` or `locationFile`, but not both."
            )

        # Error: require x/y or polyline file:
        if (
            structype in polyline_compatible_structures
            and structype in only_coordinates_structures
            and not (coordinates_in_model or locationfile_in_model)
        ):
            raise ValueError(
                f"Specify location either by setting `num/x/yCoordinates` or `locationFile` fields for a {polyline_compatible_structures[structype]} structure."
            )

        # Error: Some structures require coordinates_in_model, but not branchId and chainage.
        if (
            not locationfile_in_model
            and structype in only_coordinates_structures
            and not coordinates_in_model
        ):
            raise ValueError(
                f"Specify location by setting `num/x/yCoordinates` for a {only_coordinates_structures[structype]} structure."
            )

        # Error: final check: at least one of x/y, branchId+chainage or polyline file must be given
        branch_and_chainage_in_model = Structure.validate_branch_and_chainage_in_model(
            filtered_values
        )

        if not (
            branch_and_chainage_in_model
            or coordinates_in_model
            or locationfile_in_model
        ):
            raise ValueError(
                "Specify location either by setting `branchId` and `chainage` or `num/x/yCoordinates` or `locationFile` fields."
            )

        return self

    @field_validator("locationfile", mode="before")
    @classmethod
    def resolve_locationfile(cls, value) -> dict:
        if isinstance(value, (str, Path)):
            return DiskOnlyFileModel(filepath=Path(value))
        return value

    @property
    def polylinefile(self) -> DiskOnlyFileModel | None:
        """Deprecated alias of `locationfile`, renamed in structure file version 3.01."""
        warnings.warn(
            "`polylinefile` is renamed to `locationfile`.",
            DeprecationWarning,
            stacklevel=2,
        )
        return self.locationfile

    @polylinefile.setter
    def polylinefile(self, value: DiskOnlyFileModel | None) -> None:
        warnings.warn(
            "`polylinefile` is renamed to `locationfile`.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.locationfile = value

    @staticmethod
    def validate_branch_and_chainage_in_model(values: dict) -> bool:
        """Validate branch and chainage in model.

        Static method to validate whether the given branchid and chainage values
        match the expectation of a new structure.

        Args:
            values (dict): Dictionary of values to be used to generate a structure.

        Raises:
            ValueError: When the value for branchid or chainage are not valid.

        Returns:
            bool: Result of valid branchid / chainage in dictionary.
        """
        branchid = values.get("branchid", None)
        if branchid is None:
            return False

        chainage = values.get("chainage", None)
        if str_is_empty_or_none(branchid) or chainage is None:
            raise ValueError(
                "A valid value for branchId and chainage is required when branchId key is specified."
            )
        return True

    @staticmethod
    def validate_coordinates_in_model(values: dict) -> bool:
        """Validate coordinates in model.

        Static method to validate whether the given values match the expectations
        of a structure to define its coordinates.

        Args:
            values (dict): Dictionary of values to be used to generate a structure.

        Raises:
            ValueError: When the given coordinates is less than 2.
            ValueError: When the given coordinates do not match in expected size.

        Returns:
            bool: Result of valid coordinates in dictionary.
        """
        searched_keys = ["numcoordinates", "xcoordinates", "ycoordinates"]
        if any(values.get(k, None) is None for k in searched_keys):
            return False

        n_coords = values["numcoordinates"]
        if n_coords < 2:
            raise ValueError(
                f"Expected at least 2 coordinates, but only {n_coords} declared."
            )

        def get_coord_len(coord: str) -> int:
            if values[coord] is None:
                return 0
            return len(values[coord])

        len_x_coords = get_coord_len("xcoordinates")
        len_y_coords = get_coord_len("ycoordinates")
        if n_coords == len_x_coords == len_y_coords:
            return True
        raise ValueError(
            f"Expected {n_coords} coordinates, given {len_x_coords} for xCoordinates and {len_y_coords} for yCoordinates."
        )

    def _inapplicable_location_fields(self) -> Set:
        """The location fields that do not apply to this structure.

        Returns:
            Set: The coordinate or branch fields that are not serialized.
        """
        if self.type == "compound":
            exclude_set = self._loc_all_fields
        elif self.branchid is not None:
            exclude_set = self._loc_coord_fields
        else:
            exclude_set = self._loc_branch_fields
        return exclude_set

    def _should_be_serialized(
        self, key: str, value: Any, save_settings: ModelSaveSettings
    ) -> bool:
        """Do not serialize the non-applicable, or unset props like coordinates or branches."""
        return (
            key not in self._inapplicable_location_fields()
            and super()._should_be_serialized(key, value, save_settings)
        )

    def _get_identifier(self, data: dict) -> Optional[str]:
        return data.get("id") or data.get("name")

polylinefile property writable

Deprecated alias of locationfile, renamed in structure file version 3.01.

Comments

Bases: Comments

Comments for the Structure section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
 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
class Comments(INIBasedModel.Comments):
    """Comments for the Structure section fields."""

    id: Optional[str] = "Unique structure id (max. 256 characters)."
    name: Optional[str] = "Given name in the user interface."
    locationfile: Optional[str] = Field(
        "*.pli; Polyline geometry definition for 2D structure.",
        alias="locationFile",
    )
    branchid: Optional[str] = Field(
        "Branch on which the structure is located.", alias="branchId"
    )
    chainage: Optional[str] = "Chainage on the branch (m)."

    numcoordinates: Optional[str] = Field(
        "Number of values in xCoordinates and yCoordinates", alias="numCoordinates"
    )
    xcoordinates: Optional[str] = Field(
        "x-coordinates of the location of the structure. (number of values = numCoordinates)",
        alias="xCoordinates",
    )
    ycoordinates: Optional[str] = Field(
        "y-coordinates of the location of the structure. (number of values = numCoordinates)",
        alias="yCoordinates",
    )

check_location()

Check location of the structure.

Validates the location of the structure based on the given parameters for the following cases
  • if a branchid is given, then it is expected also the chainage, otherwise numcoordinates xcoordinates and ycoordinates shall be expected.

Raises:

Type Description
ValueError

When branchid or chainage values are not valid (empty strings).

ValueError

When the number of xcoordinates and ycoordinates do not match numcoordinates.

Returns:

Name Type Description
dict

Dictionary of values validated for the new structure.

Source code in hydrolib/core/dflowfm/structure/models.py
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
@model_validator(mode="after")
def check_location(self):
    """Check location of the structure.

    Validates the location of the structure based on the given parameters for the following cases:
        - if a branchid is given, then it is expected also the chainage, otherwise numcoordinates xcoordinates
        and ycoordinates shall be expected.

    Raises:
        ValueError: When branchid or chainage values are not valid (empty strings).
        ValueError: When the number of xcoordinates and ycoordinates do not match numcoordinates.

    Returns:
        dict: Dictionary of values validated for the new structure.
    """
    values_dict = self.model_dump()

    filtered_values = {k: v for k, v in values_dict.items() if v is not None}
    structype = filtered_values.get("type", "").lower()

    if structype == "compound" or issubclass(self.__class__, Compound):
        # Compound structure does not require a location specification.
        return self

    # Backwards compatibility for old-style polylinefile input field, now
    # called locationFile (instead of num/x/yCoordinates):
    polyline_compatible_structures = dict(
        pump="Pump",
        dambreak="Dambreak",
        gate="Gate",
        weir="Weir",
        generalstructure="GeneralStructure",
    )
    locationfile_in_model = (
        structype in polyline_compatible_structures.keys()
        and filtered_values.get("locationfile") is not None
    )

    # No branchId+chainage for some structures:
    only_coordinates_structures = dict(
        longculvert="LongCulvert", dambreak="Dambreak"
    )
    coordinates_in_model = Structure.validate_coordinates_in_model(filtered_values)

    # Error: do not allow both x/y and polyline file:
    if locationfile_in_model and coordinates_in_model:
        raise ValueError(
            "Specify location either by `num/x/yCoordinates` or `locationFile`, but not both."
        )

    # Error: require x/y or polyline file:
    if (
        structype in polyline_compatible_structures
        and structype in only_coordinates_structures
        and not (coordinates_in_model or locationfile_in_model)
    ):
        raise ValueError(
            f"Specify location either by setting `num/x/yCoordinates` or `locationFile` fields for a {polyline_compatible_structures[structype]} structure."
        )

    # Error: Some structures require coordinates_in_model, but not branchId and chainage.
    if (
        not locationfile_in_model
        and structype in only_coordinates_structures
        and not coordinates_in_model
    ):
        raise ValueError(
            f"Specify location by setting `num/x/yCoordinates` for a {only_coordinates_structures[structype]} structure."
        )

    # Error: final check: at least one of x/y, branchId+chainage or polyline file must be given
    branch_and_chainage_in_model = Structure.validate_branch_and_chainage_in_model(
        filtered_values
    )

    if not (
        branch_and_chainage_in_model
        or coordinates_in_model
        or locationfile_in_model
    ):
        raise ValueError(
            "Specify location either by setting `branchId` and `chainage` or `num/x/yCoordinates` or `locationFile` fields."
        )

    return self

rename_keys(values) classmethod

Renames some old keywords to the currently supported keywords.

Source code in hydrolib/core/dflowfm/structure/models.py
180
181
182
183
184
185
@model_validator(mode="before")
@classmethod
def rename_keys(cls, values: Any) -> Any:
    """Renames some old keywords to the currently supported keywords."""
    values = cls._convert_section_to_dict(values)
    return cls._rename_legacy_keys(values, {"locationfile": ["polylinefile"]})

validate_branch_and_chainage_in_model(values) staticmethod

Validate branch and chainage in model.

Static method to validate whether the given branchid and chainage values match the expectation of a new structure.

Parameters:

Name Type Description Default
values dict

Dictionary of values to be used to generate a structure.

required

Raises:

Type Description
ValueError

When the value for branchid or chainage are not valid.

Returns:

Name Type Description
bool bool

Result of valid branchid / chainage in dictionary.

Source code in hydrolib/core/dflowfm/structure/models.py
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
@staticmethod
def validate_branch_and_chainage_in_model(values: dict) -> bool:
    """Validate branch and chainage in model.

    Static method to validate whether the given branchid and chainage values
    match the expectation of a new structure.

    Args:
        values (dict): Dictionary of values to be used to generate a structure.

    Raises:
        ValueError: When the value for branchid or chainage are not valid.

    Returns:
        bool: Result of valid branchid / chainage in dictionary.
    """
    branchid = values.get("branchid", None)
    if branchid is None:
        return False

    chainage = values.get("chainage", None)
    if str_is_empty_or_none(branchid) or chainage is None:
        raise ValueError(
            "A valid value for branchId and chainage is required when branchId key is specified."
        )
    return True

validate_coordinates_in_model(values) staticmethod

Validate coordinates in model.

Static method to validate whether the given values match the expectations of a structure to define its coordinates.

Parameters:

Name Type Description Default
values dict

Dictionary of values to be used to generate a structure.

required

Raises:

Type Description
ValueError

When the given coordinates is less than 2.

ValueError

When the given coordinates do not match in expected size.

Returns:

Name Type Description
bool bool

Result of valid coordinates in dictionary.

Source code in hydrolib/core/dflowfm/structure/models.py
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
@staticmethod
def validate_coordinates_in_model(values: dict) -> bool:
    """Validate coordinates in model.

    Static method to validate whether the given values match the expectations
    of a structure to define its coordinates.

    Args:
        values (dict): Dictionary of values to be used to generate a structure.

    Raises:
        ValueError: When the given coordinates is less than 2.
        ValueError: When the given coordinates do not match in expected size.

    Returns:
        bool: Result of valid coordinates in dictionary.
    """
    searched_keys = ["numcoordinates", "xcoordinates", "ycoordinates"]
    if any(values.get(k, None) is None for k in searched_keys):
        return False

    n_coords = values["numcoordinates"]
    if n_coords < 2:
        raise ValueError(
            f"Expected at least 2 coordinates, but only {n_coords} declared."
        )

    def get_coord_len(coord: str) -> int:
        if values[coord] is None:
            return 0
        return len(values[coord])

    len_x_coords = get_coord_len("xcoordinates")
    len_y_coords = get_coord_len("ycoordinates")
    if n_coords == len_x_coords == len_y_coords:
        return True
    raise ValueError(
        f"Expected {n_coords} coordinates, given {len_x_coords} for xCoordinates and {len_y_coords} for yCoordinates."
    )

StructureGeneral

Bases: INIGeneral

[General] section with structure file metadata.

Source code in hydrolib/core/dflowfm/structure/models.py
1486
1487
1488
1489
1490
1491
class StructureGeneral(INIGeneral):
    """`[General]` section with structure file metadata."""

    _header: Literal["General"] = "General"
    fileversion: str = Field("3.01", alias="fileVersion")
    filetype: Literal["structure"] = Field("structure", alias="fileType")

StructureModel

Bases: INIModel

The overall structure model that contains the contents of one structure file.

This model is typically referenced under a FMModel.geometry.structurefile[..].

Attributes:

Name Type Description
general StructureGeneral

[General] block with file metadata.

structure List[Structure]

List of [Structure] blocks for all hydraulic structures.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class StructureModel(INIModel):
    """
    The overall structure model that contains the contents of one structure file.

    This model is typically referenced under a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[..]`.

    Attributes:
        general (StructureGeneral):
            `[General]` block with file metadata.
        structure (List[Structure]):
            List of `[Structure]` blocks for all hydraulic structures.
    """

    general: StructureGeneral = StructureGeneral()
    structure: Annotated[
        List[
            Annotated[
                SerializeAsAny[StructureUnion],
                BeforeValidator(_normalize_structure_type),
            ]
        ],
        BeforeValidator(make_list),
    ] = []

    def _upgrade_fileversion_for_locationfile(self) -> None:
        """Raise the file version to 3.01 when a structure uses `locationFile`.

        `locationFile` replaced `polylineFile` in structure file version 3.01. The D-Flow
        FM kernel reads a version 1.00 file only through its old reader, which does not
        know `locationFile`, so a structure with a location file must not be written
        under an older file version.
        """
        fileversion = _parse_fileversion(self.general.fileversion)
        uses_locationfile = any(
            structure.locationfile is not None for structure in self.structure
        )
        if (
            uses_locationfile
            and fileversion is not None
            and fileversion < _LOCATIONFILE_MIN_FILEVERSION
        ):
            logger.warning(
                f"Structure file version {self.general.fileversion} is raised to 3.01, "
                "because a structure uses `locationFile` (it replaces `polylineFile` "
                "from version 3.01)."
            )
            self.general.fileversion = "3.01"

    @model_validator(mode="after")
    def _check_fileversion_for_locationfile(self):
        """Make sure the file version matches the location keyword of the structures."""
        self._upgrade_fileversion_for_locationfile()
        return self

    def _serialize(self, data: dict, save_settings: ModelSaveSettings) -> None:
        """Check the file version again before writing, because structures can be added
        to the list after the model was created."""
        self._upgrade_fileversion_for_locationfile()
        super()._serialize(data, save_settings)

    @classmethod
    def _ext(cls) -> str:
        return ".ini"

    @classmethod
    def _filename(cls) -> str:
        return "structures"

UniversalWeir

Bases: Structure

Universal Weir structure.

Hydraulic structure with type=universalWeir, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the Universal Weir input as described in UM Sec.C.14.2.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class UniversalWeir(Structure):
    """Universal Weir structure.

    Hydraulic structure with `type=universalWeir`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the Universal Weir input as described in
    [UM Sec.C.14.2](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.2).
    """

    class Comments(Structure.Comments):
        """Comments for the UniversalWeir section fields."""

        type: Optional[str] = Field(
            "Structure type; must read universalWeir", alias="type"
        )
        allowedflowdir: Optional[str] = Field(
            FlowDirection.allowedvaluestext, alias="allowedFlowdir"
        )

        numlevels: Optional[str] = Field("Number of yz-Values.", alias="numLevels")
        yvalues: Optional[str] = Field(
            "y-values of the cross section (m). (number of values = numLevels)",
            alias="yValues",
        )
        zvalues: Optional[str] = Field(
            "z-values of the cross section (m). (number of values = numLevels)",
            alias="zValues",
        )
        crestlevel: Optional[str] = Field(
            "Crest level of weir (m AD).", alias="crestLevel"
        )
        dischargecoeff: Optional[str] = Field(
            "Discharge coefficient c_e (-).", alias="dischargeCoeff"
        )

    comments: Comments = Comments()

    type: Literal["universalWeir"] = Field("universalWeir", alias="type")
    allowedflowdir: FlowDirection = Field(alias="allowedFlowDir")

    numlevels: int = Field(alias="numLevels")
    yvalues: List[float] = Field(alias="yValues")
    zvalues: List[float] = Field(alias="zValues")
    crestlevel: float = Field(alias="crestLevel")
    dischargecoeff: float = Field(alias="dischargeCoeff")

    @field_validator("yvalues", "zvalues", mode="before")
    @classmethod
    def _split_to_list(cls, v, info: ValidationInfo):
        return cls.split_string_on_delimiter(v, info)

    @field_validator("allowedflowdir", mode="before")
    @classmethod
    def _flowdirection_validator(cls, v) -> FlowDirection:
        return enum_value_parser(v, FlowDirection)

Comments

Bases: Comments

Comments for the UniversalWeir section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Comments(Structure.Comments):
    """Comments for the UniversalWeir section fields."""

    type: Optional[str] = Field(
        "Structure type; must read universalWeir", alias="type"
    )
    allowedflowdir: Optional[str] = Field(
        FlowDirection.allowedvaluestext, alias="allowedFlowdir"
    )

    numlevels: Optional[str] = Field("Number of yz-Values.", alias="numLevels")
    yvalues: Optional[str] = Field(
        "y-values of the cross section (m). (number of values = numLevels)",
        alias="yValues",
    )
    zvalues: Optional[str] = Field(
        "z-values of the cross section (m). (number of values = numLevels)",
        alias="zValues",
    )
    crestlevel: Optional[str] = Field(
        "Crest level of weir (m AD).", alias="crestLevel"
    )
    dischargecoeff: Optional[str] = Field(
        "Discharge coefficient c_e (-).", alias="dischargeCoeff"
    )

Weir

Bases: Structure

Weir structure.

Hydraulic structure with type=weir, to be included in a structure file. Typically inside the structure list of a FMModel.geometry.structurefile[0].structure[..]

All lowercased attributes match with the weir input as described in UM Sec.C.14.1.

Source code in hydrolib/core/dflowfm/structure/models.py
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
class Weir(Structure):
    """Weir structure.

    Hydraulic structure with `type=weir`, to be included in a structure file.
    Typically inside the structure list of a [FMModel][hydrolib.core.dflowfm.mdu.models.FMModel]`.geometry.structurefile[0].structure[..]`

    All lowercased attributes match with the weir input as described in
    [UM Sec.C.14.1](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.14.1).
    """

    class Comments(Structure.Comments):
        """Comments for the Weir section fields."""

        type: Optional[str] = Field("Structure type; must read weir", alias="type")
        allowedflowdir: Optional[str] = Field(
            FlowDirection.allowedvaluestext, alias="allowedFlowdir"
        )

        crestlevel: Optional[str] = Field(
            "Crest level of weir (m AD).", alias="crestLevel"
        )
        crestwidth: Optional[str] = Field("Width of the weir (m).", alias="crestWidth")
        corrcoeff: Optional[str] = Field(
            "Correction coefficient (-).", alias="corrCoeff"
        )
        usevelocityheight: Optional[str] = Field(
            "Flag indicating whether the velocity height is to be calculated or not.",
            alias="useVelocityHeight",
        )

    comments: Comments = Comments()

    type: Literal["weir"] = Field("weir", alias="type")
    allowedflowdir: Optional[FlowDirection] = Field(
        FlowDirection.both.value, alias="allowedFlowDir"
    )

    crestlevel: ForcingDataUnion = Field(alias="crestLevel")
    crestwidth: CrestWidthField = None
    corrcoeff: float = Field(1.0, alias="corrCoeff")
    usevelocityheight: bool = Field(True, alias="useVelocityHeight")

    @model_validator(mode="before")
    @classmethod
    def _rename_legacy_corrcoeff(cls, values: Any) -> Any:
        """Read the legacy `lat_contr_coeff` keyword as `corrCoeff`.

        Structure files older than version 2.01 give the weir correction coefficient as
        `lat_contr_coeff`. The manual lists it as superseded by `corrCoeff`, and the
        D-Flow FM kernel applies both keywords in the same way to a weir.

        Args:
            values (Any): The raw input for this structure block, normally the
                flattened `[Structure]` section as a dict.

        Returns:
            Any: The input with the legacy keyword renamed.
        """
        values = cls._convert_section_to_dict(values)
        return cls._rename_legacy_keys(values, {"corrcoeff": ["lat_contr_coeff"]})

    @field_validator("allowedflowdir", mode="before")
    @classmethod
    def _flowdirection_validator(cls, v) -> FlowDirection:
        return enum_value_parser(v, FlowDirection)

Comments

Bases: Comments

Comments for the Weir section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
class Comments(Structure.Comments):
    """Comments for the Weir section fields."""

    type: Optional[str] = Field("Structure type; must read weir", alias="type")
    allowedflowdir: Optional[str] = Field(
        FlowDirection.allowedvaluestext, alias="allowedFlowdir"
    )

    crestlevel: Optional[str] = Field(
        "Crest level of weir (m AD).", alias="crestLevel"
    )
    crestwidth: Optional[str] = Field("Width of the weir (m).", alias="crestWidth")
    corrcoeff: Optional[str] = Field(
        "Correction coefficient (-).", alias="corrCoeff"
    )
    usevelocityheight: Optional[str] = Field(
        "Flag indicating whether the velocity height is to be calculated or not.",
        alias="useVelocityHeight",
    )

load_model(value)

Load a model from a file path or return the value as is.

Source code in hydrolib/core/dflowfm/structure/models.py
73
74
75
76
77
78
79
80
81
def load_model(value):
    """Load a model from a file path or return the value as is."""
    if isinstance(value, (str, Path)):
        path = Path(value)
        if path.suffix == ".tim":
            return TimModel(filepath=path)
        elif path.suffix == ".bc":
            return ForcingModel(filepath=path)
    return value  # already a float, TimModel, or ForcingModel