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.12.5.

Source code in hydrolib/core/dflowfm/structure/models.py
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
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.12.5](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
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 compound input as described in UM Sec.C.12.11.

Source code in hydrolib/core/dflowfm/structure/models.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
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 compound input as described in
    [UM Sec.C.12.11](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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 split_string_on_delimiter(cls, v, info)

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.12.3.

Source code in hydrolib/core/dflowfm/structure/models.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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.12.3](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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 split_string_on_delimiter(cls, 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
518
519
520
521
522
523
524
525
526
527
528
@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
507
508
509
510
511
512
513
514
515
516
@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
530
531
532
533
534
535
536
537
538
539
@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
493
494
495
496
497
498
499
500
501
502
503
504
505
@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
433
434
435
436
437
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.12.10.

Source code in hydrolib/core/dflowfm/structure/models.py
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
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.12.10](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
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
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
@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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
@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
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
@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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
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
301
302
303
304
305
306
307
308
309
310
311
312
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."

GateOpeningHorizontalDirection

Bases: StrEnum

Horizontal opening direction of gate door[s].

Source code in hydrolib/core/dflowfm/structure/models.py
790
791
792
793
794
795
796
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: 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 orifice input as described in UM Sec.C.12.9.

Source code in hydrolib/core/dflowfm/structure/models.py
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
class GeneralStructure(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 orifice input as described in
    [UM Sec.C.12.9](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.9).
    """

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

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

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

        crestwidth: Optional[str] = Field("w_s [m]", alias="crestWidth")
        crestlevel: Optional[str] = Field("z_s [m AD]", alias="crestLevel")
        crestlength: Optional[str] = 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: Optional[str] = Field("w_d1 [m]", alias="downstream1Width")
        downstream1level: Optional[str] = Field("z_d1 [m AD]", alias="downstream1Level")
        downstream2width: Optional[str] = Field("w_d2 [m]", alias="downstream2Width")
        downstream2level: Optional[str] = Field("z_d2 [m AD]", alias="downstream2Level")

        gateloweredgelevel: Optional[str] = Field(
            "Position of gate door’s lower edge [m AD]", alias="gateLowerEdgeLevel"
        )
        posfreegateflowcoeff: Optional[str] = Field(
            "Positive free gate flow corr.coeff. cgf [-]", alias="posFreeGateFlowCoeff"
        )
        posdrowngateflowcoeff: Optional[str] = Field(
            "Positive drowned gate flow corr.coeff. cgd [-]",
            alias="posDrownGateFlowCoeff",
        )
        posfreeweirflowcoeff: Optional[str] = Field(
            "Positive free weir flow corr.coeff. cwf [-]", alias="posFreeWeirFlowCoeff"
        )
        posdrownweirflowcoeff: Optional[str] = Field(
            "Positive drowned weir flow corr.coeff. cwd [-]",
            alias="posDrownWeirFlowCoeff",
        )
        poscontrcoeffreegate: Optional[str] = Field(
            "Positive gate flow contraction coefficient µgf [-]",
            alias="posContrCoefFreeGate",
        )
        negfreegateflowcoeff: Optional[str] = Field(
            "Negative free gate flow corr.coeff. cgf [-]", alias="negFreeGateFlowCoeff"
        )
        negdrowngateflowcoeff: Optional[str] = Field(
            "Negative drowned gate flow corr.coeff. cgd [-]",
            alias="negDrownGateFlowCoeff",
        )
        negfreeweirflowcoeff: Optional[str] = Field(
            "Negative free weir flow corr.coeff. cwf [-]", alias="negFreeWeirFlowCoeff"
        )
        negdrownweirflowcoeff: Optional[str] = Field(
            "Negative drowned weir flow corr.coeff. cwd [-]",
            alias="negDrownWeirFlowCoeff",
        )
        negcontrcoeffreegate: Optional[str] = Field(
            "Negative gate flow contraction coefficient mu gf [-]",
            alias="negContrCoefFreeGate",
        )
        extraresistance: Optional[str] = Field(
            "Extra resistance [-]", alias="extraResistance"
        )
        gateheight: Optional[str] = Field(None, alias="gateHeight")
        gateopeningwidth: Optional[str] = Field(
            "Opening width between gate doors [m], should be smaller than (or equal to) crestWidth",
            alias="gateOpeningWidth",
        )
        gateopeninghorizontaldirection: Optional[str] = Field(
            "Horizontal opening direction of gate door[s]. Possible values are: symmetric, fromLeft, fromRight",
            alias="gateOpeningHorizontalDirection",
        )
        usevelocityheight: Optional[str] = Field(
            "Flag indicates whether the velocity height is to be calculated or not",
            alias="useVelocityHeight",
        )

    comments: Optional[Comments] = Comments()

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

    upstream1width: Optional[float] = Field(10.0, alias="upstream1Width")
    upstream1level: Optional[float] = Field(0.0, alias="upstream1Level")
    upstream2width: Optional[float] = Field(10.0, alias="upstream2Width")
    upstream2level: Optional[float] = Field(0.0, alias="upstream2Level")

    crestwidth: Optional[float] = Field(10.0, alias="crestWidth")
    crestlevel: Optional[ForcingDataUnion] = Field(0.0, alias="crestLevel")
    crestlength: Optional[float] = Field(0.0, alias="crestLength")

    downstream1width: Optional[float] = Field(10.0, alias="downstream1Width")
    downstream1level: Optional[float] = Field(0.0, alias="downstream1Level")
    downstream2width: Optional[float] = Field(10.0, alias="downstream2Width")
    downstream2level: Optional[float] = Field(0.0, alias="downstream2Level")

    gateloweredgelevel: Optional[ForcingDataUnion] = Field(
        11.0, alias="gateLowerEdgeLevel"
    )
    posfreegateflowcoeff: Optional[float] = Field(1.0, alias="posFreeGateFlowCoeff")
    posdrowngateflowcoeff: Optional[float] = Field(1.0, alias="posDrownGateFlowCoeff")
    posfreeweirflowcoeff: Optional[float] = Field(1.0, alias="posFreeWeirFlowCoeff")
    posdrownweirflowcoeff: Optional[float] = Field(1.0, alias="posDrownWeirFlowCoeff")
    poscontrcoeffreegate: Optional[float] = Field(1.0, alias="posContrCoefFreeGate")
    negfreegateflowcoeff: Optional[float] = Field(1.0, alias="negFreeGateFlowCoeff")
    negdrowngateflowcoeff: Optional[float] = Field(1.0, alias="negDrownGateFlowCoeff")
    negfreeweirflowcoeff: Optional[float] = Field(1.0, alias="negFreeWeirFlowCoeff")
    negdrownweirflowcoeff: Optional[float] = Field(1.0, alias="negDrownWeirFlowCoeff")
    negcontrcoeffreegate: Optional[float] = Field(1.0, alias="negContrCoefFreeGate")
    extraresistance: Optional[float] = Field(0.0, alias="extraResistance")
    gateheight: Optional[float] = Field(1e10, alias="gateHeight")
    gateopeningwidth: Optional[ForcingDataUnion] = Field(0.0, alias="gateOpeningWidth")
    gateopeninghorizontaldirection: Optional[GateOpeningHorizontalDirection] = Field(
        GateOpeningHorizontalDirection.symmetric.value,
        alias="gateOpeningHorizontalDirection",
    )
    usevelocityheight: Optional[bool] = Field(True, alias="useVelocityHeight")

Comments

Bases: Comments

Comments for the GeneralStructure section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
class Comments(Structure.Comments):
    """Comments for the GeneralStructure section fields."""

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

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

    crestwidth: Optional[str] = Field("w_s [m]", alias="crestWidth")
    crestlevel: Optional[str] = Field("z_s [m AD]", alias="crestLevel")
    crestlength: Optional[str] = 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: Optional[str] = Field("w_d1 [m]", alias="downstream1Width")
    downstream1level: Optional[str] = Field("z_d1 [m AD]", alias="downstream1Level")
    downstream2width: Optional[str] = Field("w_d2 [m]", alias="downstream2Width")
    downstream2level: Optional[str] = Field("z_d2 [m AD]", alias="downstream2Level")

    gateloweredgelevel: Optional[str] = Field(
        "Position of gate door’s lower edge [m AD]", alias="gateLowerEdgeLevel"
    )
    posfreegateflowcoeff: Optional[str] = Field(
        "Positive free gate flow corr.coeff. cgf [-]", alias="posFreeGateFlowCoeff"
    )
    posdrowngateflowcoeff: Optional[str] = Field(
        "Positive drowned gate flow corr.coeff. cgd [-]",
        alias="posDrownGateFlowCoeff",
    )
    posfreeweirflowcoeff: Optional[str] = Field(
        "Positive free weir flow corr.coeff. cwf [-]", alias="posFreeWeirFlowCoeff"
    )
    posdrownweirflowcoeff: Optional[str] = Field(
        "Positive drowned weir flow corr.coeff. cwd [-]",
        alias="posDrownWeirFlowCoeff",
    )
    poscontrcoeffreegate: Optional[str] = Field(
        "Positive gate flow contraction coefficient µgf [-]",
        alias="posContrCoefFreeGate",
    )
    negfreegateflowcoeff: Optional[str] = Field(
        "Negative free gate flow corr.coeff. cgf [-]", alias="negFreeGateFlowCoeff"
    )
    negdrowngateflowcoeff: Optional[str] = Field(
        "Negative drowned gate flow corr.coeff. cgd [-]",
        alias="negDrownGateFlowCoeff",
    )
    negfreeweirflowcoeff: Optional[str] = Field(
        "Negative free weir flow corr.coeff. cwf [-]", alias="negFreeWeirFlowCoeff"
    )
    negdrownweirflowcoeff: Optional[str] = Field(
        "Negative drowned weir flow corr.coeff. cwd [-]",
        alias="negDrownWeirFlowCoeff",
    )
    negcontrcoeffreegate: Optional[str] = Field(
        "Negative gate flow contraction coefficient mu gf [-]",
        alias="negContrCoefFreeGate",
    )
    extraresistance: Optional[str] = Field(
        "Extra resistance [-]", alias="extraResistance"
    )
    gateheight: Optional[str] = Field(None, alias="gateHeight")
    gateopeningwidth: Optional[str] = Field(
        "Opening width between gate doors [m], should be smaller than (or equal to) crestWidth",
        alias="gateOpeningWidth",
    )
    gateopeninghorizontaldirection: Optional[str] = Field(
        "Horizontal opening direction of gate door[s]. Possible values are: symmetric, fromLeft, fromRight",
        alias="gateOpeningHorizontalDirection",
    )
    usevelocityheight: Optional[str] = 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.13.4.

Source code in hydrolib/core/dflowfm/structure/models.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
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.13.4](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.13.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 split_string_on_delimiter(cls, 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
315
316
317
318
319
320
321
322
323
324
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.12.7.

Source code in hydrolib/core/dflowfm/structure/models.py
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
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.12.7](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.7).
    """

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

    crestlevel: ForcingDataUnion = Field(alias="crestLevel")
    crestwidth: Optional[float] = Field(None, alias="crestWidth")
    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.12.6.

Source code in hydrolib/core/dflowfm/structure/models.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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.12.6](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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 split_string_on_delimiter(cls, 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
709
710
711
712
713
714
715
716
717
718
719
@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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
@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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
@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: INIBasedModel

Structure model.

Source code in hydrolib/core/dflowfm/structure/models.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
class Structure(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."
        polylinefile: Optional[str] = Field(
            "*.pli; Polyline geometry definition for 2D structure.",
            alias="polylinefile",
        )
        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")

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

    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.

        The Structure does not currently support raising an error on unknown keywords.
        """
        return None

    @field_validator("xcoordinates", "ycoordinates", mode="before")
    @classmethod
    def _split_to_list(cls, v, info: ValidationInfo):
        return split_string_on_delimiter(cls, v, info)

    @field_validator("type", mode="after")
    @classmethod
    def lowercase_type(cls, v: str) -> str:
        if isinstance(v, str):
            return v.lower()
        return v

    @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 (instead of num/x/yCoordinates):
        polyline_compatible_structures = dict(
            pump="Pump",
            dambreak="Dambreak",
            gate="Gate",
            weir="Weir",
            generalstructure="GeneralStructure",
        )
        polylinefile_in_model = (
            structype in polyline_compatible_structures.keys()
            and filtered_values.get("polylinefile") 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 polylinefile_in_model and coordinates_in_model:
            raise ValueError(
                "Specify location either by `num/x/yCoordinates` or `polylinefile`, but not both."
            )

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

        # Error: Some structures require coordinates_in_model, but not branchId and chainage.
        if (
            not polylinefile_in_model
            and structype in only_coordinates_structures.keys()
        ):
            if 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 polylinefile_in_model
        ):
            raise ValueError(
                "Specify location either by setting `branchId` and `chainage` or `num/x/yCoordinates` or `polylinefile` fields."
            )

        return self

    @field_validator("polylinefile", mode="before")
    @classmethod
    def resolve_polylinefile(cls, value) -> dict:
        if isinstance(value, (str, Path)):
            return DiskOnlyFileModel(filepath=Path(value))
        return 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 _exclude_fields(self) -> Set:
        # exclude the non-applicable, or unset props like coordinates or branches
        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
        exclude_set = super()._exclude_fields().union(exclude_set)
        return exclude_set

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

Comments

Bases: Comments

Comments for the Structure section fields.

Source code in hydrolib/core/dflowfm/structure/models.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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."
    polylinefile: Optional[str] = Field(
        "*.pli; Polyline geometry definition for 2D structure.",
        alias="polylinefile",
    )
    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
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
@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 (instead of num/x/yCoordinates):
    polyline_compatible_structures = dict(
        pump="Pump",
        dambreak="Dambreak",
        gate="Gate",
        weir="Weir",
        generalstructure="GeneralStructure",
    )
    polylinefile_in_model = (
        structype in polyline_compatible_structures.keys()
        and filtered_values.get("polylinefile") 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 polylinefile_in_model and coordinates_in_model:
        raise ValueError(
            "Specify location either by `num/x/yCoordinates` or `polylinefile`, but not both."
        )

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

    # Error: Some structures require coordinates_in_model, but not branchId and chainage.
    if (
        not polylinefile_in_model
        and structype in only_coordinates_structures.keys()
    ):
        if 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 polylinefile_in_model
    ):
        raise ValueError(
            "Specify location either by setting `branchId` and `chainage` or `num/x/yCoordinates` or `polylinefile` fields."
        )

    return self

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
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
@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
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
@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
1230
1231
1232
1233
1234
1235
class StructureGeneral(INIGeneral):
    """`[General]` section with structure file metadata."""

    _header: Literal["General"] = "General"
    fileversion: str = Field("3.00", 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
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
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[StructureUnion], BeforeValidator(make_list)] = []

    @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.12.2.

Source code in hydrolib/core/dflowfm/structure/models.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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.12.2](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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 split_string_on_delimiter(cls, 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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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.12.1.

Source code in hydrolib/core/dflowfm/structure/models.py
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
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.12.1](https://content.oss.deltares.nl/delft3dfm1d2d/D-Flow_FM_User_Manual_1D2D.pdf#subsection.C.12.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: Optional[float] = Field(None, alias="crestWidth")
    corrcoeff: float = Field(1.0, alias="corrCoeff")
    usevelocityheight: bool = Field(True, alias="useVelocityHeight")

    @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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
41
42
43
44
45
46
47
48
49
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