Skip to content

Core

DHyDAMO Core API

Core model classes: HyDAMO data, the RR model and the RTC model.

data_model

HYDROLIB's data model: the HyDAMO tables, under their DAMO 2.2 names, and HYDROLIB's extensions.

Every DAMO version is loaded into this one model: the version steps (hydrolib.dhydamo.io.damo_versions.steps) rename a file's layers and columns back to DAMO 2.2. The model is plain data and independent of any DAMO version. HyDAMO.__init__ builds its tables from it.

Column dataclass

A declared column with something to say beyond its name.

Ordinary columns are declared by name only; a column is declared as a Column when HYDROLIB has a reason to note, or treats it in a special way.

Parameters

name : str The column, under its DAMO 2.2 name, or its name in the version that introduced it (see since). reason : str Why HYDROLIB needs it, or treats it this way. hydrolib_only : bool Whether the column is HYDROLIB's own: no DAMO version defines it. Default is False. fill_from_globalid : bool Whether the column is filled from globalid where it is absent or empty, before duplicates get a suffix. Default is False. rewrite : tuple[str, str], optional (old, new): a value rewritten when loading, whatever the DAMO version. Only the exact value is rewritten, so no general stripping of whitespace or commas. identity : bool Whether the column is the table's identity: its index and the id of its model objects. An empty value raises an error, duplicates get a suffix. Default is False. values : tuple[str, ...] The values the code compares the column against, as DAMO spells them. The contract test checks that each DAMO version allows them. Default is none. since : str, optional The first DAMO version with the column, e.g. "2.5", for a column DAMO added rather than renamed. Default is None: every version has it.

Source code in hydrolib/dhydamo/core/data_model.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@dataclass(frozen=True)
class Column:
    """A declared column with something to say beyond its name.

    Ordinary columns are declared by name only; a column is declared as a `Column`
    when HYDROLIB has a reason to note, or treats it in a special way.

    Parameters
    ----------
    name : str
        The column, under its DAMO 2.2 name, or its name in the version that
        introduced it (see *since*).
    reason : str
        Why HYDROLIB needs it, or treats it this way.
    hydrolib_only : bool
        Whether the column is HYDROLIB's own: no DAMO version defines it. Default is
        ``False``.
    fill_from_globalid : bool
        Whether the column is filled from ``globalid`` where it is absent or empty,
        before duplicates get a suffix. Default is ``False``.
    rewrite : tuple[str, str], optional
        ``(old, new)``: a value rewritten when loading, whatever the DAMO version.
        Only the exact value is rewritten, so no general stripping of whitespace or
        commas.
    identity : bool
        Whether the column is the table's identity: its index and the id of its model
        objects. An empty value raises an error, duplicates get a suffix. Default is
        ``False``.
    values : tuple[str, ...]
        The values the code compares the column against, as DAMO spells them. The
        contract test checks that each DAMO version allows them. Default is none.
    since : str, optional
        The first DAMO version with the column, e.g. ``"2.5"``, for a column DAMO
        added rather than renamed. Default is ``None``: every version has it.
    """

    name: str
    reason: str
    hydrolib_only: bool = False
    fill_from_globalid: bool = False
    rewrite: tuple[str, str] | None = None
    identity: bool = False
    values: tuple[str, ...] = ()
    since: str | None = None

    def in_version(self, version: str) -> bool:
        """Return whether DAMO *version* has the column (see *since*)."""
        return self.since is None or _version_key(version) >= _version_key(self.since)
in_version(version: str) -> bool

Return whether DAMO version has the column (see since).

Source code in hydrolib/dhydamo/core/data_model.py
67
68
69
def in_version(self, version: str) -> bool:
    """Return whether DAMO *version* has the column (see *since*)."""
    return self.since is None or _version_key(version) >= _version_key(self.since)

DamoRelations

The DAMO relations between the HyDAMO tables.

A DAMO foreign key holds the parent's globalid. The one exception is the parameterised-profile values, which share normgeparamprofielid with their profile, so that is the parent key.

Source code in hydrolib/dhydamo/core/data_model.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
class DamoRelations:
    """The DAMO relations between the HyDAMO tables.

    A DAMO foreign key holds the parent's ``globalid``. The one exception is the
    parameterised-profile values, which share ``normgeparamprofielid`` with their
    profile, so that is the parent key.
    """

    PROFILE_LINE = Relation(
        name="profile_line",
        child_table="profile",
        foreign_key="profiellijnid",
        parent_table="profile_line",
    )
    PROFILE_ROUGHNESS = Relation(
        name="profile_roughness",
        child_table="profile_roughness",
        foreign_key="profielpuntid",
        parent_table="profile",
    )
    PROFILE_LINE_GROUP = Relation(
        name="profile_line_group",
        child_table="profile_line",
        foreign_key="profielgroepid",
        parent_table="profile_group",
    )
    PROFILE_GROUP_BRANCH = Relation(
        name="profile_group_branch",
        child_table="profile_group",
        foreign_key="hydroobjectid",
        parent_table="branches",
    )
    PROFILE_GROUP_WEIR = Relation(
        name="profile_group_weir",
        child_table="profile_group",
        foreign_key="stuwid",
        parent_table="weirs",
    )
    PROFILE_GROUP_BRIDGE = Relation(
        name="profile_group_bridge",
        child_table="profile_group",
        foreign_key="brugid",
        parent_table="bridges",
    )
    PARAM_PROFILE_BRANCH = Relation(
        name="param_profile_branch",
        child_table="param_profile",
        foreign_key="hydroobjectid",
        parent_table="branches",
    )
    PARAM_PROFILE_VALUES = Relation(
        name="param_profile_values",
        child_table="param_profile_values",
        foreign_key="normgeparamprofielid",
        parent_table="param_profile",
        parent_key="normgeparamprofielid",
    )
    OPENING_WEIR = Relation(
        name="opening_weir",
        child_table="opening",
        foreign_key="stuwid",
        parent_table="weirs",
    )
    OPENING_MANAGEMENT_DEVICE = Relation(
        name="opening_management_device",
        child_table="opening",
        foreign_key="regelmiddelid",
        parent_table="management_device",
    )
    MANAGEMENT_DEVICE_OPENING = Relation(
        name="management_device_opening",
        child_table="management_device",
        foreign_key="kunstwerkopeningid",
        parent_table="opening",
    )
    MANAGEMENT_DEVICE_CULVERT = Relation(
        name="management_device_culvert",
        child_table="management_device",
        foreign_key="duikersifonhevelid",
        parent_table="culverts",
    )
    MANAGEMENT_DEVICE_PUMPSTATION = Relation(
        name="management_device_pumpstation",
        child_table="management_device",
        foreign_key="gemaalid",
        parent_table="pumpstations",
    )
    PUMP_PUMPSTATION = Relation(
        name="pump_pumpstation",
        child_table="pumps",
        foreign_key="gemaalid",
        parent_table="pumpstations",
    )
    MANAGEMENT_PUMP = Relation(
        name="management_pump",
        child_table="management",
        foreign_key="pompid",
        parent_table="pumps",
    )
    MANAGEMENT_DEVICE = Relation(
        name="management_device",
        child_table="management",
        foreign_key="regelmiddelid",
        parent_table="management_device",
    )
    MANAGEMENT_BOUNDARY_CONDITION = Relation(
        name="management_boundary_condition",
        child_table="management",
        foreign_key="hydrologischerandvoorwaardeid",
        parent_table="boundary_conditions",
    )
    CATCHMENT_LATERAL = Relation(
        name="catchment_lateral",
        child_table="catchments",
        foreign_key="lateraleknoopid",
        parent_table="laterals",
    )

Extension dataclass

A column HYDROLIB defines or treats on top of DAMO 2.2, from extensions.

Parameters

table : str HyDAMO attribute of the table. column : str The column. kind : ExtensionKind What HYDROLIB does with it. reason : str Why HYDROLIB needs it.

Source code in hydrolib/dhydamo/core/data_model.py
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
@dataclass(frozen=True)
class Extension:
    """A column HYDROLIB defines or treats on top of DAMO 2.2, from `extensions`.

    Parameters
    ----------
    table : str
        HyDAMO attribute of the table.
    column : str
        The column.
    kind : ExtensionKind
        What HYDROLIB does with it.
    reason : str
        Why HYDROLIB needs it.
    """

    table: str
    column: str
    kind: ExtensionKind
    reason: str

OwnRelations

The relations of HYDROLIB's own tables (OWN_TABLES), an extension.

These tables aren't DAMO and have no globalid: a child refers to its parent's code in codegerelateerdobject.

Source code in hydrolib/dhydamo/core/data_model.py
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
class OwnRelations:
    """The relations of HYDROLIB's own tables (`OWN_TABLES`), an extension.

    These tables aren't DAMO and have no ``globalid``: a child refers to its
    parent's ``code`` in ``codegerelateerdobject``.
    """

    OVERFLOW_SEWER_AREA = Relation(
        name="overflow_sewer_area",
        child_table="overflows",
        foreign_key="codegerelateerdobject",
        parent_table="sewer_areas",
        parent_key="code",
    )
    GREENHOUSE_LATERAL_AREA = Relation(
        name="greenhouse_lateral_area",
        child_table="greenhouse_laterals",
        foreign_key="codegerelateerdobject",
        parent_table="greenhouse_areas",
        parent_key="code",
    )

OwnTable dataclass

A table HYDROLIB defines itself: not DAMO, and loaded from its own files.

Parameters

geotype : type[BaseGeometry] Geometry type of the table. required_columns : tuple[str, ...] Columns the table must have. reason : str Why HYDROLIB needs it. optional_columns : tuple[Column, ...] Other columns HYDROLIB reads when present, each with its reason.

Source code in hydrolib/dhydamo/core/data_model.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
@dataclass(frozen=True)
class OwnTable:
    """A table HYDROLIB defines itself: not DAMO, and loaded from its own files.

    Parameters
    ----------
    geotype : type[BaseGeometry]
        Geometry type of the table.
    required_columns : tuple[str, ...]
        Columns the table must have.
    reason : str
        Why HYDROLIB needs it.
    optional_columns : tuple[Column, ...]
        Other columns HYDROLIB reads when present, each with its reason.
    """

    geotype: type[BaseGeometry]
    required_columns: tuple[str, ...]
    reason: str
    optional_columns: tuple[Column, ...] = ()

    @property
    def optional_names(self) -> tuple[str, ...]:
        """The names of the optional columns."""
        return tuple(column.name for column in self.optional_columns)
optional_names: tuple[str, ...] property

The names of the optional columns.

Relation dataclass

A foreign-key relation from a child table to a parent table.

Following a relation is in hydrolib.dhydamo.core.relations; the two methods here only say how its keys match.

Attributes

name : str Name of the relation, for messages. child_table : str HyDAMO attribute of the table with the foreign key. foreign_key : str Column of the child table that refers to the parent. parent_table : str HyDAMO attribute of the table that is referred to. parent_key : str Column of the parent table that is referred to. Defaults to "globalid".

Source code in hydrolib/dhydamo/core/data_model.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
@dataclass(frozen=True, slots=True)
class Relation:
    """A foreign-key relation from a child table to a parent table.

    Following a relation is in `hydrolib.dhydamo.core.relations`; the two methods
    here only say how its keys match.

    Attributes
    ----------
    name : str
        Name of the relation, for messages.
    child_table : str
        HyDAMO attribute of the table with the foreign key.
    foreign_key : str
        Column of the child table that refers to the parent.
    parent_table : str
        HyDAMO attribute of the table that is referred to.
    parent_key : str
        Column of the parent table that is referred to. Defaults to ``"globalid"``.
    """

    name: str
    child_table: str
    foreign_key: str
    parent_table: str
    parent_key: str = "globalid"

    def parents_of(
        self,
        child_rows: pd.DataFrame,
        parent_table: pd.DataFrame,
    ) -> pd.DataFrame:
        """Return parent rows referenced by one or more child rows.

        The ``of`` in ``parents_of`` refers to the first argument,
        ``child_rows``. This relation supplies the traversal metadata: values
        from its ``foreign_key`` on ``child_rows`` are matched against its
        ``parent_key`` on ``parent_table``.

        Parameters
        ----------
        child_rows : pandas.DataFrame
            One or more rows from this relation's ``child_table``. The
            relation's ``foreign_key`` must be present as a column.
        parent_table : pandas.DataFrame
            Candidate rows from this relation's ``parent_table``. The
            relation's ``parent_key`` must be present as a column.

        Returns
        -------
        pandas.DataFrame
            Rows from ``parent_table`` whose parent key is referenced by
            ``child_rows``. The original index, column order, and dataframe
            type are preserved. Null foreign-key values never match.

        Raises
        ------
        KeyError
            If ``foreign_key`` is missing from ``child_rows`` or ``parent_key``
            is missing from ``parent_table``.

        Notes
        -----
        This method does not enforce relation cardinality. It can return zero,
        one, or multiple parent rows; the caller decides how those cases are
        handled.
        """
        foreign_keys = child_rows[self.foreign_key].dropna()
        return parent_table.loc[parent_table[self.parent_key].isin(foreign_keys)]

    def children_of(
        self,
        parent_rows: pd.DataFrame,
        child_table: pd.DataFrame,
    ) -> pd.DataFrame:
        """Return child rows that reference one or more parent rows.

        The ``of`` in ``children_of`` refers to the first argument,
        ``parent_rows``. This relation supplies the traversal metadata: values
        from its ``parent_key`` on ``parent_rows`` are matched against its
        ``foreign_key`` on ``child_table``.

        Parameters
        ----------
        parent_rows : pandas.DataFrame
            One or more rows from this relation's ``parent_table``. The
            relation's ``parent_key`` must be present as a column.
        child_table : pandas.DataFrame
            Candidate rows from this relation's ``child_table``. The
            relation's ``foreign_key`` must be present as a column.

        Returns
        -------
        pandas.DataFrame
            Rows from ``child_table`` whose foreign key references
            ``parent_rows``. The original index, column order, and dataframe
            type are preserved. Null parent-key values never match.

        Raises
        ------
        KeyError
            If ``parent_key`` is missing from ``parent_rows`` or
            ``foreign_key`` is missing from ``child_table``.

        Notes
        -----
        This method does not enforce relation cardinality. It can return zero,
        one, or multiple child rows; the caller decides how those cases are
        handled.
        """
        parent_keys = parent_rows[self.parent_key].dropna()
        return child_table.loc[child_table[self.foreign_key].isin(parent_keys)]
children_of(parent_rows: pd.DataFrame, child_table: pd.DataFrame) -> pd.DataFrame

Return child rows that reference one or more parent rows.

The of in children_of refers to the first argument, parent_rows. This relation supplies the traversal metadata: values from its parent_key on parent_rows are matched against its foreign_key on child_table.

Parameters

parent_rows : pandas.DataFrame One or more rows from this relation's parent_table. The relation's parent_key must be present as a column. child_table : pandas.DataFrame Candidate rows from this relation's child_table. The relation's foreign_key must be present as a column.

Returns

pandas.DataFrame Rows from child_table whose foreign key references parent_rows. The original index, column order, and dataframe type are preserved. Null parent-key values never match.

Raises

KeyError If parent_key is missing from parent_rows or foreign_key is missing from child_table.

Notes

This method does not enforce relation cardinality. It can return zero, one, or multiple child rows; the caller decides how those cases are handled.

Source code in hydrolib/dhydamo/core/data_model.py
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
def children_of(
    self,
    parent_rows: pd.DataFrame,
    child_table: pd.DataFrame,
) -> pd.DataFrame:
    """Return child rows that reference one or more parent rows.

    The ``of`` in ``children_of`` refers to the first argument,
    ``parent_rows``. This relation supplies the traversal metadata: values
    from its ``parent_key`` on ``parent_rows`` are matched against its
    ``foreign_key`` on ``child_table``.

    Parameters
    ----------
    parent_rows : pandas.DataFrame
        One or more rows from this relation's ``parent_table``. The
        relation's ``parent_key`` must be present as a column.
    child_table : pandas.DataFrame
        Candidate rows from this relation's ``child_table``. The
        relation's ``foreign_key`` must be present as a column.

    Returns
    -------
    pandas.DataFrame
        Rows from ``child_table`` whose foreign key references
        ``parent_rows``. The original index, column order, and dataframe
        type are preserved. Null parent-key values never match.

    Raises
    ------
    KeyError
        If ``parent_key`` is missing from ``parent_rows`` or
        ``foreign_key`` is missing from ``child_table``.

    Notes
    -----
    This method does not enforce relation cardinality. It can return zero,
    one, or multiple child rows; the caller decides how those cases are
    handled.
    """
    parent_keys = parent_rows[self.parent_key].dropna()
    return child_table.loc[child_table[self.foreign_key].isin(parent_keys)]
parents_of(child_rows: pd.DataFrame, parent_table: pd.DataFrame) -> pd.DataFrame

Return parent rows referenced by one or more child rows.

The of in parents_of refers to the first argument, child_rows. This relation supplies the traversal metadata: values from its foreign_key on child_rows are matched against its parent_key on parent_table.

Parameters

child_rows : pandas.DataFrame One or more rows from this relation's child_table. The relation's foreign_key must be present as a column. parent_table : pandas.DataFrame Candidate rows from this relation's parent_table. The relation's parent_key must be present as a column.

Returns

pandas.DataFrame Rows from parent_table whose parent key is referenced by child_rows. The original index, column order, and dataframe type are preserved. Null foreign-key values never match.

Raises

KeyError If foreign_key is missing from child_rows or parent_key is missing from parent_table.

Notes

This method does not enforce relation cardinality. It can return zero, one, or multiple parent rows; the caller decides how those cases are handled.

Source code in hydrolib/dhydamo/core/data_model.py
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
def parents_of(
    self,
    child_rows: pd.DataFrame,
    parent_table: pd.DataFrame,
) -> pd.DataFrame:
    """Return parent rows referenced by one or more child rows.

    The ``of`` in ``parents_of`` refers to the first argument,
    ``child_rows``. This relation supplies the traversal metadata: values
    from its ``foreign_key`` on ``child_rows`` are matched against its
    ``parent_key`` on ``parent_table``.

    Parameters
    ----------
    child_rows : pandas.DataFrame
        One or more rows from this relation's ``child_table``. The
        relation's ``foreign_key`` must be present as a column.
    parent_table : pandas.DataFrame
        Candidate rows from this relation's ``parent_table``. The
        relation's ``parent_key`` must be present as a column.

    Returns
    -------
    pandas.DataFrame
        Rows from ``parent_table`` whose parent key is referenced by
        ``child_rows``. The original index, column order, and dataframe
        type are preserved. Null foreign-key values never match.

    Raises
    ------
    KeyError
        If ``foreign_key`` is missing from ``child_rows`` or ``parent_key``
        is missing from ``parent_table``.

    Notes
    -----
    This method does not enforce relation cardinality. It can return zero,
    one, or multiple parent rows; the caller decides how those cases are
    handled.
    """
    foreign_keys = child_rows[self.foreign_key].dropna()
    return parent_table.loc[parent_table[self.parent_key].isin(foreign_keys)]

Table dataclass

A HyDAMO table: its DAMO 2.2 layer, the columns HYDROLIB reads, and how it is read.

A column is declared by its name, or as a Column when there is more to say.

Parameters

layer : str DAMO 2.2 layer, matched case-insensitively. geotype : type[BaseGeometry] or UnionType or None Geometry type of a spatial table, e.g. Point or Polygon | MultiPolygon; None for a table without geometry. required_columns : tuple[str or Column, ...] Columns a loaded layer must have; a missing one is an error. optional_columns : tuple[str or Column, ...] Other columns HYDROLIB reads. Loading doesn't need them: a missing one is absent after loading. Building the model may still need one for some objects, e.g. debiet for a discharge boundary; it then fails on the missing column. derived_columns : tuple[Column, ...] Columns computed after loading, whatever the DAMO version (see hydrolib.dhydamo.io.damo_versions.loader). A derived column may also be read; its reason then says how the two combine, e.g. overwritten or only filled where empty. group_by : str, optional Column whose points are grouped into one line each. order_by : str, optional Column that orders the points of a line. optional_layer : bool Whether a file may lack the layer. Default is True. check_geotype : bool Whether the geometries must have the table's geometry type. Default is True.

Source code in hydrolib/dhydamo/core/data_model.py
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
@dataclass(frozen=True)
class Table:
    """A HyDAMO table: its DAMO 2.2 layer, the columns HYDROLIB reads, and how it is read.

    A column is declared by its name, or as a `Column` when there is more to say.

    Parameters
    ----------
    layer : str
        DAMO 2.2 layer, matched case-insensitively.
    geotype : type[BaseGeometry] or UnionType or None
        Geometry type of a spatial table, e.g. ``Point`` or ``Polygon | MultiPolygon``;
        ``None`` for a table without geometry.
    required_columns : tuple[str or Column, ...]
        Columns a loaded layer must have; a missing one is an error.
    optional_columns : tuple[str or Column, ...]
        Other columns HYDROLIB reads. Loading doesn't need them: a missing one is
        absent after loading. Building the model may still need one for some
        objects, e.g. ``debiet`` for a discharge boundary; it then fails on the
        missing column.
    derived_columns : tuple[Column, ...]
        Columns computed after loading, whatever the DAMO version (see
        `hydrolib.dhydamo.io.damo_versions.loader`). A derived column may also be
        read; its reason then says how the two combine, e.g. overwritten or only
        filled where empty.
    group_by : str, optional
        Column whose points are grouped into one line each.
    order_by : str, optional
        Column that orders the points of a line.
    optional_layer : bool
        Whether a file may lack the layer. Default is ``True``.
    check_geotype : bool
        Whether the geometries must have the table's geometry type. Default is
        ``True``.
    """

    layer: str
    geotype: Geotype | None
    required_columns: tuple[str | Column, ...]
    optional_columns: tuple[str | Column, ...] = ()
    derived_columns: tuple[Column, ...] = ()
    group_by: str | None = None
    order_by: str | None = None
    optional_layer: bool = True
    check_geotype: bool = True

    def __post_init__(self) -> None:
        """Check that at most one column is filled from ``globalid``.

        Raises
        ------
        ValueError
            If more than one column is: the loader fills one column per table.
        """
        filled = [column.name for column in self.columns if column.fill_from_globalid]
        if len(filled) > 1:
            raise ValueError(
                f"Table {self.layer} fills more than one column from globalid "
                f"({', '.join(filled)}); the loader fills one column per table."
            )

    @property
    def required_names(self) -> tuple[str, ...]:
        """The names of the required columns."""
        return tuple(_column(column).name for column in self.required_columns)

    @property
    def optional_names(self) -> tuple[str, ...]:
        """The names of the optional columns."""
        return tuple(_column(column).name for column in self.optional_columns)

    @property
    def columns(self) -> tuple[Column, ...]:
        """The read columns, required then optional, each as a `Column`."""
        return tuple(
            _column(column)
            for column in (*self.required_columns, *self.optional_columns)
        )

    @property
    def identity_column(self) -> str | None:
        """The read column that is the table's identity and index, if any.

        A derived identity, such as the profile's ``code``, isn't read: its
        derivation sets the index.
        """
        for column in self.columns:
            if column.identity:
                return column.name
        return None

    @property
    def column_filled_from_globalid(self) -> str | None:
        """The column filled from ``globalid``, if any."""
        for column in self.columns:
            if column.fill_from_globalid:
                return column.name
        return None
__post_init__() -> None

Check that at most one column is filled from globalid.

Raises

ValueError If more than one column is: the loader fills one column per table.

Source code in hydrolib/dhydamo/core/data_model.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def __post_init__(self) -> None:
    """Check that at most one column is filled from ``globalid``.

    Raises
    ------
    ValueError
        If more than one column is: the loader fills one column per table.
    """
    filled = [column.name for column in self.columns if column.fill_from_globalid]
    if len(filled) > 1:
        raise ValueError(
            f"Table {self.layer} fills more than one column from globalid "
            f"({', '.join(filled)}); the loader fills one column per table."
        )
column_filled_from_globalid: str | None property

The column filled from globalid, if any.

columns: tuple[Column, ...] property

The read columns, required then optional, each as a Column.

identity_column: str | None property

The read column that is the table's identity and index, if any.

A derived identity, such as the profile's code, isn't read: its derivation sets the index.

optional_names: tuple[str, ...] property

The names of the optional columns.

required_names: tuple[str, ...] property

The names of the required columns.

extensions() -> list[Extension]

Return HYDROLIB's extensions to DAMO 2.2, as declared on the tables' columns.

Returns

list[Extension] Per table in TABLES order: its identity, HYDROLIB-only columns, value rewrites and columns filled from globalid, in column order, then its derived columns.

Source code in hydrolib/dhydamo/core/data_model.py
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def extensions() -> list[Extension]:
    """Return HYDROLIB's extensions to DAMO 2.2, as declared on the tables' columns.

    Returns
    -------
    list[Extension]
        Per table in `TABLES` order: its identity, HYDROLIB-only columns, value
        rewrites and columns filled from ``globalid``, in column order, then its
        derived columns.
    """
    found = []
    for name, table in TABLES.items():
        for column in (*table.columns, *table.derived_columns):
            if column.identity:
                found.append(Extension(name, column.name, "identity", column.reason))
        for column in table.columns:
            if column.hydrolib_only:
                found.append(
                    Extension(name, column.name, "HYDROLIB-only column", column.reason)
                )
            if column.rewrite is not None:
                found.append(
                    Extension(name, column.name, "value rewrite", column.reason)
                )
            if column.fill_from_globalid:
                found.append(
                    Extension(name, column.name, "filled from globalid", column.reason)
                )
        for column in table.derived_columns:
            found.append(Extension(name, column.name, "derived column", column.reason))
    return found

drr

The D-RR model: unpaved, paved, greenhouse and open water nodes, and their forcings.

DRRModel

The D-RR model.

Holds the unpaved, paved, greenhouse and open water nodes, and the external forcings (seepage, precipitation, evaporation and boundary nodes). Write it with DRRWriter.

Source code in hydrolib/dhydamo/core/drr.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class DRRModel:
    """The D-RR model.

    Holds the unpaved, paved, greenhouse and open water nodes, and the external forcings
    (seepage, precipitation, evaporation and boundary nodes). Write it with
    ``DRRWriter``.
    """

    def __init__(self) -> None:
        """Create an empty RR model."""
        self.d3b_parameters: dict[str, str | int | float] = {}

        # Land-use counts and surface levels shared by the RR node types.
        self.zonal_cache = zonal.ZonalCache()

        self.unpaved = Unpaved(self)

        self.paved = Paved(self)

        self.greenhouse = Greenhouse(self)

        self.openwater = Openwater(self)

        self.external_forcings = ExternalForcings(self)

        self.dimr_path = ""

    @staticmethod
    def _time_from_filename(path: str | Path) -> pd.Timestamp:
        """Return the time in a file name such as ``precip_20160601.tif``: the part after the first ``_``."""
        filename = os.path.split(path)[1]
        return pd.Timestamp(filename.split("_")[1].split(".")[0])

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def read_raster(self, file: str | Path, static: bool = False) -> tuple:
        """Read the first band of a raster with rasterio.

        Parameters
        ----------
        file : str or Path
            Raster file. Without ``static``, its name holds the time after the first
            ``_``, e.g. ``precip_20160601.tif``.
        static : bool, optional
            The raster has no time. Defaults to False.

        Returns
        -------
        tuple
            The array and its transform, and without ``static`` also the time.
        """
        if isinstance(file, str):
            filename = Path(file)
        else:
            filename = file

        if not static:
            time = self._time_from_filename(file)

        dataset = rasterio.open(filename)
        affine = dataset.transform
        grid = dataset.read(1)

        if static:
            return grid, affine
        else:
            return grid, affine, time
__init__() -> None

Create an empty RR model.

Source code in hydrolib/dhydamo/core/drr.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(self) -> None:
    """Create an empty RR model."""
    self.d3b_parameters: dict[str, str | int | float] = {}

    # Land-use counts and surface levels shared by the RR node types.
    self.zonal_cache = zonal.ZonalCache()

    self.unpaved = Unpaved(self)

    self.paved = Paved(self)

    self.greenhouse = Greenhouse(self)

    self.openwater = Openwater(self)

    self.external_forcings = ExternalForcings(self)

    self.dimr_path = ""
read_raster(file: str | Path, static: bool = False) -> tuple

Read the first band of a raster with rasterio.

Parameters

file : str or Path Raster file. Without static, its name holds the time after the first _, e.g. precip_20160601.tif. static : bool, optional The raster has no time. Defaults to False.

Returns

tuple The array and its transform, and without static also the time.

Source code in hydrolib/dhydamo/core/drr.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def read_raster(self, file: str | Path, static: bool = False) -> tuple:
    """Read the first band of a raster with rasterio.

    Parameters
    ----------
    file : str or Path
        Raster file. Without ``static``, its name holds the time after the first
        ``_``, e.g. ``precip_20160601.tif``.
    static : bool, optional
        The raster has no time. Defaults to False.

    Returns
    -------
    tuple
        The array and its transform, and without ``static`` also the time.
    """
    if isinstance(file, str):
        filename = Path(file)
    else:
        filename = file

    if not static:
        time = self._time_from_filename(file)

    dataset = rasterio.open(filename)
    affine = dataset.transform
    grid = dataset.read(1)

    if static:
        return grid, affine
    else:
        return grid, affine, time

ExternalForcings

External forcings of the RR model: meteo, seepage and boundary nodes.

Parameters

drrmodel : DRRModel The RR model they belong to.

Source code in hydrolib/dhydamo/core/drr.py
 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
class ExternalForcings:
    """External forcings of the RR model: meteo, seepage and boundary nodes.

    Parameters
    ----------
    drrmodel : DRRModel
        The RR model they belong to.
    """

    def __init__(self, drrmodel: DRRModel) -> None:
        # Point to relevant attributes from parent
        self.drrmodel = drrmodel
        self.io = drrreader.ExternalForcingsIO(self)

        self.boundary_nodes: dict[str, dict[str, str]] = {}
        self.seepage: dict[str, dict[str, pd.Series]] = {}
        # a series per meteo area, or the path of an existing meteo file
        self.precip: dict[str, dict[str, pd.Series]] | str = {}
        self.evap: dict[str, dict[str, pd.Series]] | str = {}

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_precip(self, id: str, series: pd.Series) -> None:
        """Add the precipitation time series of a meteo area.

        Parameters
        ----------
        id : str
            Id of the meteo area.
        series : pd.Series
            Precipitation, with a time index.

        Raises
        ------
        TypeError
            If the precipitation is already read from a meteo file.
        """
        if isinstance(self.precip, str):
            raise TypeError(f"The precipitation is already read from {self.precip}.")
        self.precip[id] = {"precip": series}

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_evap(self, id: str, series: pd.Series) -> None:
        """Add the evaporation time series of a meteo area.

        Parameters
        ----------
        id : str
            Id of the meteo area.
        series : pd.Series
            Evaporation, with a time index.

        Raises
        ------
        TypeError
            If the evaporation is already read from a meteo file.
        """
        if isinstance(self.evap, str):
            raise TypeError(f"The evaporation is already read from {self.evap}.")
        self.evap[id] = {"evap": series}

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_seepage(self, id: str, series: pd.Series) -> None:
        """Add the seepage time series of a catchment.

        Parameters
        ----------
        id : str
            Id of the catchment.
        series : pd.Series
            Seepage, with a time index.
        """
        self.seepage[id] = {"seepage": series}

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_boundary_node(self, id: str, px: str, py: str) -> None:
        """Add a boundary node, which couples RR nodes to a lateral of the FM model.

        Parameters
        ----------
        id : str
            Id of the boundary node.
        px, py : str
            Coordinates of the node.
        """
        self.boundary_nodes[id] = {"id": id, "px": px, "py": py}
add_boundary_node(id: str, px: str, py: str) -> None

Add a boundary node, which couples RR nodes to a lateral of the FM model.

Parameters

id : str Id of the boundary node. px, py : str Coordinates of the node.

Source code in hydrolib/dhydamo/core/drr.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_boundary_node(self, id: str, px: str, py: str) -> None:
    """Add a boundary node, which couples RR nodes to a lateral of the FM model.

    Parameters
    ----------
    id : str
        Id of the boundary node.
    px, py : str
        Coordinates of the node.
    """
    self.boundary_nodes[id] = {"id": id, "px": px, "py": py}
add_evap(id: str, series: pd.Series) -> None

Add the evaporation time series of a meteo area.

Parameters

id : str Id of the meteo area. series : pd.Series Evaporation, with a time index.

Raises

TypeError If the evaporation is already read from a meteo file.

Source code in hydrolib/dhydamo/core/drr.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_evap(self, id: str, series: pd.Series) -> None:
    """Add the evaporation time series of a meteo area.

    Parameters
    ----------
    id : str
        Id of the meteo area.
    series : pd.Series
        Evaporation, with a time index.

    Raises
    ------
    TypeError
        If the evaporation is already read from a meteo file.
    """
    if isinstance(self.evap, str):
        raise TypeError(f"The evaporation is already read from {self.evap}.")
    self.evap[id] = {"evap": series}
add_precip(id: str, series: pd.Series) -> None

Add the precipitation time series of a meteo area.

Parameters

id : str Id of the meteo area. series : pd.Series Precipitation, with a time index.

Raises

TypeError If the precipitation is already read from a meteo file.

Source code in hydrolib/dhydamo/core/drr.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_precip(self, id: str, series: pd.Series) -> None:
    """Add the precipitation time series of a meteo area.

    Parameters
    ----------
    id : str
        Id of the meteo area.
    series : pd.Series
        Precipitation, with a time index.

    Raises
    ------
    TypeError
        If the precipitation is already read from a meteo file.
    """
    if isinstance(self.precip, str):
        raise TypeError(f"The precipitation is already read from {self.precip}.")
    self.precip[id] = {"precip": series}
add_seepage(id: str, series: pd.Series) -> None

Add the seepage time series of a catchment.

Parameters

id : str Id of the catchment. series : pd.Series Seepage, with a time index.

Source code in hydrolib/dhydamo/core/drr.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_seepage(self, id: str, series: pd.Series) -> None:
    """Add the seepage time series of a catchment.

    Parameters
    ----------
    id : str
        Id of the catchment.
    series : pd.Series
        Seepage, with a time index.
    """
    self.seepage[id] = {"seepage": series}

Greenhouse

Greenhouse nodes of the RR model.

Parameters

drrmodel : DRRModel The RR model they belong to.

Source code in hydrolib/dhydamo/core/drr.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
class Greenhouse:
    """Greenhouse nodes of the RR model.

    Parameters
    ----------
    drrmodel : DRRModel
        The RR model they belong to.
    """

    def __init__(self, drrmodel: DRRModel) -> None:
        self.drrmodel = drrmodel
        self.gh_nodes: dict[str, dict[str, str]] = {}

        # Create the io class
        self.io = drrreader.GreenhouseIO(self)

    #    GRHS id ’1’ na 10 ar 1000. 0. 0. 3000. 0. 0. 0. 0. 0. 0. sl 1.0 as 0. sd ’roofstor 1mm’ si
    #    ’silo typ1’ ms ’meteostat1’ is 50.0 grhs
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_greenhouse(
        self,
        id: str,
        area: str,
        surface_level: str,
        roof_storage: str,
        basin_storage_class: str,
        meteo_area: str,
        px: str,
        py: str,
        boundary_node: str,
    ) -> None:
        """Add a greenhouse node.

        Parameters
        ----------
        id : str
            Catchment or greenhouse area id.
        area : str
            Greenhouse area (m2).
        surface_level : str
            Surface level (m).
        roof_storage : str
            Roof storage (mm).
        basin_storage_class : str
            Basin storage class.
        meteo_area : str
            Id of the meteo area, to which a station in the meteo file is assigned.
        px, py : str
            Coordinates of the node.
        boundary_node : str
            Boundary node to which the node drains.
        """
        self.gh_nodes[id] = {
            "id": "gh_" + id,
            "ar": area,
            "sl": surface_level,
            "sd": roof_storage,
            "ms": "ms_" + meteo_area,
            "is": "0",
            "px": px,
            "py": py,
            "boundary_node": boundary_node,
            "basin_storage_class": basin_storage_class,
        }
add_greenhouse(id: str, area: str, surface_level: str, roof_storage: str, basin_storage_class: str, meteo_area: str, px: str, py: str, boundary_node: str) -> None

Add a greenhouse node.

Parameters

id : str Catchment or greenhouse area id. area : str Greenhouse area (m2). surface_level : str Surface level (m). roof_storage : str Roof storage (mm). basin_storage_class : str Basin storage class. meteo_area : str Id of the meteo area, to which a station in the meteo file is assigned. px, py : str Coordinates of the node. boundary_node : str Boundary node to which the node drains.

Source code in hydrolib/dhydamo/core/drr.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_greenhouse(
    self,
    id: str,
    area: str,
    surface_level: str,
    roof_storage: str,
    basin_storage_class: str,
    meteo_area: str,
    px: str,
    py: str,
    boundary_node: str,
) -> None:
    """Add a greenhouse node.

    Parameters
    ----------
    id : str
        Catchment or greenhouse area id.
    area : str
        Greenhouse area (m2).
    surface_level : str
        Surface level (m).
    roof_storage : str
        Roof storage (mm).
    basin_storage_class : str
        Basin storage class.
    meteo_area : str
        Id of the meteo area, to which a station in the meteo file is assigned.
    px, py : str
        Coordinates of the node.
    boundary_node : str
        Boundary node to which the node drains.
    """
    self.gh_nodes[id] = {
        "id": "gh_" + id,
        "ar": area,
        "sl": surface_level,
        "sd": roof_storage,
        "ms": "ms_" + meteo_area,
        "is": "0",
        "px": px,
        "py": py,
        "boundary_node": boundary_node,
        "basin_storage_class": basin_storage_class,
    }

Openwater

Open water nodes of the RR model.

Parameters

drrmodel : DRRModel The RR model they belong to.

Source code in hydrolib/dhydamo/core/drr.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
class Openwater:
    """Open water nodes of the RR model.

    Parameters
    ----------
    drrmodel : DRRModel
        The RR model they belong to.
    """

    def __init__(self, drrmodel: DRRModel) -> None:
        self.drrmodel = drrmodel
        self.ow_nodes: dict[str, dict[str, str]] = {}

        # Create the io class
        self.io = drrreader.OpenwaterIO(self)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_openwater(
        self, id: str, area: str, meteo_area: str, px: str, py: str, boundary_node: str
    ) -> None:
        """Add an open water node.

        Parameters
        ----------
        id : str
            Catchment id.
        area : str
            Open water area (m2).
        meteo_area : str
            Id of the meteo area, to which a station in the meteo file is assigned.
        px, py : str
            Coordinates of the node.
        boundary_node : str
            Boundary node to which the node drains.
        """
        self.ow_nodes[id] = {
            "id": "ow_" + id,
            "ar": area,
            "ms": "ms_" + meteo_area,
            "px": px,
            "py": py,
            "boundary_node": boundary_node,
        }
add_openwater(id: str, area: str, meteo_area: str, px: str, py: str, boundary_node: str) -> None

Add an open water node.

Parameters

id : str Catchment id. area : str Open water area (m2). meteo_area : str Id of the meteo area, to which a station in the meteo file is assigned. px, py : str Coordinates of the node. boundary_node : str Boundary node to which the node drains.

Source code in hydrolib/dhydamo/core/drr.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_openwater(
    self, id: str, area: str, meteo_area: str, px: str, py: str, boundary_node: str
) -> None:
    """Add an open water node.

    Parameters
    ----------
    id : str
        Catchment id.
    area : str
        Open water area (m2).
    meteo_area : str
        Id of the meteo area, to which a station in the meteo file is assigned.
    px, py : str
        Coordinates of the node.
    boundary_node : str
        Boundary node to which the node drains.
    """
    self.ow_nodes[id] = {
        "id": "ow_" + id,
        "ar": area,
        "ms": "ms_" + meteo_area,
        "px": px,
        "py": py,
        "boundary_node": boundary_node,
    }

Paved

Paved nodes of the RR model.

Parameters

drrmodel : DRRModel The RR model they belong to.

Source code in hydrolib/dhydamo/core/drr.py
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
class Paved:
    """Paved nodes of the RR model.

    Parameters
    ----------
    drrmodel : DRRModel
        The RR model they belong to.
    """

    def __init__(self, drrmodel: DRRModel) -> None:
        # Point to relevant attributes from parent
        self.drrmodel = drrmodel
        self.pav_nodes: dict[str, dict[str, str]] = {}

        # Create the io class
        self.io = drrreader.PavedIO(self)

    # PAVE id 'pav_Nde_n003' ar 16200 lv 1 sd '1' ss 0 qc 0 1.94E-05 0 qo 2 2 ms 'Station1' aaf 1 is 0 np 0 dw '1' ro 0 ru 0 qh '' pave#
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_paved(
        self,
        id: str,
        area: str,
        surface_level: str,
        street_storage: str,
        sewer_storage: str,
        pump_capacity: str,
        meteo_area: str,
        px: str,
        py: str,
        boundary_node: str,
    ) -> None:
        """Add a paved node.

        Parameters
        ----------
        id : str
            Catchment or overflow id.
        area : str
            Paved area (m2).
        surface_level : str
            Surface level (m).
        street_storage : str
            Street storage (mm).
        sewer_storage : str
            Sewer storage (mm).
        pump_capacity : str
            Sewer pump capacity (m3/s); ``PavedIO`` computes it from mm/h and the area.
        meteo_area : str
            Id of the meteo area, to which a station in the meteo file is assigned.
        px, py : str
            Coordinates of the node.
        boundary_node : str
            Boundary node to which the node drains.
        """
        self.pav_nodes[id] = {
            "id": "pav_" + id,
            "ar": area,
            "lv": surface_level,
            "qc": pump_capacity,
            "strs": street_storage,
            "sews": sewer_storage,
            "ms": "ms_" + meteo_area,
            "is": "0",
            "np": "0",
            "ro": "0",
            "ru": "0",
            "px": px,
            "py": py,
            "boundary_node": boundary_node,
        }
add_paved(id: str, area: str, surface_level: str, street_storage: str, sewer_storage: str, pump_capacity: str, meteo_area: str, px: str, py: str, boundary_node: str) -> None

Add a paved node.

Parameters

id : str Catchment or overflow id. area : str Paved area (m2). surface_level : str Surface level (m). street_storage : str Street storage (mm). sewer_storage : str Sewer storage (mm). pump_capacity : str Sewer pump capacity (m3/s); PavedIO computes it from mm/h and the area. meteo_area : str Id of the meteo area, to which a station in the meteo file is assigned. px, py : str Coordinates of the node. boundary_node : str Boundary node to which the node drains.

Source code in hydrolib/dhydamo/core/drr.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_paved(
    self,
    id: str,
    area: str,
    surface_level: str,
    street_storage: str,
    sewer_storage: str,
    pump_capacity: str,
    meteo_area: str,
    px: str,
    py: str,
    boundary_node: str,
) -> None:
    """Add a paved node.

    Parameters
    ----------
    id : str
        Catchment or overflow id.
    area : str
        Paved area (m2).
    surface_level : str
        Surface level (m).
    street_storage : str
        Street storage (mm).
    sewer_storage : str
        Sewer storage (mm).
    pump_capacity : str
        Sewer pump capacity (m3/s); ``PavedIO`` computes it from mm/h and the area.
    meteo_area : str
        Id of the meteo area, to which a station in the meteo file is assigned.
    px, py : str
        Coordinates of the node.
    boundary_node : str
        Boundary node to which the node drains.
    """
    self.pav_nodes[id] = {
        "id": "pav_" + id,
        "ar": area,
        "lv": surface_level,
        "qc": pump_capacity,
        "strs": street_storage,
        "sews": sewer_storage,
        "ms": "ms_" + meteo_area,
        "is": "0",
        "np": "0",
        "ro": "0",
        "ru": "0",
        "px": px,
        "py": py,
        "boundary_node": boundary_node,
    }

Unpaved

Unpaved nodes of the RR model, with their Ernst definitions.

Parameters

drrmodel : DRRModel The RR model they belong to.

Source code in hydrolib/dhydamo/core/drr.py
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
class Unpaved:
    """Unpaved nodes of the RR model, with their Ernst definitions.

    Parameters
    ----------
    drrmodel : DRRModel
        The RR model they belong to.
    """

    def __init__(self, drrmodel: DRRModel) -> None:
        # Point to relevant attributes from parent
        self.drrmodel = drrmodel

        # initialize a dataframe for every type of nodes related to 'unpaved'
        self.unp_nodes: dict[str, dict[str, str]] = {}
        self.ernst_defs: dict[str, dict[str, str]] = {}
        # couple input class
        self.io = drrreader.UnpavedIO(self)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_unpaved(
        self,
        id: str,
        total_area: str,
        lu_areas: str,
        surface_level: str,
        soiltype: str,
        surface_storage: str,
        infiltration_capacity: str,
        initial_gwd: str,
        meteo_area: str,
        px: str,
        py: str,
        boundary_node: str,
    ) -> None:
        """Add an unpaved node.

        Parameters
        ----------
        id : str
            Catchment id.
        total_area : str
            Total node area (m2).
        lu_areas : str
            Area per land use class (m2), space separated.
        surface_level : str
            Surface level (m).
        soiltype : str
            Soil type (class id).
        surface_storage : str
            Surface storage (mm).
        infiltration_capacity : str
            Infiltration capacity (mm/d).
        initial_gwd : str
            Initial groundwater depth below the surface (m, positive is below the surface).
        meteo_area : str
            Id of the meteo area, to which a station in the meteo file is assigned.
        px, py : str
            Coordinates of the node.
        boundary_node : str
            Boundary node to which the node drains.
        """
        self.unp_nodes[id] = {
            "id": "unp_" + id,
            "na": "16",
            "ar": lu_areas,
            "ga": total_area,
            "lv": surface_level,
            "co": "3",
            "su": "0",
            "sd": surface_storage,
            "sp": "sep_" + id,
            "ic": infiltration_capacity,
            "ed": "ernst_" + id,
            "bt": soiltype,
            "ig": initial_gwd,
            "mg": surface_level,
            "gl": "1.5",
            "is": "0",
            "ms": "ms_" + meteo_area,
            "px": px,
            "py": py,
            "boundary_node": boundary_node,
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_ernst_def(self, id: str, cvo: str, lv: str, cvi: str, cvs: str) -> None:
        """Add an Ernst definition for the unpaved node of a catchment.

        Parameters
        ----------
        id : str
            Catchment id.
        cvo : str
            Drainage resistance per layer (d), space separated.
        lv : str
            Depth of each layer (m), space separated.
        cvi : str
            Infiltration resistance (d).
        cvs : str
            Surface runoff resistance (d).
        """
        self.ernst_defs[id] = {
            "id": "ernst_" + id,
            "cvi": cvi,
            "cvs": cvs,
            "cvo": cvo,
            "lv": lv,
        }
add_ernst_def(id: str, cvo: str, lv: str, cvi: str, cvs: str) -> None

Add an Ernst definition for the unpaved node of a catchment.

Parameters

id : str Catchment id. cvo : str Drainage resistance per layer (d), space separated. lv : str Depth of each layer (m), space separated. cvi : str Infiltration resistance (d). cvs : str Surface runoff resistance (d).

Source code in hydrolib/dhydamo/core/drr.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_ernst_def(self, id: str, cvo: str, lv: str, cvi: str, cvs: str) -> None:
    """Add an Ernst definition for the unpaved node of a catchment.

    Parameters
    ----------
    id : str
        Catchment id.
    cvo : str
        Drainage resistance per layer (d), space separated.
    lv : str
        Depth of each layer (m), space separated.
    cvi : str
        Infiltration resistance (d).
    cvs : str
        Surface runoff resistance (d).
    """
    self.ernst_defs[id] = {
        "id": "ernst_" + id,
        "cvi": cvi,
        "cvs": cvs,
        "cvo": cvo,
        "lv": lv,
    }
add_unpaved(id: str, total_area: str, lu_areas: str, surface_level: str, soiltype: str, surface_storage: str, infiltration_capacity: str, initial_gwd: str, meteo_area: str, px: str, py: str, boundary_node: str) -> None

Add an unpaved node.

Parameters

id : str Catchment id. total_area : str Total node area (m2). lu_areas : str Area per land use class (m2), space separated. surface_level : str Surface level (m). soiltype : str Soil type (class id). surface_storage : str Surface storage (mm). infiltration_capacity : str Infiltration capacity (mm/d). initial_gwd : str Initial groundwater depth below the surface (m, positive is below the surface). meteo_area : str Id of the meteo area, to which a station in the meteo file is assigned. px, py : str Coordinates of the node. boundary_node : str Boundary node to which the node drains.

Source code in hydrolib/dhydamo/core/drr.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_unpaved(
    self,
    id: str,
    total_area: str,
    lu_areas: str,
    surface_level: str,
    soiltype: str,
    surface_storage: str,
    infiltration_capacity: str,
    initial_gwd: str,
    meteo_area: str,
    px: str,
    py: str,
    boundary_node: str,
) -> None:
    """Add an unpaved node.

    Parameters
    ----------
    id : str
        Catchment id.
    total_area : str
        Total node area (m2).
    lu_areas : str
        Area per land use class (m2), space separated.
    surface_level : str
        Surface level (m).
    soiltype : str
        Soil type (class id).
    surface_storage : str
        Surface storage (mm).
    infiltration_capacity : str
        Infiltration capacity (mm/d).
    initial_gwd : str
        Initial groundwater depth below the surface (m, positive is below the surface).
    meteo_area : str
        Id of the meteo area, to which a station in the meteo file is assigned.
    px, py : str
        Coordinates of the node.
    boundary_node : str
        Boundary node to which the node drains.
    """
    self.unp_nodes[id] = {
        "id": "unp_" + id,
        "na": "16",
        "ar": lu_areas,
        "ga": total_area,
        "lv": surface_level,
        "co": "3",
        "su": "0",
        "sd": surface_storage,
        "sp": "sep_" + id,
        "ic": infiltration_capacity,
        "ed": "ernst_" + id,
        "bt": soiltype,
        "ig": initial_gwd,
        "mg": surface_level,
        "gl": "1.5",
        "is": "0",
        "ms": "ms_" + meteo_area,
        "px": px,
        "py": py,
        "boundary_node": boundary_node,
    }

drtc

The D-RTC model: time, PID and interval controllers, complex controllers and their XML files.

ComplexControllers

Bases: TypedDict

XML of the complex controllers: fragments per RTC file, and the parsed DIMR config roots.

pydantic needs typing_extensions.TypedDict (not typing.TypedDict) on Python < 3.12.

Source code in hydrolib/dhydamo/core/drtc.py
80
81
82
83
84
85
86
87
88
89
90
91
92
class ComplexControllers(TypedDict):
    """XML of the complex controllers: fragments per RTC file, and the parsed DIMR config roots.

    pydantic needs ``typing_extensions.TypedDict`` (not ``typing.TypedDict``) on Python < 3.12.
    """

    dataconfig_import: list[str]
    dataconfig_export: list[str]
    toolsconfig_rules: list[str]
    toolsconfig_triggers: list[str]
    timeseries: list[str]
    state: list[str]
    dimr_config: list[ET.Element]

DRTCModel

Main class to generate RTC-module files.

Source code in hydrolib/dhydamo/core/drtc.py
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
class DRTCModel:
    """Main class to generate RTC-module files."""

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def __init__(
        self,
        hydamo: HyDAMO,
        fm: FMModel,
        output_path: str | Path | None = None,
        rtc_onlytimeseries: bool = False,
        rtc_timeseriesdata: pd.DataFrame | None = None,
        complex_controllers_folder: list[str | Path] | str | Path | None = None,
        id_limit_complex_controllers: list[str] | None = None,
        rtc_timestep: float = 60,
    ) -> None:
        """Initialize the DRTCModel.

        Internal controller dictionaries and output paths are initialized, optional
        complex-controller XML is parsed, and RTC template files are copied to the
        output folder.

        Parameters
        ----------
        hydamo : HyDAMO
            The HyDAMO data, with the structures and management.
        fm : FMModel
            The FM model; its reference date and times set the RTC period.
        output_path : str or Path, optional
            Folder in which an ``rtc`` subfolder is created for the RTC files. Defaults to
            None: the current working directory.
        rtc_onlytimeseries : bool, optional
            Build the RTC control from ``rtc_timeseriesdata`` only;
            ``complex_controllers_folder`` is then ignored. Defaults to False.
        rtc_timeseriesdata : pd.DataFrame, optional
            Time series used with ``rtc_onlytimeseries``, with the structure ids as
            columns. Defaults to None.
        complex_controllers_folder : list[Path or str], Path or str, optional
            Folder(s) with custom RTC XML files to import, without
            ``rtc_onlytimeseries``. Defaults to None.
        id_limit_complex_controllers : list[str], optional
            Ids that may be coupled to complex controllers. Required with
            ``complex_controllers_folder``; an empty list allows no ids. Defaults to None.
        rtc_timestep : float, optional
            Time step of the RTC model (s). Defaults to 60.
        """
        self.hydamo = hydamo

        self.time_settings: TimeSettings = {
            "start": pd.to_datetime(fm.time.refdate, format="%Y%m%d"),
            "end": pd.to_datetime(fm.time.refdate, format="%Y%m%d")
            + pd.to_timedelta(fm.time.tstop, unit="s"),
            "step": rtc_timestep,
        }

        self.pid_controllers: dict[str, PIDController] = {}
        self.time_controllers: dict[str, TimeController] = {}
        self.interval_controllers: dict[str, IntervalController] = {}

        # initial state: from an earlier model run (set_state_from_file) and/or per structure (set_initial_state)
        self.state_from_file: dict[str, str] | None = None
        self.initial_state: dict[str, float] = {}
        # ids of the time series in rtcDataConfig.xml, set by write_dataconfig
        self._written_dataconfig_ids: set[str] | None = None

        # set up the output path
        base_output_path = Path(".") if output_path is None else Path(output_path)
        self.output_path = base_output_path / "rtc"
        self.output_path.mkdir(parents=True, exist_ok=True)

        # Save object id by type
        self.struct_ids_by_type = DRTCModel._get_struct_ids_by_type(self.hydamo)

        # parse user-provided controllers
        self.complex_controllers: ComplexControllers | None = None
        self.cc_structs = None
        self.cc_ids = None
        self.cc_referenced_ids = None
        self.cc_id_limit = None
        if rtc_onlytimeseries and complex_controllers_folder is not None:
            # User supplied controllers in timeseries_only mode, emit warning
            logger.warning(
                "`complex_controllers_folder` is ignored because `rtc_onlytimeseries=True`. "
                "Set `rtc_onlytimeseries=False` to enable complex controllers."
            )
        elif not rtc_onlytimeseries and complex_controllers_folder is not None:
            if id_limit_complex_controllers is None:
                # When complex_controllers_folder is supplied, the whitelist
                # needs to be supplied as well
                raise SyntaxError(
                    "Missing required `id_limit_complex_controllers` while "
                    "`complex_controllers_folder` is provided. Supply a list of "
                    "allowed IDs to couple to complex controller logic."
                )

            # Discover complex-controller references before and after HyDAMO validation.
            #
            # These are intentionally two separate concepts:
            # - cc_referenced_ids: all structure ids mentioned in the user-provided
            #   complex-controller dimr_config.xml files.
            # - cc_ids: only the referenced ids that also exist in the HyDAMO model.
            #
            # The distinction matters when filtering DIMR couplers. A referenced id
            # that is missing from HyDAMO must be removed from the complex-controller
            # XML. If we only kept the validated set, that invalid id would look like
            # an unrelated/non-complex DIMR item and could accidentally pass through.
            (
                self.cc_structs,
                self.cc_ids,
                self.cc_referenced_ids,
            ) = self._load_complex_controller_structs(
                complex_controllers_folder,
                self.struct_ids_by_type,
                log_validation=True,
            )
            logger.info(
                "Complex controllers: found %d unique structure references in dimr_config.xml: %s",
                len(self.cc_referenced_ids),
                self.cc_referenced_ids,
            )
            logger.info(
                "Complex controllers: matched %d references to HyDAMO structures: %s",
                len(self.cc_ids),
                self.cc_ids,
            )

            # Save whitelist of allowed controller ids.
            self.cc_id_limit = set(id_limit_complex_controllers)
            if len(self.cc_id_limit) == 0:
                logger.warning(
                    "`id_limit_complex_controllers` is empty. No IDs are allowed, "
                    "so all complex controller references will be filtered out."
                )
            else:
                logger.info(
                    "Complex controllers: applying id_limit_complex_controllers with %d allowed IDs: %s",
                    len(self.cc_id_limit),
                    self.cc_id_limit,
                )

            # Load complex controllers
            self.complex_controllers = self._load_complex_controllers(
                complex_controllers_folder
            )

        # copy files from the template RTC-folder
        self.template_dir = Path(__file__).resolve().parent / ".." / "resources" / "RTC"
        for filepath in self.template_dir.iterdir():
            if filepath.suffix in {".xsd", ".json"}:
                shutil.copy(filepath, self.output_path / filepath.name)

        if rtc_onlytimeseries:
            if rtc_timeseriesdata is None:
                raise ValueError(
                    "`rtc_timeseriesdata` is required when `rtc_onlytimeseries=True`."
                )
            for name, data in rtc_timeseriesdata.items():
                if name in hydamo.structures.rweirs_df.id.to_list():
                    steering_var = CREST_LEVEL
                if name in hydamo.structures.orifices_df.id.to_list():
                    steering_var = GATE_LOWER_EDGE_LEVEL
                if name in hydamo.structures.pumps_df.id.to_list():
                    steering_var = CAPACITY
                self.add_time_controller(
                    structure_id=str(name), steering_variable=steering_var, data=data
                )
            self.check_timeseries(rtc_timeseriesdata)
            self.complex_controllers = None

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def allow_struct(
        self,
        cc_id: str,
        allow_observations: bool = False,
        allow_if_filter_inactive: bool = True,
        allow_if_not_referenced: bool = False,
    ) -> bool:
        """Return whether a structure id is allowed by the complex-controller filter.

        Parameters
        ----------
        cc_id : str
            Structure or observation id to evaluate.
        allow_observations : bool, optional
            Pass through observation ids that exist in the HyDAMO model. Defaults to
            False.
        allow_if_filter_inactive : bool, optional
            Return value when no complex controller filter is active
            (``cc_referenced_ids`` or ``cc_id_limit`` is None). Defaults to True.
        allow_if_not_referenced : bool, optional
            Return value when filtering is active, but ``cc_id`` is not in
            ``cc_referenced_ids``. Defaults to False.

        Returns
        -------
        bool
            Whether the id is allowed.
        """
        allow, _ = self._allow_struct_with_reason(
            cc_id=cc_id,
            allow_observations=allow_observations,
            allow_if_filter_inactive=allow_if_filter_inactive,
            allow_if_not_referenced=allow_if_not_referenced,
        )
        return allow

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _allow_struct_with_reason(
        self,
        cc_id: str,
        allow_observations: bool = False,
        allow_if_filter_inactive: bool = True,
        allow_if_not_referenced: bool = False,
    ) -> tuple[bool, str | None]:
        """Return whether an id is allowed and why it is rejected.

        The reason is only populated for rejected ids, so skip log messages can
        distinguish "not whitelisted" from "referenced in RTC XML but missing
        from HyDAMO".
        """
        if allow_observations and cc_id in self.struct_ids_by_type["observations"]:
            return True, None

        if (
            self.cc_referenced_ids is None
            or self.cc_ids is None
            or self.cc_id_limit is None
        ):
            return allow_if_filter_inactive, (
                None
                if allow_if_filter_inactive
                else "complex-controller filtering is inactive"
            )

        # IDs not mentioned in the DIMR couplers are outside the complex-controller
        # reference set. Some callers, such as DIMR coupler filtering, choose to
        # keep those unrelated items; callers parsing RTC fragments reject them.
        if cc_id not in self.cc_referenced_ids:
            return allow_if_not_referenced, (
                None
                if allow_if_not_referenced
                else "not part of complex-controller references in dimr_config.xml"
            )

        # The id is referenced by complex-controller DIMR XML but was not validated
        # against HyDAMO. It should never be coupled, even when the caller keeps
        # unrelated/non-referenced DIMR items.
        if cc_id not in self.cc_ids:
            return (
                False,
                "referenced by complex-controller XML but missing from HyDAMO",
            )

        if cc_id not in self.cc_id_limit:
            return False, "excluded by id_limit_complex_controllers"

        return True, None

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def check_timeseries(self, timeseries: pd.DataFrame) -> None:
        """Warn for each structure with a controller in ``hydamo.management`` but no time series.

        Parameters
        ----------
        timeseries : pd.DataFrame
            Time series, with the structure ids as columns.
        """
        all_management = self.hydamo.management
        # The resolver raises for rows referencing neither a pump nor a management device.
        hydamo_controllers = all_management[
            all_management[DamoRelations.MANAGEMENT_PUMP.foreign_key].notna()
            | all_management[DamoRelations.MANAGEMENT_DEVICE.foreign_key].notna()
        ]
        for _, management in hydamo_controllers.iterrows():
            resolved = self._resolve_management_structure(management)
            if resolved is None:
                continue
            _, structure_id = resolved
            if structure_id not in timeseries.columns:
                logger.warning(
                    "For %s a controller is defined in hydamo.management, but no timeseries is provided for it.",
                    structure_id,
                )

    def _resolve_management_structure(
        self, management: pd.Series
    ) -> tuple[str, str] | None:
        """Resolve a `hydamo.management` row to the structure it steers.

        Dispatches on whether the row references a pump (`pompid`) or a
        management device (`regelmiddelid`), then, for management devices,
        resolves the underlying weir/orifice (via `_resolve_weir_via_opening`
        and `hydamo.structures.compound_weir_structure_ids`) or culvert (via
        `management_device.duikersifonhevelid`).

        Architecture note: this method, and the weir/orifice resolution it
        delegates to `_resolve_weir_via_opening`, intentionally lives here and
        not in `hydrolib.dhydamo.io.damo_versions`. The version steps there
        only normalize differences between DAMO schema versions (column
        renames, layer name changes) into one canonical HyDAMO column set;
        once `hydamo.management` reaches this method, the DAMO version is
        irrelevant. Mapping a management record to a controllable structure is
        RTC-specific business logic, so it belongs in DRTCModel.

        Parameters
        ----------
        management : pd.Series
            A single row from ``hydamo.management``, in canonical
            (as loaded) column form. Must have ``pompid`` and
            ``regelmiddelid``, where exactly one of the two is expected to be non-null.

        Returns
        -------
        tuple[str, str] or None
            ``(structure_type, structure_id)``, where ``structure_type`` is one of
            ``"pump"``, ``"weir"`` or ``"culvert"`` and ``structure_id`` is the id of the
            built D-FlowFM structure. None when the referenced pump, management device,
            weir or culvert cannot be resolved or is not present in the built D-FlowFM
            structures; a warning is logged in that case.

        Raises
        ------
        ValueError
            If neither ``pompid`` nor ``regelmiddelid`` is set on ``management``, since a
            management record must reference one of the two.
        """
        management_pump = DamoRelations.MANAGEMENT_PUMP
        management_device = DamoRelations.MANAGEMENT_DEVICE
        management_rows = management.to_frame().T
        pump_id = management[management_pump.foreign_key]
        if not pd.isna(pump_id):
            pumps = management_pump.parents_of(management_rows, self.hydamo.pumps)
            if not pumps.empty:
                struc_id = pumps["code"].to_numpy()[0]
                return "pump", struc_id
            return None

        management_device_id = management[management_device.foreign_key]
        if pd.isna(management_device_id):
            raise ValueError(
                "Only management_devices and pumps can be connected to a management object."
            )

        mandev = management_device.parents_of(
            management_rows,
            self.hydamo.management_device,
        )
        if mandev.empty:
            logger.warning(
                "Management for management_device %s could not be found.",
                management_device_id,
            )
            return None

        weir_code = self._resolve_weir_via_opening(mandev)
        if weir_code is None:
            # Fall back to ids assigned at D-FlowFM structure-build time for
            # weirs/orifices with more than one opening (compound structures).
            # See the comment on Structures.compound_weir_structure_ids in
            # core/hydamo.py for why this lookup cannot be made statically.
            weir_code = self.hydamo.structures.compound_weir_structure_ids.get(
                management_device_id
            )
        if weir_code is not None:
            if weir_code in list(self.hydamo.structures.rweirs_df.id) or (
                not self.hydamo.structures.orifices_df.empty
                and weir_code in list(self.hydamo.structures.orifices_df.id)
            ):
                return "weir", weir_code
            # Resolved a HyDAMO/structure-build reference, but the D-FlowFM
            # structures haven't been built (yet), or building it was skipped
            # (e.g. it was filtered out, or had no valid opening data).
            logger.warning(
                "Management for management_device %s resolved to structure '%s', "
                "but it is not present in the built D-FlowFM structures.",
                management_device_id,
                weir_code,
            )
            return None

        culvert_relation = DamoRelations.MANAGEMENT_DEVICE_CULVERT
        if pd.notna(mandev[culvert_relation.foreign_key]).any():
            struc = culvert_relation.parents_of(
                mandev.iloc[:1],
                self.hydamo.culverts,
            )
            if struc.empty:
                logger.warning(
                    "Management for management_device %s could not be connected to a culvert.",
                    management_device_id,
                )
                return None
            return "culvert", struc.code.to_numpy()[0]

        logger.warning(
            "Management for management_device %s could not be connected to a culvert or weir.",
            management_device_id,
        )
        return None

    def _resolve_weir_via_opening(self, mandev: pd.DataFrame) -> str | None:
        """Resolve a single-opening weir/orifice structure id from static HyDAMO relations.

        Walks the FK chain that already exists on the HyDAMO model, independent
        of D-FlowFM structure conversion having run:

            management_device.kunstwerkopeningid
                -> opening.globalid
                -> opening.stuwid
                -> weirs.globalid -> weirs.code

        For a weir/orifice with exactly one opening, StructuresIO.weirs() (in
        converters/hydamo2df.py) uses `weir.code` as the D-FlowFM structure id,
        i.e. exactly the code this chain resolves to - so this is safe to call
        before structures have been built.

        It deliberately returns None (rather than raising or guessing) for
        compound, multi-opening weirs (i.e. more than one `opening` row shares
        the resolved `stuwid`): their structure id gets a `_N` suffix assigned
        during structure conversion (enumeration order of openings in
        StructuresIO.weirs()), which cannot be derived from HyDAMO data alone.
        Those are looked up separately via
        `hydamo.structures.compound_weir_structure_ids` by the caller.

        Parameters
        ----------
        mandev : pd.DataFrame
            The ``hydamo.management_device`` row(s) for a single management record's
            ``regelmiddelid`` (as selected by ``_resolve_management_structure``).
            Expected to contain at most one row; only the first row is used if there are
            more.

        Returns
        -------
        str or None
            The weir's or orifice's HyDAMO ``code`` (equal to its D-FlowFM structure id),
            or None if ``mandev`` has no ``kunstwerkopeningid``, the chain to ``weirs``
            cannot be resolved, or the weir turns out to be compound (multi-opening).
        """
        opening_relation = DamoRelations.MANAGEMENT_DEVICE_OPENING
        if opening_relation.foreign_key not in mandev.columns:
            return None
        opening_id = mandev[opening_relation.foreign_key].to_numpy()[0]
        if pd.isna(opening_id):
            return None

        opening_row = opening_relation.parents_of(
            mandev.iloc[:1],
            self.hydamo.opening,
        )
        weir_relation = DamoRelations.OPENING_WEIR
        if opening_row.empty or weir_relation.foreign_key not in opening_row.columns:
            return None
        weir_row = weir_relation.parents_of(opening_row, self.hydamo.weirs)
        if weir_row.empty:
            return None

        # A weir with more than one opening is "compound": StructuresIO builds
        # one structure per opening with a generated suffix (weir.code_N), not
        # weir.code itself. We cannot tell here which suffix belongs to this
        # particular opening, so defer to compound_weir_structure_ids instead
        # of returning the (wrong, unsuffixed) weir code.
        sibling_openings = weir_relation.children_of(
            weir_row.iloc[:1], self.hydamo.opening
        )
        if len(sibling_openings) > 1:
            return None

        return weir_row["code"].to_numpy()[0]

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def parse_complex_controller(self, xml_folder: Path | str) -> ComplexControllers:
        """Read user-specified 'complex' controllers from the RTC XML files in a folder.

        Items that refer to structures that are not allowed (see `allow_struct`) are
        skipped and logged.

        Parameters
        ----------
        xml_folder : Path or str
            Folder with the custom XML files.

        Returns
        -------
        ComplexControllers
            The XML fragments per RTC file, and the parsed DIMR config.
        """
        files = [p for p in Path(xml_folder).iterdir() if p.suffix == ".xml"]
        savedict: ComplexControllers = {
            "dataconfig_import": [],
            "dataconfig_export": [],
            "toolsconfig_rules": [],
            "toolsconfig_triggers": [],
            "timeseries": [],
            "state": [],
            "dimr_config": [],
        }

        handlers = {
            RTC_DATA_CONFIG_XML: self._parse_cc_rtc_dataconfig,
            RTC_TOOLS_CONFIG_XML: self._parse_cc_rtc_toolsconfig,
            TIMESERIES_IMPORT_XML: self._parse_cc_timeseries,
            STATE_IMPORT_XML: self._parse_cc_state,
            "dimr_config.xml": self._parse_cc_dimr_config,
        }

        for filepath in files:
            handler = handlers.get(filepath.name)
            if handler is None:
                continue
            root = ET.parse(filepath).getroot()
            savedict = handler(root, savedict)

        return savedict

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_cc_rtc_dataconfig(
        self, root: ET.Element, savedict: ComplexControllers
    ) -> ComplexControllers:
        """Add the allowed import and export series of rtcDataConfig.xml to ``savedict``."""
        children = self._parse_unique_children(root)
        import_series = children.get("importSeries")
        if import_series is not None:
            for num, el in enumerate(import_series):
                xml_text = ET.tostring(el).decode()
                if "PITimeSeries" in xml_text and num == 0:
                    continue
                allow, el_text, reason = self._parse_dataconfig_item(el)
                if not allow:
                    logger.info(
                        f"{RTC_DATA_CONFIG_XML}: Skipped importSeries item for elementId '%s': %s.",
                        el_text,
                        reason,
                    )
                    continue
                savedict["dataconfig_import"].append(xml_text)

        export_series = children.get("exportSeries")
        if export_series is not None:
            for el in export_series:
                xml_text = ET.tostring(el).decode()
                if "PITimeSeries" in xml_text or "CSVTimeSeries" in xml_text:
                    continue
                allow, el_text, reason = self._parse_dataconfig_item(el)
                if not allow:
                    logger.info(
                        f"{RTC_DATA_CONFIG_XML}: Skipped exportSeries item for elementId '%s': %s.",
                        el_text,
                        reason,
                    )
                    continue
                savedict["dataconfig_export"].append(xml_text)

        return savedict

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_cc_rtc_toolsconfig(
        self, root: ET.Element, savedict: ComplexControllers
    ) -> ComplexControllers:
        """Add the allowed rules and triggers of rtcToolsConfig.xml to ``savedict``."""
        children = self._parse_unique_children(root)

        rules = children.get("rules")
        if rules is not None:
            for el in rules:
                allow, el_text, reason = self._parse_toolsconfig_item(el)
                if not allow:
                    logger.info(
                        f"{RTC_TOOLS_CONFIG_XML}: Skipped rule element '%s': %s.",
                        el_text,
                        reason,
                    )
                    continue
                savedict["toolsconfig_rules"].append(ET.tostring(el).decode())

        triggers = children.get("triggers")
        if triggers is not None:
            for el in triggers:
                allow, el_text, reason = self._parse_toolsconfig_item(el)
                if not allow:
                    logger.info(
                        f"{RTC_TOOLS_CONFIG_XML}: Skipped trigger element '%s': %s.",
                        el_text,
                        reason,
                    )
                    continue
                savedict["toolsconfig_triggers"].append(ET.tostring(el).decode())

        return savedict

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_cc_timeseries(
        self, root: ET.Element, savedict: ComplexControllers
    ) -> ComplexControllers:
        """Add all elements of timeseries_import.xml to ``savedict``."""
        for el in root:
            savedict["timeseries"].append(ET.tostring(el).decode())

        return savedict

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_cc_state(
        self, root: ET.Element, savedict: ComplexControllers
    ) -> ComplexControllers:
        """Add the elements of the tree vector of state_import.xml to ``savedict``."""
        for el in root[0]:
            savedict["state"].append(ET.tostring(el).decode())

        return savedict

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_cc_dimr_config(
        self, root: ET.Element, savedict: ComplexControllers
    ) -> ComplexControllers:
        """Add dimr_config.xml to ``savedict``, without the coupler items that are not allowed."""
        red_root = copy.deepcopy(root)
        for coupler_name, coupler_target in (
            ("rtc_to_flow", "targetName"),
            ("flow_to_rtc", "sourceName"),
        ):
            self._filter_dimr_coupler_items(red_root, coupler_name, coupler_target)
        savedict["dimr_config"].append(red_root)

        return savedict

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _filter_dimr_coupler_items(
        self, red_root: ET.Element, coupler_name: str, coupler_target: str
    ) -> None:
        """Remove the items of a coupler that refer to structures that are not allowed, in place."""
        for coupler in list(red_root):
            if coupler.attrib.get("name") != coupler_name:
                continue
            for sub_el in list(coupler):
                target = sub_el.find(".//{*}" + coupler_target)
                allow, el_text, reason = self._parse_dimr_item(target)
                if allow:
                    continue
                logger.info(
                    "dimr_config.xml: Skipped %s element with '%s' '%s': %s.",
                    coupler_name,
                    coupler_target,
                    el_text,
                    reason,
                )
                coupler.remove(sub_el)

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def find_complex_controller_ids(
        complex_controllers_folder: list[str | Path] | str | Path,
        hydamo: HyDAMO,
    ) -> set[str]:
        """Return the ids of the structures that the complex controllers refer to.

        Only structures that exist in the HyDAMO model are returned; observation points
        are left out.

        Parameters
        ----------
        complex_controllers_folder : list[str or Path], str or Path
            Folder(s) with the complex controllers (their ``dimr_config.xml``).
        hydamo : HyDAMO
            The HyDAMO data, with the structures.

        Returns
        -------
        set[str]
            Structure ids.
        """
        # Do not log validation warnings in this method
        struct_ids_by_type = DRTCModel._get_struct_ids_by_type(hydamo)
        cc_structs, _, _ = DRTCModel._load_complex_controller_structs(
            complex_controllers_folder,
            struct_ids_by_type,
            log_validation=False,
        )
        # Do not return observation point IDs in this method
        cc_ids = {
            cc.struct_name for cc in cc_structs if cc.struct_type != "observations"
        }

        return cc_ids

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _load_complex_controller_structs(
        complex_controllers_folder: list[str | Path] | str | Path,
        struct_ids_by_type: dict[str, set[str]],
        log_validation: bool = True,
    ) -> tuple[list[DRTCStructure], set[str], set[str]]:
        """Return the structures referenced by the complex controllers that exist in HyDAMO.

        Returns the valid structures, their ids, and the ids of all referenced
        structures. Raises a ValueError for duplicate structure ids.
        """
        folders = DRTCModel._as_folder_list(complex_controllers_folder)
        referenced_cc_structs = DRTCModel._collect_complex_controller_structs(folders)
        referenced_cc_structs, referenced_cc_ids = (
            DRTCModel._deduplicate_complex_controller_structs(referenced_cc_structs)
        )
        # Keep both the pre-validation references and the validated subset. The
        # pre-validation ids are needed to recognize XML references that are invalid
        # because they do not exist in HyDAMO; otherwise they are indistinguishable
        # from unrelated DIMR coupler items.
        cc_structs, cc_ids = DRTCModel._validate_complex_controller_structs(
            referenced_cc_structs, struct_ids_by_type, log_validation
        )

        return cc_structs, cc_ids, referenced_cc_ids

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _as_folder_list(
        complex_controllers_folder: list[str | Path] | str | Path,
    ) -> list[str | Path]:
        """Return one folder, or a list of folders, as a list."""
        if isinstance(complex_controllers_folder, list):
            return complex_controllers_folder
        return [complex_controllers_folder]

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _collect_complex_controller_structs(
        folders: list[str | Path],
    ) -> list[DRTCStructure]:
        """Return the structures referenced in the dimr_config.xml of each folder."""
        # Find complex controller structs and referred observation points.
        complex_controller_structs = []
        for folder in folders:
            for filepath in Path(folder).iterdir():
                if filepath.name != "dimr_config.xml":
                    continue
                root = ET.parse(filepath).getroot()
                complex_controller_structs.extend(
                    DRTCModel._parse_referenced_structures(root)
                )
        return complex_controller_structs

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _deduplicate_complex_controller_structs(
        complex_controller_structs: list[DRTCStructure],
    ) -> tuple[list[DRTCStructure], set[str]]:
        """Return each structure once, and their ids; raise a ValueError for duplicate structures.

        Observation points may occur more than once.
        """
        # Observation points can be referenced multiple times, but we keep one entry.
        # Other structures can only be defined once.
        duplicates = []
        unique_structs = {}
        for fs in complex_controller_structs:
            if fs.struct_name not in unique_structs:
                unique_structs[fs.struct_name] = fs
                continue
            if fs.struct_type != "observations":
                duplicates.append(fs.struct_name)

        if duplicates:
            msg = f"Duplicate complex controller ids found: {duplicates}"
            logger.error(msg)
            raise ValueError(msg)

        deduplicated_structs = list(unique_structs.values())
        complex_controller_ids = set(unique_structs.keys())
        return deduplicated_structs, complex_controller_ids

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _validate_complex_controller_structs(
        complex_controller_structs: list[DRTCStructure],
        struct_ids_by_type: dict[str, set[str]],
        log_validation: bool,
    ) -> tuple[list[DRTCStructure], set[str]]:
        """Return the structures that exist in HyDAMO, and their ids; log the others."""
        validated_cc_structs = []
        for fs in complex_controller_structs:
            if (
                fs.struct_type not in struct_ids_by_type
                or fs.struct_name not in struct_ids_by_type[fs.struct_type]
            ):
                msg = f"Complex controllers: reference missing from HyDAMO; skipping {fs.struct_type}/{fs.struct_name}"
                if log_validation:
                    logger.warning(msg)
            else:
                validated_cc_structs.append(fs)
        validated_cc_ids = {fs.struct_name for fs in validated_cc_structs}

        return validated_cc_structs, validated_cc_ids

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _get_struct_ids_by_type(hydamo: HyDAMO) -> dict[str, set[str]]:
        """Return the ids of the observation points and structures of HyDAMO, per type."""
        return {
            "observations": set(
                hydamo.observationpoints.observation_points.get("name", [])
            ),
            "weirs": set(hydamo.structures.rweirs_df.get("id", []))
            | set(hydamo.structures.uweirs_df.get("id", [])),
            "orifices": set(hydamo.structures.orifices_df.get("id", [])),
            "pumps": set(hydamo.structures.pumps_df.get("id", [])),
            "generalstructures": set(
                hydamo.structures.generalstructures_df.get("id", [])
            ),
            "culverts": set(hydamo.structures.culverts_df.get("id", [])),
            "bridges": set(hydamo.structures.bridges_df.get("id", [])),
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _load_complex_controllers(
        self,
        complex_controllers_folder: list[str | Path] | str | Path,
    ) -> ComplexControllers:
        """Normalize input folders, merge parsed controllers, and validate unique IDs."""
        if isinstance(complex_controllers_folder, list):
            folders = complex_controllers_folder
        else:
            folders = [complex_controllers_folder]
        parsed = [self.parse_complex_controller(Path(folder)) for folder in folders]
        # Append the XML fragments of all folders per section, and keep a single merged
        # DIMR root so downstream writers can consume index 0.
        return {
            "dataconfig_import": [x for c in parsed for x in c["dataconfig_import"]],
            "dataconfig_export": [x for c in parsed for x in c["dataconfig_export"]],
            "toolsconfig_rules": [x for c in parsed for x in c["toolsconfig_rules"]],
            "toolsconfig_triggers": [
                x for c in parsed for x in c["toolsconfig_triggers"]
            ],
            "timeseries": [x for c in parsed for x in c["timeseries"]],
            "state": [x for c in parsed for x in c["state"]],
            "dimr_config": self._merge_dimr_config_roots(
                [x for c in parsed for x in c["dimr_config"]]
            ),
        }

    @staticmethod
    def get_item_pair(item: ET.Element) -> tuple[str, str] | None:
        """Return the source and target name of a DIMR coupler item.

        Parameters
        ----------
        item : ET.Element
            An ``item`` element of a coupler.

        Returns
        -------
        tuple[str, str] or None
            ``(sourceName, targetName)``, or None if one of them is missing.
        """
        source = item.find(".//{*}sourceName")
        target = item.find(".//{*}targetName")
        if (
            source is None
            or target is None
            or source.text is None
            or target.text is None
        ):
            return None
        return source.text, target.text

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _merge_dimr_config_roots(dimr_roots: list[ET.Element]) -> list[ET.Element]:
        """Merge multiple dimr_config roots into one by combining coupler items."""
        if len(dimr_roots) <= 1:
            return dimr_roots

        # Use the first root as canonical structure/template for the merged result.
        # Remove all couplers first
        merged_root = copy.deepcopy(dimr_roots[0])
        for coupler in merged_root.findall("./{*}coupler"):
            merged_root.remove(coupler)

        # Merge couplers and items
        merged_couplers: dict[str, ET.Element] = {}
        seen_items: dict[str, set[tuple[str, str]]] = {}
        for root in dimr_roots:
            for coupler in root.findall("./{*}coupler"):
                coupler_name = coupler.attrib.get("name")
                if coupler_name is None:
                    continue

                if coupler_name not in merged_couplers:
                    # Add this coupler without items
                    mc = copy.deepcopy(coupler)
                    for item in mc.findall("./{*}item"):
                        mc.remove(item)
                    merged_root.append(mc)

                    # Initialize tracking reference
                    merged_couplers[coupler_name] = mc
                    seen_items[coupler_name] = set()

                # Only add unseen coupler items
                for item in coupler.findall("./{*}item"):
                    mitem = copy.deepcopy(item)
                    pair = DRTCModel.get_item_pair(mitem)
                    if pair is None:
                        continue

                    if pair not in seen_items[coupler_name]:
                        seen_items[coupler_name].add(pair)
                        merged_couplers[coupler_name].append(mitem)

        return [merged_root]

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_dataconfig_item(
        self, el: ET.Element
    ) -> tuple[bool, str | None, str | None]:
        """Return whether a data config item is allowed, its elementId, and why it is not."""
        allow = True
        el_text = None
        reason = None

        # Check if this is a complex controller but not in the whitelist
        # Always allow observation points
        el_id = el.find(".//{*}elementId")
        if el_id is not None and el_id.text is not None:
            el_text = el_id.text
            # In complex-controller fragments: keep observation ids, keep all when no filter is configured,
            # but reject ids that are not part of referenced/validated complex-controller structures.
            allow, reason = self._allow_struct_with_reason(
                cc_id=el_text,
                allow_observations=True,
                allow_if_filter_inactive=True,
                allow_if_not_referenced=False,
            )

        return allow, el_text, reason

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_toolsconfig_item(
        self, el: ET.Element
    ) -> tuple[bool, str | None, str | None]:
        """Return whether a rule or trigger is allowed, its id, and why it is not.

        It is allowed if all structures in its inputs, outputs, triggers and conditions
        are allowed.
        """
        allow = True
        el_firstchild_text = None
        reason = None

        el_firstchild = next(iter(el), None)
        if el_firstchild is None:
            return allow, el_firstchild_text, reason
        el_tags = []
        for tag in ["input", "output", "trigger", "condition"]:
            el_tags += el.findall(".//{*}" + tag)
        for el_tag in el_tags:
            for child in el_tag:
                if child.text is None:
                    continue
                if child.text.startswith(INPUT_PREFIX) or child.text.startswith(
                    OUTPUT_PREFIX
                ):
                    child_text = child.text.replace(INPUT_PREFIX, "").replace(
                        OUTPUT_PREFIX, ""
                    )
                    child_text = child_text.split("/")[0]

                    # Check if this is a complex controller but not in the whitelist
                    # Always allow observation points
                    if allow:
                        # In tools fragments: keep observation ids, keep all when no filter is configured,
                        # but reject ids that are not referenced by validated complex-controller structures.
                        allow, reason = self._allow_struct_with_reason(
                            cc_id=child_text,
                            allow_observations=True,
                            allow_if_filter_inactive=True,
                            allow_if_not_referenced=False,
                        )
                        el_firstchild_text = el_firstchild.get("id")

        return allow, el_firstchild_text, reason

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_dimr_item(
        self, target: ET.Element | None
    ) -> tuple[bool, str | None, str | None]:
        """Return whether a coupler item is allowed, its name if not, and why it is not."""
        allow = True
        el_text = None
        reason = None
        if target is None or not target.text:
            return allow, el_text, reason

        parts = target.text.split("/")
        if len(parts) < 3:
            return allow, target.text, reason

        _, struct_id, _ = parts

        # Check if this is a complex controller but not in the whitelist
        # For DIMR coupler items: keep observation ids and keep non-complex/non-referenced ids,
        # and only filter out referenced complex-controller ids that are not in the whitelist.
        allow, reason = self._allow_struct_with_reason(
            cc_id=struct_id,
            allow_observations=True,
            allow_if_filter_inactive=True,
            allow_if_not_referenced=True,
        )
        if not allow:
            el_text = target.text

        return allow, el_text, reason

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_referenced_structures(root: ET.Element) -> list[DRTCStructure]:
        """Return the structures in the rtc_to_flow and flow_to_rtc couplers of a DIMR config."""
        structures = []
        rtc_to_flow = root.findall(
            ".//{*}coupler[@name='rtc_to_flow']/{*}item/{*}targetName"
        )
        flow_to_rtc = root.findall(
            ".//{*}coupler[@name='flow_to_rtc']/{*}item/{*}sourceName"
        )
        for item in rtc_to_flow + flow_to_rtc:
            if item.text is None:
                continue
            structures.append(DRTCStructure(*item.text.split("/")))

        return structures

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _parse_unique_children(root: ET.Element) -> dict[str, ET.Element]:
        """Return the children of an element by tag, without namespace; raise a KeyError for duplicates."""
        # Store xml sections by tag, this function assumes unique children.
        children: dict[str, ET.Element] = {}
        for child in root:
            # remove namespace from tag
            tag = child.tag
            if tag.startswith("{"):
                tag = tag.split("}")[1]
            # Sanity check: ensure that tag does not exist yet
            if tag in children:
                raise KeyError(f"Duplicate tag '{tag}'")
            children[tag] = child

        return children

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _strip_namespace(tag: str) -> str:
        """Return a tag without its ``{namespace}``."""
        return tag.split("}", 1)[-1] if tag.startswith("{") else tag

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _dataconfig_timeseries_key(el: ET.Element) -> str | None:
        """Return the id of a timeSeries element, or None for other elements."""
        if DRTCModel._strip_namespace(el.tag) != "timeSeries":
            return None
        return el.attrib.get("id")

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _timeseries_series_key(el: ET.Element) -> str | None:
        """Return ``location|parameter`` of a series element, or None for other elements."""
        if DRTCModel._strip_namespace(el.tag) != "series":
            return None
        location = el.find("./{*}header/{*}locationId")
        parameter = el.find("./{*}header/{*}parameterId")
        if location is None or parameter is None:
            return None
        if location.text is None or parameter.text is None:
            return None
        return f"{location.text}|{parameter.text}"

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _state_leaf_key(el: ET.Element) -> str | None:
        """Return the id of a treeVectorLeaf element, or None for other elements."""
        if DRTCModel._strip_namespace(el.tag) != "treeVectorLeaf":
            return None
        return el.attrib.get("id")

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def _append_unique_elements(
        self,
        parent: ET.Element,
        elements: Sequence[str | ET.Element],
        key_getter: Callable[[ET.Element], str | None],
        file_label: str,
    ) -> None:
        """Append elements to a parent, skipping ids or XML that the parent already has, in place.

        Elements with a key (from ``key_getter``) are compared by key, others by their XML.
        Skipped elements are logged with ``file_label``.
        """
        seen_keys = set()
        seen_raw_xml = set()

        for child in list(parent):
            key = key_getter(child)
            if key is not None:
                seen_keys.add(key)
            else:
                seen_raw_xml.add(ET.tostring(child, encoding="unicode"))

        for item in elements:
            element = (
                ET.fromstring(item) if isinstance(item, str) else copy.deepcopy(item)
            )
            key = key_getter(element)
            if key is not None:
                if key in seen_keys:
                    logger.warning(
                        "%s: Skipped writing %s, id already present", file_label, key
                    )
                    continue
                seen_keys.add(key)
                parent.append(element)
                continue

            raw_xml = ET.tostring(element, encoding="unicode")
            if raw_xml in seen_raw_xml:
                logger.warning("%s: Skipped writing duplicate XML fragment", file_label)
                continue
            seen_raw_xml.add(raw_xml)
            parent.append(element)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def from_hydamo(
        self,
        pid_settings: dict | None = None,
        interval_settings: dict | None = None,
        timeseries: pd.DataFrame | None = None,
    ) -> None:
        """Add the time, PID and interval controllers of ``hydamo.management``.

        The settings that HyDAMO lacks are keyed by D-Flow FM structure id: the weir,
        orifice, pump or culvert code, or for a weir with several openings the id of
        the opening's structure (e.g. ``S_98740_3``). Structures without their own key
        get the settings under ``"global"``. Keys that match no structure with that
        type of controller are listed in one warning per settings dict.

        A structure gets one controller: when several Sturing rows with a supported
        controller type (PID, interval or time) resolve to the same structure, the
        first of them is used and the others are skipped with a warning. Rows with
        another type are skipped with a warning before any other check.

        Parameters
        ----------
        pid_settings : dict, optional
            ``ki``, ``kp``, ``kd`` and ``maxspeed`` of the PID controllers, per structure
            id and under ``"global"``. Defaults to None.
        interval_settings : dict, optional
            ``deadband`` and ``maxspeed`` of the interval controllers, per structure id
            and under ``"global"``. Defaults to None.
        timeseries : pd.DataFrame, optional
            Time series of the time controllers, with the structure ids as columns.
            Defaults to None.

        Raises
        ------
        ValueError
            For inconsistent input, e.g. a PID controller without ``pid_settings``.
        """
        # the Sturing code of the row that controls each structure: the first wins
        controlled_by: dict[str, str] = {}
        pid_structures: set[str] = set()
        interval_structures: set[str] = set()
        for _, management in self.hydamo.management.iterrows():
            resolved = self._resolve_management_structure(management)
            if resolved is None:
                continue
            structype, struc_id = resolved
            # only rows that create a controller compete for a structure
            if management.typecontroller not in ("PID", "interval", "time"):
                logger.warning(
                    f"{management.typecontroller} is not a valid controller type - skipped."
                )
                continue
            if struc_id in controlled_by:
                logger.warning(
                    "Structure %s is controlled by Sturing %s and %s. Using %s.",
                    struc_id,
                    controlled_by[struc_id],
                    management.code,
                    controlled_by[struc_id],
                )
                continue
            if (
                structype == "weir"
                and management.stuurvariabele == "bovenkant afsluitmiddel"
            ):
                steering_variable = CREST_LEVEL
            elif structype == "weir" and management.stuurvariabele == "hoogte opening":
                steering_variable = GATE_LOWER_EDGE_LEVEL
            elif structype == "pump" and management.stuurvariabele == "pompdebiet":
                steering_variable = CAPACITY
            elif (
                structype == "culvert" and management.stuurvariabele == "hoogte opening"
            ):
                steering_variable = VALVE_OPENING
            else:
                raise ValueError(
                    f"Invalid value for steering variable of {struc_id}: {management.stuurvariabele}. Allowed values are 'bovenkant afsluitmiddel' for weirs, 'hoogte opening' for oroficies and culverts, and 'pompdebiet' for pumps."
                )

            if management.doelvariabele == "waterstand":
                target_variable = "Water level (op)"
            elif management.doelvariabele == "debiet":
                target_variable = "Discharge (op)"
            else:
                raise ValueError(
                    f"Invalid value for target variable of {struc_id}: {management.doelvariabele}."
                )

            if management.typecontroller == "PID":
                if pid_settings is None:
                    raise ValueError(
                        f"{management.code} contains a PID controller, but no pid_settings are provided. Please do so."
                    )
                pid_structures.add(struc_id)
                pid = _settings_for("pid_settings", pid_settings, struc_id)
                self.add_pid_controller(
                    structure_id=struc_id,
                    steering_variable=steering_variable,
                    target_variable=target_variable,
                    ki=pid["ki"],
                    kp=pid["kp"],
                    kd=pid["kd"],
                    max_speed=pid["maxspeed"],
                    setpoint=management.streefwaarde,
                    lower_bound=management.ondergrens,
                    upper_bound=management.bovengrens,
                    observation_location=management.meetlocatieid,
                )

            elif management.typecontroller == "interval":
                if interval_settings is None:
                    raise ValueError(
                        f"{management.code} contains an interval controller, but no interval_settings are provided. Please do so."
                    )
                interval_structures.add(struc_id)
                interval = _settings_for(
                    "interval_settings", interval_settings, struc_id
                )
                self.add_interval_controller(
                    structure_id=struc_id,
                    steering_variable=steering_variable,
                    target_variable=target_variable,
                    deadband=interval["deadband"],
                    setting_above=management.bovengrens,
                    setting_below=management.ondergrens,
                    max_speed=interval["maxspeed"],
                    setpoint=management.streefwaarde,
                    observation_location=management.meetlocatieid,
                )

            elif management.typecontroller == "time":
                if timeseries is None:
                    raise ValueError(
                        f"{management.code} contains a time controller, but no time series are provided. Please do so."
                    )
                else:
                    data = timeseries.loc[:, struc_id]
                    self.add_time_controller(
                        structure_id=struc_id,
                        steering_variable=steering_variable,
                        data=data,
                    )
            controlled_by[struc_id] = management.code

        _warn_unknown_settings_keys("pid_settings", pid_settings, pid_structures)
        _warn_unknown_settings_keys(
            "interval_settings", interval_settings, interval_structures
        )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_time_controller(
        self,
        structure_id: str,
        steering_variable: str,
        data: pd.Series,
        interpolation_option: str = "LINEAR",
        extrapolation_option: str = "BLOCK",
    ) -> None:
        """Add a time controller to a structure.

        Parameters
        ----------
        structure_id : str
            Structure id.
        steering_variable : str
            Variable that is controlled, usually the crest level.
        data : pd.Series
            Time series of the setting.
        interpolation_option : str, optional
            Interpolation option. Defaults to ``"LINEAR"``.
        extrapolation_option : str, optional
            Extrapolation option. Defaults to ``"BLOCK"``.
        """
        self.time_controllers[structure_id] = {
            "type": "Time",
            "data": data,
            "steering_variable": steering_variable,
            "interpolation_option": interpolation_option,
            "extrapolation_option": extrapolation_option,
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_pid_controller(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        structure_id: str,
        steering_variable: str,
        target_variable: str,
        setpoint: Annotated[float | str | pd.Series, Field(union_mode="left_to_right")],
        lower_bound: Annotated[
            float | str | None, Field(union_mode="left_to_right")
        ] = None,
        upper_bound: Annotated[
            float | str | None, Field(union_mode="left_to_right")
        ] = None,
        observation_location: str,
        ki: float = 0.001,
        kp: float = 0.0,
        kd: float = 0.0,
        max_speed: float = 0.00033,
        interpolation_option: str = "LINEAR",
        extrapolation_option: str = "BLOCK",
    ) -> None:
        """Add a PID controller to a structure.

        All arguments are keyword-only.

        Parameters
        ----------
        structure_id : str
            Structure id.
        steering_variable : str
            Variable that is controlled, usually the crest level.
        target_variable : str
            Target variable, usually the water level.
        setpoint : float, str or pd.Series
            Setpoint, or a time series of the setpoint.
        lower_bound, upper_bound : float or str, optional
            Lowest and highest allowed setting. Default to None.
        observation_location : str
            Id of the observation point.
        ki, kp, kd : float, optional
            Gain factors. Default to 0.001, 0.0 and 0.0.
        max_speed : float, optional
            Maximum speed of change of the setting. Defaults to 0.00033.
        interpolation_option : str, optional
            Interpolation option. Defaults to ``"LINEAR"``.
        extrapolation_option : str, optional
            Extrapolation option. Defaults to ``"BLOCK"``.
        """
        self.pid_controllers[structure_id] = {
            "type": "PID",
            "steering_variable": steering_variable,
            "target_variable": target_variable,
            "setpoint": setpoint,
            "observation_point": observation_location,
            "lower_bound": lower_bound,
            "upper_bound": upper_bound,
            "ki": ki,
            "kp": kp,
            "kd": kd,
            "max_speed": max_speed,
            "interpolation_option": interpolation_option,
            "extrapolation_option": extrapolation_option,
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_interval_controller(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        structure_id: str,
        steering_variable: str,
        target_variable: str,
        deadband: Annotated[
            float | str | None, Field(union_mode="left_to_right")
        ] = None,
        setpoint: Annotated[float | str | pd.Series, Field(union_mode="left_to_right")],
        setting_below: Annotated[float | str, Field(union_mode="left_to_right")],
        setting_above: Annotated[float | str, Field(union_mode="left_to_right")],
        max_speed: Annotated[
            float | str | None, Field(union_mode="left_to_right")
        ] = None,
        observation_location: str,
        interpolation_option: str = "LINEAR",
        extrapolation_option: str = "BLOCK",
    ) -> None:
        """Add an interval controller to a structure.

        All arguments are keyword-only.

        Parameters
        ----------
        structure_id : str
            Structure id.
        steering_variable : str
            Variable that is controlled, usually the crest level.
        target_variable : str
            Target variable, usually the water level.
        deadband : float or str, optional
            Dead band around the setpoint. Defaults to None.
        setpoint : float, str or pd.Series
            Setpoint, or a time series of the setpoint.
        setting_below, setting_above : float or str
            Setting when the target variable is below or above the setpoint.
        max_speed : float or str, optional
            Maximum speed of change of the setting. Defaults to None.
        observation_location : str
            Id of the observation point.
        interpolation_option : str, optional
            Interpolation option. Defaults to ``"LINEAR"``.
        extrapolation_option : str, optional
            Extrapolation option. Defaults to ``"BLOCK"``.
        """
        self.interval_controllers[structure_id] = {
            "type": "Interval",
            "steering_variable": steering_variable,
            "target_variable": target_variable,
            "setpoint": setpoint,
            "observation_point": observation_location,
            "setting_below": setting_below,
            "setting_above": setting_above,
            "max_speed": max_speed,
            "deadband": deadband,
            "interpolation_option": interpolation_option,
            "extrapolation_option": extrapolation_option,
        }

    def set_state_from_file(
        self, state_export: str | Path, check_time: bool = True
    ) -> None:
        """Use the RTC state of an earlier model run as initial state (warm start).

        The state_export.xml of the earlier run is written as state_import.xml, including the internal
        state of the rules (e.g. the integral term of PID controllers). This assumes that the RTC configuration
        is the same as in the earlier run: state items that do not occur in the new rtcDataConfig.xml are
        skipped, and controllers that are missing in the state keep their default initial setting. Both
        are reported as a warning.

        Parameters
        ----------
        state_export : str or Path
            Path to state_export.xml, or the rtc folder of the earlier run.
        check_time : bool, optional
            Compare the time of the state (from statePI.xml next to the state file) with
            the start time of this model, and warn if they differ. Defaults to True.
        """
        path = Path(state_export)
        if path.is_dir():
            path = path / "state_export.xml"
        if not path.exists():
            raise FileNotFoundError(f"RTC state file {path} not found.")

        leaves = self._read_state_leaves(path)
        if not leaves:
            raise ValueError(f"No state items (treeVectorLeaf) found in {path}.")
        self.state_from_file = leaves
        logger.info(f"Read {len(leaves)} RTC state items from {path}.")

        if not check_time:
            return
        statepi = path.parent / "statePI.xml"
        state_time = self._read_state_time(statepi) if statepi.exists() else None
        if state_time is None:
            logger.info(
                f"No time found for the RTC state in {statepi}; the time of the state is not checked."
            )
        elif state_time != self.time_settings["start"]:
            logger.warning(
                f"The RTC state is valid for {state_time}, but the model starts at {self.time_settings['start']}."
            )

    def set_state_from_modelrun(
        self,
        his_path: str | Path,
        time: dt | pd.Timestamp | str | None = None,
        netcdf_index: int | None = None,
    ) -> dict[str, float]:
        """Use the structure settings of an earlier model run (his-file) as initial setting of the controllers.

        For every controlled structure, the steered variable (crest level, gate lower edge level, valve
        opening or pump capacity) is read from the his-file at the given time and passed to set_initial_state.
        Unlike set_state_from_file, any time step can be used, but the internal state of the rules (e.g. the
        integral term of PID controllers) is not restored.

        Parameters
        ----------
        his_path : str or Path
            Path to the his file of the earlier run.
        time : datetime, pd.Timestamp or str, optional
            Time of the settings; the nearest time step is used. Defaults to None.
        netcdf_index : int, optional
            Time index instead of a time. Defaults to None: without a time, the last
            time step.

        Returns
        -------
        dict[str, float]
            Initial setting per structure id.
        """
        if time is not None and netcdf_index is not None:
            raise ValueError("Provide either time or netcdf_index, not both.")
        if time is None and netcdf_index is None:
            logger.info(f"No time given; the last time step in {his_path} is used.")
        controllers = {
            **self.time_controllers,
            **self.interval_controllers,
            **self.pid_controllers,
        }
        kinds = {
            kind for sources in HIS_SETTING_VARIABLES.values() for kind, _ in sources
        }

        values, missing = {}, []
        with Dataset(his_path) as his:
            if time is not None:
                index = time_index(his, time)
            else:
                index = -1 if netcdf_index is None else netcdf_index
            names = {
                kind: [n.strip() for n in chartostring(his[f"{kind}_name"][:])]
                for kind in kinds
                if f"{kind}_name" in his.variables
            }
            for structure_id, controller in controllers.items():
                value = self._read_structure_setting(
                    his, names, structure_id, controller["steering_variable"], index
                )
                if value is None:
                    missing.append(structure_id)
                else:
                    values[structure_id] = value

        if missing:
            logger.warning(
                f"No setting found in {his_path} for {len(missing)} controlled structure(s), "
                f"these keep their default initial setting: {missing}"
            )
        logger.info(
            f"Initial setting of {len(values)} controlled structures read from {his_path}."
        )
        self.set_initial_state(values)
        return values

    @staticmethod
    def _read_structure_setting(
        his: Dataset,
        names: dict[str, list[str]],
        structure_id: str,
        steering_variable: str,
        index: int,
    ) -> float | None:
        """Read the setting of a structure for a steering variable from a his-file.

        The first structure type in HIS_SETTING_VARIABLES that contains the structure is used. If its value is
        missing (masked or not finite), None is returned; other structure types are not tried.

        Parameters
        ----------
        his : Dataset
            The opened his-file.
        names : dict[str, list[str]]
            Structure names per structure type in the his-file, e.g. {"weirgen": ["S_1", ...]}.
        structure_id : str
            Id of the structure.
        steering_variable : str
            Steering variable of the controller, e.g. CREST_LEVEL.
        index : int
            Time index.

        Returns
        -------
        float | None
            The setting, or None if the structure or its value is not found.
        """
        for kind, quantity in HIS_SETTING_VARIABLES.get(steering_variable, []):
            variable = f"{kind}_{quantity}"
            if (
                kind in names
                and structure_id in names[kind]
                and variable in his.variables
            ):
                value = his[variable][index, names[kind].index(structure_id)]
                if np.ma.is_masked(value) or not np.isfinite(value):
                    return None
                return float(value)
        return None

    def set_initial_state(self, values: dict[str, float]) -> None:
        """Set the initial setting of controlled structures, e.g. {"S_96840": 16.2}.

        The value is written to state_import.xml for the steered variable of the structure. It overrides the
        default initial setting and a state read with set_state_from_file.

        Parameters
        ----------
        values : dict[str, float]
            Initial setting per structure id.
        """
        self.initial_state.update(
            {str(key): float(value) for key, value in values.items()}
        )

    @staticmethod
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def finish_file(xmlroot: ET.Element, filename: Path | str) -> None:
        """Write an XML tree to a file, with an XML declaration, pretty-printed.

        Parameters
        ----------
        xmlroot : ET.Element
            Root of the XML tree.
        filename : Path or str
            File to write.
        """
        xmlbytes = bytes(
            '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>',
            encoding="utf-8",
        ) + ET.tostring(xmlroot)
        xmlstring = xmlbytes.decode("utf-8").replace("\n", "").replace("  ", "")
        with open(filename, "w+") as f:
            f.write(xmlstring)
        with open(filename) as f:
            temp = xml.dom.minidom.parseString(f.read())
        with open(filename, "w+") as f:
            f.write(temp.toprettyxml())

    def write_xml_v1(self) -> None:
        """Write all RTC XML files."""
        self.write_runtimeconfig()
        self.write_toolsconfig()
        self.write_timeseries_import()
        self.write_dataconfig()
        self.write_state_import()

    def write_runtimeconfig(self) -> None:
        """Write rtcRuntimeConfig.xml, from the template, with the model period and time step."""
        # namespaces for all other xml files
        generalname = "http://www.wldelft.nl/fews"
        xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
        gn_brackets = "{" + generalname + "}"

        # registering namespaces
        ET.register_namespace("", generalname)
        ET.register_namespace("xsi", xsi_name)

        # parsing xml file to python and get the root of the existing xml file
        configfile = ET.parse(
            os.path.join(self.template_dir, "rtcRuntimeConfig_empty.xml")
        )
        myroot = configfile.getroot()

        # convert date and runtime to required input for runtimeconfig file

        # replace start/stop dates and times in xml file
        for x in myroot.iter(gn_brackets + "startDate"):
            x.set("date", self.time_settings["start"].strftime("%Y-%m-%d"))
            x.set("time", self.time_settings["start"].strftime("%H:%M:%S"))
        for x in myroot.iter(gn_brackets + "endDate"):
            x.set("date", self.time_settings["end"].strftime("%Y-%m-%d"))
            x.set("time", self.time_settings["end"].strftime("%H:%M:%S"))
        for x in myroot.iter(gn_brackets + "timeStep"):
            x.set("unit", "second")
            x.set("divider", "1")
            x.set("multiplier", str(int(self.time_settings["step"])))

        # write new xml file
        self.finish_file(myroot, self.output_path / "rtcRuntimeConfig.xml")

    def write_toolsconfig(self) -> None:
        """Write rtcToolsConfig.xml, from the template, with the rules of all controllers."""
        generalname = "http://www.wldelft.nl/fews"
        xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
        gn_brackets = "{" + generalname + "}"

        # registering namespaces
        ET.register_namespace("", generalname)
        ET.register_namespace("xsi", xsi_name)

        # parsing xml file
        configfile = ET.parse(self.template_dir / "rtcToolsConfig_empty.xml")
        myroot = configfile.getroot()

        self.all_controllers: dict[
            str, TimeController | PIDController | IntervalController
        ] = {
            **self.time_controllers,
            **self.pid_controllers,
            **self.interval_controllers,
        }

        to_remove = []
        for key in self.all_controllers:
            controller = self.all_controllers[key]
            # For simple controllers: skip only when this id has an allowed complex controller.
            # If filtering is inactive or the id is not a referenced complex id, do not skip.
            if self.allow_struct(
                cc_id=key,
                allow_observations=False,
                allow_if_filter_inactive=False,
                allow_if_not_referenced=False,
            ):
                logger.warning(
                    f"RtcToolsConfig.xml: Skipped writing {controller['type']} control for {key}, complex controller already present"
                )
                to_remove.append(key)
                continue

            a = ET.SubElement(myroot[1], gn_brackets + "rule")
            if controller["type"] == "PID":
                # rule type (PID)
                b = ET.SubElement(a, gn_brackets + "pid")
                b.set("id", "[PID]" + "Control group " + str(key) + "/PID Rule")

                # standard settings
                c = ET.SubElement(b, gn_brackets + "mode")
                c.text = "PIDVEL"

                d = ET.SubElement(b, gn_brackets + "settingMin")
                d.text = str(controller["lower_bound"])

                e = ET.SubElement(b, gn_brackets + "settingMax")
                e.text = str(controller["upper_bound"])

                f = ET.SubElement(b, gn_brackets + "settingMaxSpeed")
                f.text = str(controller["max_speed"])

                g = ET.SubElement(b, gn_brackets + "kp")
                g.text = str(controller["kp"])

                h = ET.SubElement(b, gn_brackets + "ki")
                h.text = str(controller["ki"])

                i = ET.SubElement(b, gn_brackets + "kd")
                i.text = str(controller["kd"])

                # input
                j = ET.SubElement(b, gn_brackets + "input")

                k = ET.SubElement(j, gn_brackets + "x")
                k.text = (
                    INPUT_PREFIX
                    + controller["observation_point"]
                    + "/"
                    + controller["target_variable"]
                )

                # If setpoint varies in time
                if isinstance(controller["setpoint"], pd.Series):
                    ll = ET.SubElement(j, gn_brackets + "setpointSeries")
                    ll.text = "[SP]" + "Control group " + str(key) + "/PID Rule"
                # Else fixed setpoint
                else:
                    ll = ET.SubElement(j, gn_brackets + "setpointValue")
                    ll.text = str(controller["setpoint"])

                # output
                m = ET.SubElement(b, gn_brackets + "output")

                o = ET.SubElement(m, gn_brackets + "y")
                o.text = (
                    OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
                )

                p = ET.SubElement(m, gn_brackets + "integralPart")
                p.text = "[IP]" + "Control group " + str(key) + "/PID Rule"

                q = ET.SubElement(m, gn_brackets + "differentialPart")
                q.text = "[DP]" + "Control group " + str(key) + "/PID Rule"

            elif controller["type"] == "Interval":
                # Interval RTC
                # rule type (Interval)
                b = ET.SubElement(a, gn_brackets + "interval")
                b.set(
                    "id",
                    "[IntervalRule]" + "Control group " + str(key) + "/Interval Rule",
                )

                # standard settings
                d = ET.SubElement(b, gn_brackets + "settingBelow")
                d.text = str(controller["setting_below"])

                e = ET.SubElement(b, gn_brackets + "settingAbove")
                e.text = str(controller["setting_above"])

                f = ET.SubElement(b, gn_brackets + "settingMaxSpeed")
                f.text = str(controller["max_speed"])

                g = ET.SubElement(b, gn_brackets + "deadbandSetpointAbsolute")
                g.text = str(controller["deadband"])

                # input
                j = ET.SubElement(b, gn_brackets + "input")

                k = ET.SubElement(
                    j, gn_brackets + "x"
                )  # leave ref = "EXPLICIT" out for now
                k.text = (
                    INPUT_PREFIX
                    + controller["observation_point"]
                    + "/"
                    + controller["target_variable"]
                )
                # If setpoint varies in time
                ll = ET.SubElement(j, gn_brackets + "setpoint")
                ll.text = "[SP]" + "Control group " + str(key) + "/Interval Rule"

                # output
                m = ET.SubElement(b, gn_brackets + "output")

                o = ET.SubElement(m, gn_brackets + "y")
                o.text = (
                    OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
                )

                p = ET.SubElement(m, gn_brackets + "status")
                p.text = "[Status]" + "Control group " + str(key) + "/Interval Rule"
            # Add time rule
            else:
                # rule type (timeabsolute)
                b = ET.SubElement(a, gn_brackets + "timeAbsolute")
                b.set("id", "[TimeRule]" + "Control group " + str(key) + "/Time Rule")

                # input
                c = ET.SubElement(b, gn_brackets + "input")

                d = ET.SubElement(c, gn_brackets + "x")
                d.text = "Control group " + str(key) + "/Time Rule"

                e = ET.SubElement(b, gn_brackets + "output")

                f = ET.SubElement(e, gn_brackets + "y")
                f.text = (
                    OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
                )

        # remove controllers that have complex controllers
        for key in to_remove:
            del self.all_controllers[key]

        # elements that are parsed from user specified files should be inserted at the right place.
        if self.complex_controllers is not None:
            for ctl in self.complex_controllers["toolsconfig_rules"]:
                myroot[1].append(ET.fromstring(ctl))
            for ctl in self.complex_controllers["toolsconfig_triggers"]:
                # no trigger block present yet
                if len(myroot) == 2:
                    trigger = ET.Element(gn_brackets + "triggers")
                    myroot.append(trigger)
                    myroot[2].append(ET.fromstring(ctl))
                else:
                    myroot[2].append(ET.fromstring(ctl))

        self.finish_file(myroot, self.output_path / RTC_TOOLS_CONFIG_XML)

    def write_dataconfig(self) -> None:
        """Write rtcDataConfig.xml, from the template, with the series of all controllers."""
        generalname = "http://www.wldelft.nl/fews"
        xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
        gn_brackets = "{" + generalname + "}"
        m3unit = "m^3/s"
        munit = "m"

        # registering namespaces
        ET.register_namespace("", generalname)
        ET.register_namespace("xsi", xsi_name)

        # Parsing xml file
        configfile = ET.parse(self.template_dir / "rtcDataConfig_empty.xml")
        myroot = configfile.getroot()

        timeseries_length = len(
            ET.parse(self.output_path / "timeseries_import.xml").getroot()
        )

        # implementing standard settings import and exportdata
        a0 = ET.SubElement(myroot[1], gn_brackets + "CSVTimeSeriesFile")
        a0.set("decimalSeparator", ".")
        a0.set("delimiter", ",")
        a0.set("adjointOutput", "false")

        a1 = ET.SubElement(myroot[1], gn_brackets + "PITimeSeriesFile")

        a2 = ET.SubElement(a1, gn_brackets + "timeSeriesFile")
        a2.text = "timeseries_export.xml"

        a3 = ET.SubElement(a1, gn_brackets + "useBinFile")
        a3.text = "false"

        # implementing standard settings import and exportdata
        if timeseries_length > 0:
            # only if timeseries are written to the import
            a4 = ET.SubElement(myroot[0], gn_brackets + "PITimeSeriesFile")
            a5 = ET.SubElement(a4, gn_brackets + "timeSeriesFile")
            a5.text = TIMESERIES_IMPORT_XML
            a6 = ET.SubElement(a4, gn_brackets + "useBinFile")
            a6.text = "false"

        # weir dependable data
        for ikey, key in enumerate(self.all_controllers.keys()):
            controller = self.all_controllers[key]
            # For simple controllers: skip only when this id has an allowed complex controller.
            # If filtering is inactive or the id is not a referenced complex id, do not skip.
            if self.allow_struct(
                cc_id=key,
                allow_observations=False,
                allow_if_filter_inactive=False,
                allow_if_not_referenced=False,
            ):
                logger.warning(
                    f"{RTC_DATA_CONFIG_XML}: Skipped writing {controller['type']} control for {key}, complex controller already present"
                )
                continue

            # te importeren data
            if controller["type"] == "PID":
                input_id = (
                    INPUT_PREFIX
                    + controller["observation_point"]
                    + "/"
                    + controller["target_variable"]
                )

                if myroot[0].find(f".//*[@id='{input_id}']") is None:
                    a = ET.SubElement(myroot[0], gn_brackets + "timeSeries")
                    a.set("id", input_id)

                    b = ET.SubElement(a, gn_brackets + "OpenMIExchangeItem")

                    c = ET.SubElement(b, gn_brackets + "elementId")
                    c.text = controller["observation_point"]

                    d = ET.SubElement(b, gn_brackets + "quantityId")
                    d.text = controller["target_variable"]

                    e = ET.SubElement(b, gn_brackets + "unit")
                    e.text = (
                        munit
                        if controller["target_variable"] == "Water level (op)"
                        else m3unit
                    )

                else:
                    logger.warning(
                        f"{RTC_DATA_CONFIG_XML}: Skipped writing {input_id}, observation point already present"
                    )

                # If a time dependent setpoint is required, add the Time Rule
                if type(controller["setpoint"]) is pd.Series:
                    a2 = ET.SubElement(myroot[0], gn_brackets + "timeSeries")

                    a2.set("id", f"[SP]Control group {key}/PID Rule")
                    b2 = ET.SubElement(a2, gn_brackets + "PITimeSeries")

                    c2 = ET.SubElement(b2, gn_brackets + "locationId")
                    c2.text = f"[PID]Control group {key}/PID Rule"

                    d2 = ET.SubElement(b2, gn_brackets + "parameterId")
                    d2.text = "SP"

                    e2 = ET.SubElement(b2, gn_brackets + "interpolationOption")
                    e2.text = controller["interpolation_option"]

                    e2 = ET.SubElement(b2, gn_brackets + "extrapolationOption")
                    e2.text = controller[
                        "extrapolation_option"
                    ]  # Changed from Block: HL

            elif controller["type"] == "Interval":
                input_id = (
                    INPUT_PREFIX
                    + controller["observation_point"]
                    + "/"
                    + controller["target_variable"]
                )
                if myroot.find(f".//*[@id='{input_id}']") is None:
                    a = ET.SubElement(myroot[0], gn_brackets + "timeSeries")

                    a.set("id", input_id)

                    b = ET.SubElement(a, gn_brackets + "OpenMIExchangeItem")

                    c = ET.SubElement(b, gn_brackets + "elementId")
                    c.text = controller["observation_point"]

                    d = ET.SubElement(b, gn_brackets + "quantityId")
                    d.text = controller["target_variable"]

                    e = ET.SubElement(b, gn_brackets + "unit")
                    e.text = (
                        munit
                        if controller["target_variable"] == "Water level (op)"
                        else m3unit
                    )
                else:
                    logger.warning(
                        f"{RTC_DATA_CONFIG_XML}: Skipped writing {input_id}, observation point already present"
                    )

                if type(controller["setpoint"]) is pd.Series:
                    a2 = ET.SubElement(myroot[0], gn_brackets + "timeSeries")

                    a2.set("id", f"[SP]Control group {key}/Interval Rule")
                    b3 = ET.SubElement(a2, gn_brackets + "PITimeSeries")

                    c3 = ET.SubElement(b3, gn_brackets + "locationId")
                    c3.text = f"[IntervalRule]Control group {key}/Interval Rule"

                    d3 = ET.SubElement(b3, gn_brackets + "parameterId")
                    d3.text = "SP"

                    e3 = ET.SubElement(b3, gn_brackets + "interpolationOption")
                    e3.text = controller["interpolation_option"]

                    f3 = ET.SubElement(b3, gn_brackets + "extrapolationOption")
                    f3.text = controller[
                        "extrapolation_option"
                    ]  # Changed from Block: HL

            else:
                a = ET.SubElement(myroot[0], gn_brackets + "timeSeries")
                a.set("id", "Control group " + str(key) + "/Time Rule")
                b = ET.SubElement(a, gn_brackets + "PITimeSeries")

                c = ET.SubElement(b, gn_brackets + "locationId")
                c.text = f"[TimeRule]Control group {key}/Time Rule"

                d = ET.SubElement(b, gn_brackets + "parameterId")
                d.text = "TimeSeries"

                e = ET.SubElement(b, gn_brackets + "interpolationOption")
                e.text = controller["interpolation_option"]

                e = ET.SubElement(b, gn_brackets + "extrapolationOption")
                e.text = controller["extrapolation_option"]  # Changed from Block: HL

            # te exporteren data:
            f = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
            f.set(
                "id", OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
            )

            g = ET.SubElement(f, gn_brackets + "OpenMIExchangeItem")

            h = ET.SubElement(g, gn_brackets + "elementId")
            h.text = str(key)

            j = ET.SubElement(g, gn_brackets + "quantityId")
            j.text = controller["steering_variable"]

            k = ET.SubElement(g, gn_brackets + "unit")
            k.text = m3unit if controller["steering_variable"] == CAPACITY else munit

        for ikey, key in enumerate(self.all_controllers.keys()):
            controller = self.all_controllers[key]

            if controller["type"] == "PID":
                i = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
                i.set("id", "[IP]Control group " + str(key) + "/PID Rule")

                j = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
                j.set("id", "[DP]Control group " + str(key) + "/PID Rule")

            elif (
                controller["type"] == "Interval"
            ):  # Change slightly when working with Interval rule
                j = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
                j.set("id", "[Status]Control group " + str(key) + "/Interval Rule")

        # the parsed complex controllers should be inserted at the right place
        if self.complex_controllers is not None:
            self._append_unique_elements(
                parent=myroot[0],
                elements=self.complex_controllers["dataconfig_import"],
                key_getter=self._dataconfig_timeseries_key,
                file_label=RTC_DATA_CONFIG_XML,
            )
            self._append_unique_elements(
                parent=myroot[1],
                elements=self.complex_controllers["dataconfig_export"],
                key_getter=self._dataconfig_timeseries_key,
                file_label=RTC_DATA_CONFIG_XML,
            )

        self.finish_file(myroot, self.output_path / RTC_DATA_CONFIG_XML)
        self._written_dataconfig_ids = self._element_ids(myroot)

    def write_timeseries_import(self) -> None:
        """Write timeseries_import.xml, from the template, with the time series of the controllers."""
        generalname = "http://www.wldelft.nl/fews/PI"
        xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
        gn_brackets = "{" + generalname + "}"

        # registering namespaces
        ET.register_namespace("", generalname)
        ET.register_namespace("xsi", xsi_name)

        # Parsing xml file
        configfile = ET.parse(self.template_dir / "timeseries_import_empty.xml")
        myroot = configfile.getroot()

        for key in self.all_controllers:
            controller = self.all_controllers[key]
            # For simple controllers: skip only when this id has an allowed complex controller.
            # If filtering is inactive or the id is not a referenced complex id, do not skip.
            if self.allow_struct(
                cc_id=key,
                allow_observations=False,
                allow_if_filter_inactive=False,
                allow_if_not_referenced=False,
            ):
                logger.warning(
                    f"{TIMESERIES_IMPORT_XML}: Skipped writing {controller['type']} control for {key}, complex controller already present"
                )
                continue

            if controller["type"] == "Time":
                # te importeren data
                dates = pd.to_datetime(controller["data"].index).strftime("%Y-%m-%d")
                times = pd.to_datetime(controller["data"].index).strftime("%H:%M:%S")
                timestep = (
                    pd.to_datetime(controller["data"].index)[1]
                    - pd.to_datetime(controller["data"].index)[0]
                ).total_seconds()
                a = ET.SubElement(myroot, gn_brackets + "series")
                b = ET.SubElement(a, gn_brackets + "header")
                c = ET.SubElement(b, gn_brackets + "type")
                c.text = "instantaneous"
                d = ET.SubElement(b, gn_brackets + "locationId")
                d.text = f"[TimeRule]Control group {key}/Time Rule"
                e = ET.SubElement(b, gn_brackets + "parameterId")
                e.text = "TimeSeries"
                f = ET.SubElement(b, gn_brackets + "timeStep")
                f.attrib = {
                    "unit": "minute",
                    "multiplier": str(int(timestep / 60.0)),
                    "divider": str(1),
                }
                g = ET.SubElement(b, gn_brackets + "startDate")
                g.attrib = {"date": dates[0], "time": times[0]}
                h = ET.SubElement(b, gn_brackets + "endDate")
                h.attrib = {"date": dates[-1], "time": times[-1]}
                i = ET.SubElement(b, gn_brackets + "missVal")
                i.text = "-999.0"
                j = ET.SubElement(b, gn_brackets + "stationName")
                j.text = ""
                for event_date, event_time, value in zip(
                    dates, times, controller["data"].to_numpy()
                ):
                    k = ET.SubElement(a, gn_brackets + "event")
                    k.attrib = {
                        "date": event_date,
                        "time": event_time,
                        "value": str(value),
                    }
            elif controller["type"] == "Interval":
                setpoint = controller["setpoint"]
                if isinstance(setpoint, float):
                    setpoint = pd.Series(
                        [setpoint, setpoint],
                        index=[self.time_settings["start"], self.time_settings["end"]],
                    )
                    controller["setpoint"] = setpoint
                if isinstance(setpoint, str):
                    raise TypeError(
                        f"Setpoint {setpoint!r} of interval controller {key} must be a number or a pd.Series."
                    )

                # te importeren data
                dates = pd.to_datetime(setpoint.index).strftime("%Y-%m-%d")
                times = pd.to_datetime(setpoint.index).strftime("%H:%M:%S")
                timestep = (
                    pd.to_datetime(f"{dates[1]} {times[1]}")
                    - pd.to_datetime(f"{dates[0]} {times[0]}")
                ).total_seconds()

                a = ET.SubElement(myroot, gn_brackets + "series")
                b = ET.SubElement(a, gn_brackets + "header")
                c = ET.SubElement(b, gn_brackets + "type")
                c.text = "instantaneous"

                d = ET.SubElement(b, gn_brackets + "locationId")
                d.text = f"[IntervalRule]Control group {key}/Interval Rule"

                e = ET.SubElement(b, gn_brackets + "parameterId")
                e.text = "SP"
                f = ET.SubElement(b, gn_brackets + "timeStep")
                f.attrib = {
                    "unit": "minute",
                    "multiplier": str(int(timestep / 60.0)),
                    "divider": str(1),
                }
                g = ET.SubElement(b, gn_brackets + "startDate")
                g.attrib = {"date": dates[0], "time": times[0]}
                h = ET.SubElement(b, gn_brackets + "endDate")
                h.attrib = {"date": dates[-1], "time": times[-1]}
                i = ET.SubElement(b, gn_brackets + "missVal")
                i.text = "-999.0"
                for event_date, event_time, value in zip(
                    dates, times, setpoint.to_numpy()
                ):
                    k = ET.SubElement(a, gn_brackets + "event")
                    k.attrib = {
                        "date": event_date,
                        "time": event_time,
                        "value": str(value),
                    }

            # Create a timeseries import if a time-dependent setpoint is used
            elif controller["type"] == "PID" and isinstance(
                controller["setpoint"], pd.Series
            ):
                # te importeren data
                dates = pd.to_datetime(controller["setpoint"].index).strftime(
                    "%Y-%m-%d"
                )
                times = pd.to_datetime(controller["setpoint"].index).strftime(
                    "%H:%M:%S"
                )
                timestep = (
                    pd.to_datetime(controller["setpoint"].index)[1]
                    - pd.to_datetime(controller["setpoint"].index)[0]
                ).total_seconds()
                a = ET.SubElement(myroot, gn_brackets + "series")
                b = ET.SubElement(a, gn_brackets + "header")
                c = ET.SubElement(b, gn_brackets + "type")
                c.text = "instantaneous"

                d = ET.SubElement(b, gn_brackets + "locationId")
                d.text = f"[PID]Control group {key}/PID Rule"

                e = ET.SubElement(b, gn_brackets + "parameterId")
                e.text = "SP"
                f = ET.SubElement(b, gn_brackets + "timeStep")
                f.attrib = {
                    "unit": "minute",
                    "multiplier": str(int(timestep / 60.0)),
                    "divider": str(1),
                }
                g = ET.SubElement(b, gn_brackets + "startDate")
                g.attrib = {"date": dates[0], "time": times[0]}
                h = ET.SubElement(b, gn_brackets + "endDate")
                h.attrib = {"date": dates[-1], "time": times[-1]}
                i = ET.SubElement(b, gn_brackets + "missVal")
                i.text = "-999.0"
                j = ET.SubElement(b, gn_brackets + "stationName")
                j.text = ""
                for event_date, event_time, value in zip(
                    dates, times, controller["setpoint"].to_numpy()
                ):
                    k = ET.SubElement(a, gn_brackets + "event")
                    k.attrib = {
                        "date": event_date,
                        "time": event_time,
                        "value": str(value),
                    }

        if self.complex_controllers is not None:
            self._append_unique_elements(
                parent=myroot,
                elements=self.complex_controllers["timeseries"],
                key_getter=self._timeseries_series_key,
                file_label=TIMESERIES_IMPORT_XML,
            )

        self.finish_file(myroot, self.output_path / TIMESERIES_IMPORT_XML)

    def write_state_import(self) -> None:
        """Write state_import.xml, from the template, with the initial state of the controllers."""
        generalname = "http://www.openda.org"
        xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
        gn_brackets = "{" + generalname + "}"

        # registering namespaces
        ET.register_namespace("", generalname)
        ET.register_namespace("xsi", xsi_name)

        # Parsing xml file
        configfile = ET.parse(self.template_dir / "state_import_empty.xml")
        myroot = configfile.getroot()

        a0 = ET.SubElement(myroot, gn_brackets + "treeVector")

        for key in self.all_controllers:
            controller = self.all_controllers[key]
            # For simple controllers: skip only when this id has an allowed complex controller.
            # If filtering is inactive or the id is not a referenced complex id, do not skip.
            if self.allow_struct(
                cc_id=key,
                allow_observations=False,
                allow_if_filter_inactive=False,
                allow_if_not_referenced=False,
            ):
                logger.warning(
                    f"{STATE_IMPORT_XML}: Skipped writing {controller['type']} control for {key}, complex controller already present"
                )
                continue

            # te importeren data
            a = ET.SubElement(a0, gn_brackets + "treeVectorLeaf")
            a.attrib = {
                "id": OUTPUT_PREFIX + key + "/" + controller["steering_variable"]
            }
            b = ET.SubElement(a, gn_brackets + "vector")
            if controller["type"] == "PID":
                b.text = str(self._initial_pid_setting(key, controller))
            elif controller["type"] == "Interval":
                # Take the maximum value as a starting value
                b.text = str(
                    max(
                        float(controller["setting_above"]),
                        float(controller["setting_below"]),
                    )
                )
            else:
                b.text = str(controller["data"].to_numpy()[0])

        # the parsed complex controllers should be inserted at the right place
        if self.complex_controllers is not None:
            self._append_unique_elements(
                parent=myroot[0],
                elements=self.complex_controllers["state"],
                key_getter=self._state_leaf_key,
                file_label=STATE_IMPORT_XML,
            )

        # a state from an earlier model run and user-defined initial settings override the defaults
        self._apply_state_overrides(myroot[0], gn_brackets)

        self.finish_file(myroot, self.output_path / STATE_IMPORT_XML)

    def _initial_pid_setting(
        self, structure_id: str, controller: PIDController
    ) -> float | str | None:
        """Return the initial setting of a PID controller.

        That is the current setting of the structure, limited to the bounds of the
        controller. Falls back to the upper bound if the structure setting is not available.
        """
        setting = self._structure_setting(structure_id, controller["steering_variable"])
        if setting is None:
            return controller["upper_bound"]
        lower_bound, upper_bound = controller["lower_bound"], controller["upper_bound"]
        if lower_bound is None or upper_bound is None:
            return setting
        try:
            lower, upper = float(lower_bound), float(upper_bound)
        except ValueError:
            return setting
        return min(max(setting, lower), upper)

    def _structure_setting(
        self, structure_id: str, steering_variable: str
    ) -> float | None:
        """Get the setting of a structure for a steering variable from the structure dataframes.

        These are the columns of the HyDAMO structure tables; set_state_from_modelrun reads the corresponding
        his-file variables, which also include values that are not in these tables (e.g. culvert gate levels).
        """
        for attribute, column in STRUCTURE_SETTING_COLUMNS.get(steering_variable, []):
            df = getattr(self.hydamo.structures, attribute, None)
            if (
                df is None
                or df.empty
                or "id" not in df.columns
                or column not in df.columns
            ):
                continue
            values = df.loc[df["id"] == structure_id, column]
            if len(values) > 0 and pd.notna(values.iloc[0]):
                try:
                    return float(values.iloc[0])
                except (TypeError, ValueError):
                    return None
        return None

    def _apply_state_overrides(self, tree_vector: ET.Element, gn_brackets: str) -> None:
        """Apply the state from set_state_from_file and the values from set_initial_state to the tree vector."""
        leaf_tag = gn_brackets + "treeVectorLeaf"
        vector_tag = gn_brackets + "vector"
        if self.state_from_file is not None:
            self._apply_state_from_file(
                self.state_from_file, tree_vector, leaf_tag, vector_tag
            )
        self._apply_initial_state(tree_vector, leaf_tag, vector_tag)

    def _apply_state_from_file(
        self,
        state: dict[str, str],
        tree_vector: ET.Element,
        leaf_tag: str,
        vector_tag: str,
    ) -> None:
        """Write the state read with set_state_from_file to the tree vector.

        Items that are not part of this RTC model are skipped; leaves that are not in the state keep
        their default value.

        Parameters
        ----------
        state : dict[str, str]
            Vector (as text) per leaf id, from set_state_from_file.
        tree_vector : ET.Element
            The treeVector element of state_import.xml.
        leaf_tag : str
            Tag of the treeVectorLeaf elements, including the namespace.
        vector_tag : str
            Tag of the vector elements, including the namespace.
        """
        valid_ids = self._dataconfig_ids()
        current = self._leaves_by_id(tree_vector, leaf_tag)
        skipped = []
        for leaf_id, vector in state.items():
            if valid_ids is not None and leaf_id not in valid_ids:
                skipped.append(leaf_id)
                continue
            if leaf_id not in current:
                current[leaf_id] = ET.SubElement(tree_vector, leaf_tag, {"id": leaf_id})
            self._leaf_vector(current[leaf_id], vector_tag).text = vector

        missing = [leaf_id for leaf_id in current if leaf_id not in state]
        if skipped:
            logger.warning(
                f"{STATE_IMPORT_XML}: {len(skipped)} state item(s) are not part of this RTC model and are skipped: {skipped[:10]}"
            )
        if missing:
            logger.warning(
                f"{STATE_IMPORT_XML}: {len(missing)} item(s) are not in the state file and keep their default value: {missing[:10]}"
            )

    def _apply_initial_state(
        self, tree_vector: ET.Element, leaf_tag: str, vector_tag: str
    ) -> None:
        """Write the values from set_initial_state to the output leaves of the controlled structures.

        Parameters
        ----------
        tree_vector : ET.Element
            The treeVector element of state_import.xml.
        leaf_tag : str
            Tag of the treeVectorLeaf elements, including the namespace.
        vector_tag : str
            Tag of the vector elements, including the namespace.
        """
        current = self._leaves_by_id(tree_vector, leaf_tag)
        for structure_id, value in self.initial_state.items():
            prefix = f"{OUTPUT_PREFIX}{structure_id}/"
            matches = [leaf_id for leaf_id in current if leaf_id.startswith(prefix)]
            if not matches:
                logger.warning(
                    f"{STATE_IMPORT_XML}: no controlled structure {structure_id}, initial state not set."
                )
            for leaf_id in matches:
                self._leaf_vector(current[leaf_id], vector_tag).text = str(value)

    @staticmethod
    def _leaves_by_id(tree_vector: ET.Element, leaf_tag: str) -> dict[str, ET.Element]:
        """Return the treeVectorLeaf elements of the tree vector by id; leaves without an id are skipped.

        Parameters
        ----------
        tree_vector : ET.Element
            The treeVector element of state_import.xml.
        leaf_tag : str
            Tag of the treeVectorLeaf elements, including the namespace.

        Returns
        -------
        dict[str, ET.Element]
            treeVectorLeaf element per id.
        """
        leaves = {}
        for leaf in tree_vector.iter(leaf_tag):
            leaf_id = leaf.get("id")
            if leaf_id is not None:
                leaves[leaf_id] = leaf
        return leaves

    @staticmethod
    def _leaf_vector(leaf: ET.Element, vector_tag: str) -> ET.Element:
        """Return the vector element of a treeVectorLeaf, created if it is missing.

        Parameters
        ----------
        leaf : ET.Element
            A treeVectorLeaf element.
        vector_tag : str
            Tag of the vector elements, including the namespace.

        Returns
        -------
        ET.Element
            The (new) vector element of the leaf.
        """
        vector = leaf.find(vector_tag)
        if vector is None:
            vector = ET.SubElement(leaf, vector_tag)
        return vector

    def _dataconfig_ids(self) -> set[str] | None:
        """Return the ids of all time series in rtcDataConfig.xml, or None if it has not been written yet.

        Uses the ids from write_dataconfig of this model; reads the file only if the data config was not written
        by this model (e.g. write_state_import called on its own).
        """
        if self._written_dataconfig_ids is not None:
            return self._written_dataconfig_ids
        path = self.output_path / RTC_DATA_CONFIG_XML
        if not path.exists():
            return None
        return self._element_ids(ET.parse(path).getroot())

    @staticmethod
    def _element_ids(root: ET.Element) -> set[str]:
        """Ids of all elements in an XML tree that have an id attribute."""
        ids = set()
        for el in root.iter():
            el_id = el.get("id")
            if el_id is not None:
                ids.add(el_id)
        return ids

    @staticmethod
    def _read_state_leaves(path: Path) -> dict[str, str]:
        """Read the id and vector of all treeVectorLeaf elements of an RTC state file."""
        leaves = {}
        for el in ET.parse(path).getroot().iter():
            if DRTCModel._strip_namespace(el.tag) != "treeVectorLeaf":
                continue
            vector = next(
                (c for c in el if DRTCModel._strip_namespace(c.tag) == "vector"), None
            )
            leaf_id = el.get("id")
            if leaf_id is not None and vector is not None and vector.text is not None:
                leaves[leaf_id] = " ".join(vector.text.split())
        return leaves

    @staticmethod
    def _read_state_time(path: Path) -> pd.Timestamp | None:
        """Read the time of an RTC state from a statePI.xml file."""
        for el in ET.parse(path).getroot().iter():
            if (
                DRTCModel._strip_namespace(el.tag) == "dateTime"
                and el.get("date") is not None
            ):
                return pd.Timestamp(f"{el.get('date')} {el.get('time', '00:00:00')}")
        return None
__init__(hydamo: HyDAMO, fm: FMModel, output_path: str | Path | None = None, rtc_onlytimeseries: bool = False, rtc_timeseriesdata: pd.DataFrame | None = None, complex_controllers_folder: list[str | Path] | str | Path | None = None, id_limit_complex_controllers: list[str] | None = None, rtc_timestep: float = 60) -> None

Initialize the DRTCModel.

Internal controller dictionaries and output paths are initialized, optional complex-controller XML is parsed, and RTC template files are copied to the output folder.

Parameters

hydamo : HyDAMO The HyDAMO data, with the structures and management. fm : FMModel The FM model; its reference date and times set the RTC period. output_path : str or Path, optional Folder in which an rtc subfolder is created for the RTC files. Defaults to None: the current working directory. rtc_onlytimeseries : bool, optional Build the RTC control from rtc_timeseriesdata only; complex_controllers_folder is then ignored. Defaults to False. rtc_timeseriesdata : pd.DataFrame, optional Time series used with rtc_onlytimeseries, with the structure ids as columns. Defaults to None. complex_controllers_folder : list[Path or str], Path or str, optional Folder(s) with custom RTC XML files to import, without rtc_onlytimeseries. Defaults to None. id_limit_complex_controllers : list[str], optional Ids that may be coupled to complex controllers. Required with complex_controllers_folder; an empty list allows no ids. Defaults to None. rtc_timestep : float, optional Time step of the RTC model (s). Defaults to 60.

Source code in hydrolib/dhydamo/core/drtc.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def __init__(
    self,
    hydamo: HyDAMO,
    fm: FMModel,
    output_path: str | Path | None = None,
    rtc_onlytimeseries: bool = False,
    rtc_timeseriesdata: pd.DataFrame | None = None,
    complex_controllers_folder: list[str | Path] | str | Path | None = None,
    id_limit_complex_controllers: list[str] | None = None,
    rtc_timestep: float = 60,
) -> None:
    """Initialize the DRTCModel.

    Internal controller dictionaries and output paths are initialized, optional
    complex-controller XML is parsed, and RTC template files are copied to the
    output folder.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO data, with the structures and management.
    fm : FMModel
        The FM model; its reference date and times set the RTC period.
    output_path : str or Path, optional
        Folder in which an ``rtc`` subfolder is created for the RTC files. Defaults to
        None: the current working directory.
    rtc_onlytimeseries : bool, optional
        Build the RTC control from ``rtc_timeseriesdata`` only;
        ``complex_controllers_folder`` is then ignored. Defaults to False.
    rtc_timeseriesdata : pd.DataFrame, optional
        Time series used with ``rtc_onlytimeseries``, with the structure ids as
        columns. Defaults to None.
    complex_controllers_folder : list[Path or str], Path or str, optional
        Folder(s) with custom RTC XML files to import, without
        ``rtc_onlytimeseries``. Defaults to None.
    id_limit_complex_controllers : list[str], optional
        Ids that may be coupled to complex controllers. Required with
        ``complex_controllers_folder``; an empty list allows no ids. Defaults to None.
    rtc_timestep : float, optional
        Time step of the RTC model (s). Defaults to 60.
    """
    self.hydamo = hydamo

    self.time_settings: TimeSettings = {
        "start": pd.to_datetime(fm.time.refdate, format="%Y%m%d"),
        "end": pd.to_datetime(fm.time.refdate, format="%Y%m%d")
        + pd.to_timedelta(fm.time.tstop, unit="s"),
        "step": rtc_timestep,
    }

    self.pid_controllers: dict[str, PIDController] = {}
    self.time_controllers: dict[str, TimeController] = {}
    self.interval_controllers: dict[str, IntervalController] = {}

    # initial state: from an earlier model run (set_state_from_file) and/or per structure (set_initial_state)
    self.state_from_file: dict[str, str] | None = None
    self.initial_state: dict[str, float] = {}
    # ids of the time series in rtcDataConfig.xml, set by write_dataconfig
    self._written_dataconfig_ids: set[str] | None = None

    # set up the output path
    base_output_path = Path(".") if output_path is None else Path(output_path)
    self.output_path = base_output_path / "rtc"
    self.output_path.mkdir(parents=True, exist_ok=True)

    # Save object id by type
    self.struct_ids_by_type = DRTCModel._get_struct_ids_by_type(self.hydamo)

    # parse user-provided controllers
    self.complex_controllers: ComplexControllers | None = None
    self.cc_structs = None
    self.cc_ids = None
    self.cc_referenced_ids = None
    self.cc_id_limit = None
    if rtc_onlytimeseries and complex_controllers_folder is not None:
        # User supplied controllers in timeseries_only mode, emit warning
        logger.warning(
            "`complex_controllers_folder` is ignored because `rtc_onlytimeseries=True`. "
            "Set `rtc_onlytimeseries=False` to enable complex controllers."
        )
    elif not rtc_onlytimeseries and complex_controllers_folder is not None:
        if id_limit_complex_controllers is None:
            # When complex_controllers_folder is supplied, the whitelist
            # needs to be supplied as well
            raise SyntaxError(
                "Missing required `id_limit_complex_controllers` while "
                "`complex_controllers_folder` is provided. Supply a list of "
                "allowed IDs to couple to complex controller logic."
            )

        # Discover complex-controller references before and after HyDAMO validation.
        #
        # These are intentionally two separate concepts:
        # - cc_referenced_ids: all structure ids mentioned in the user-provided
        #   complex-controller dimr_config.xml files.
        # - cc_ids: only the referenced ids that also exist in the HyDAMO model.
        #
        # The distinction matters when filtering DIMR couplers. A referenced id
        # that is missing from HyDAMO must be removed from the complex-controller
        # XML. If we only kept the validated set, that invalid id would look like
        # an unrelated/non-complex DIMR item and could accidentally pass through.
        (
            self.cc_structs,
            self.cc_ids,
            self.cc_referenced_ids,
        ) = self._load_complex_controller_structs(
            complex_controllers_folder,
            self.struct_ids_by_type,
            log_validation=True,
        )
        logger.info(
            "Complex controllers: found %d unique structure references in dimr_config.xml: %s",
            len(self.cc_referenced_ids),
            self.cc_referenced_ids,
        )
        logger.info(
            "Complex controllers: matched %d references to HyDAMO structures: %s",
            len(self.cc_ids),
            self.cc_ids,
        )

        # Save whitelist of allowed controller ids.
        self.cc_id_limit = set(id_limit_complex_controllers)
        if len(self.cc_id_limit) == 0:
            logger.warning(
                "`id_limit_complex_controllers` is empty. No IDs are allowed, "
                "so all complex controller references will be filtered out."
            )
        else:
            logger.info(
                "Complex controllers: applying id_limit_complex_controllers with %d allowed IDs: %s",
                len(self.cc_id_limit),
                self.cc_id_limit,
            )

        # Load complex controllers
        self.complex_controllers = self._load_complex_controllers(
            complex_controllers_folder
        )

    # copy files from the template RTC-folder
    self.template_dir = Path(__file__).resolve().parent / ".." / "resources" / "RTC"
    for filepath in self.template_dir.iterdir():
        if filepath.suffix in {".xsd", ".json"}:
            shutil.copy(filepath, self.output_path / filepath.name)

    if rtc_onlytimeseries:
        if rtc_timeseriesdata is None:
            raise ValueError(
                "`rtc_timeseriesdata` is required when `rtc_onlytimeseries=True`."
            )
        for name, data in rtc_timeseriesdata.items():
            if name in hydamo.structures.rweirs_df.id.to_list():
                steering_var = CREST_LEVEL
            if name in hydamo.structures.orifices_df.id.to_list():
                steering_var = GATE_LOWER_EDGE_LEVEL
            if name in hydamo.structures.pumps_df.id.to_list():
                steering_var = CAPACITY
            self.add_time_controller(
                structure_id=str(name), steering_variable=steering_var, data=data
            )
        self.check_timeseries(rtc_timeseriesdata)
        self.complex_controllers = None
add_interval_controller(*, structure_id: str, steering_variable: str, target_variable: str, deadband: Annotated[float | str | None, Field(union_mode=left_to_right)] = None, setpoint: Annotated[float | str | pd.Series, Field(union_mode=left_to_right)], setting_below: Annotated[float | str, Field(union_mode=left_to_right)], setting_above: Annotated[float | str, Field(union_mode=left_to_right)], max_speed: Annotated[float | str | None, Field(union_mode=left_to_right)] = None, observation_location: str, interpolation_option: str = 'LINEAR', extrapolation_option: str = 'BLOCK') -> None

Add an interval controller to a structure.

All arguments are keyword-only.

Parameters

structure_id : str Structure id. steering_variable : str Variable that is controlled, usually the crest level. target_variable : str Target variable, usually the water level. deadband : float or str, optional Dead band around the setpoint. Defaults to None. setpoint : float, str or pd.Series Setpoint, or a time series of the setpoint. setting_below, setting_above : float or str Setting when the target variable is below or above the setpoint. max_speed : float or str, optional Maximum speed of change of the setting. Defaults to None. observation_location : str Id of the observation point. interpolation_option : str, optional Interpolation option. Defaults to "LINEAR". extrapolation_option : str, optional Extrapolation option. Defaults to "BLOCK".

Source code in hydrolib/dhydamo/core/drtc.py
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_interval_controller(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    structure_id: str,
    steering_variable: str,
    target_variable: str,
    deadband: Annotated[
        float | str | None, Field(union_mode="left_to_right")
    ] = None,
    setpoint: Annotated[float | str | pd.Series, Field(union_mode="left_to_right")],
    setting_below: Annotated[float | str, Field(union_mode="left_to_right")],
    setting_above: Annotated[float | str, Field(union_mode="left_to_right")],
    max_speed: Annotated[
        float | str | None, Field(union_mode="left_to_right")
    ] = None,
    observation_location: str,
    interpolation_option: str = "LINEAR",
    extrapolation_option: str = "BLOCK",
) -> None:
    """Add an interval controller to a structure.

    All arguments are keyword-only.

    Parameters
    ----------
    structure_id : str
        Structure id.
    steering_variable : str
        Variable that is controlled, usually the crest level.
    target_variable : str
        Target variable, usually the water level.
    deadband : float or str, optional
        Dead band around the setpoint. Defaults to None.
    setpoint : float, str or pd.Series
        Setpoint, or a time series of the setpoint.
    setting_below, setting_above : float or str
        Setting when the target variable is below or above the setpoint.
    max_speed : float or str, optional
        Maximum speed of change of the setting. Defaults to None.
    observation_location : str
        Id of the observation point.
    interpolation_option : str, optional
        Interpolation option. Defaults to ``"LINEAR"``.
    extrapolation_option : str, optional
        Extrapolation option. Defaults to ``"BLOCK"``.
    """
    self.interval_controllers[structure_id] = {
        "type": "Interval",
        "steering_variable": steering_variable,
        "target_variable": target_variable,
        "setpoint": setpoint,
        "observation_point": observation_location,
        "setting_below": setting_below,
        "setting_above": setting_above,
        "max_speed": max_speed,
        "deadband": deadband,
        "interpolation_option": interpolation_option,
        "extrapolation_option": extrapolation_option,
    }
add_pid_controller(*, structure_id: str, steering_variable: str, target_variable: str, setpoint: Annotated[float | str | pd.Series, Field(union_mode=left_to_right)], lower_bound: Annotated[float | str | None, Field(union_mode=left_to_right)] = None, upper_bound: Annotated[float | str | None, Field(union_mode=left_to_right)] = None, observation_location: str, ki: float = 0.001, kp: float = 0.0, kd: float = 0.0, max_speed: float = 0.00033, interpolation_option: str = 'LINEAR', extrapolation_option: str = 'BLOCK') -> None

Add a PID controller to a structure.

All arguments are keyword-only.

Parameters

structure_id : str Structure id. steering_variable : str Variable that is controlled, usually the crest level. target_variable : str Target variable, usually the water level. setpoint : float, str or pd.Series Setpoint, or a time series of the setpoint. lower_bound, upper_bound : float or str, optional Lowest and highest allowed setting. Default to None. observation_location : str Id of the observation point. ki, kp, kd : float, optional Gain factors. Default to 0.001, 0.0 and 0.0. max_speed : float, optional Maximum speed of change of the setting. Defaults to 0.00033. interpolation_option : str, optional Interpolation option. Defaults to "LINEAR". extrapolation_option : str, optional Extrapolation option. Defaults to "BLOCK".

Source code in hydrolib/dhydamo/core/drtc.py
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_pid_controller(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    structure_id: str,
    steering_variable: str,
    target_variable: str,
    setpoint: Annotated[float | str | pd.Series, Field(union_mode="left_to_right")],
    lower_bound: Annotated[
        float | str | None, Field(union_mode="left_to_right")
    ] = None,
    upper_bound: Annotated[
        float | str | None, Field(union_mode="left_to_right")
    ] = None,
    observation_location: str,
    ki: float = 0.001,
    kp: float = 0.0,
    kd: float = 0.0,
    max_speed: float = 0.00033,
    interpolation_option: str = "LINEAR",
    extrapolation_option: str = "BLOCK",
) -> None:
    """Add a PID controller to a structure.

    All arguments are keyword-only.

    Parameters
    ----------
    structure_id : str
        Structure id.
    steering_variable : str
        Variable that is controlled, usually the crest level.
    target_variable : str
        Target variable, usually the water level.
    setpoint : float, str or pd.Series
        Setpoint, or a time series of the setpoint.
    lower_bound, upper_bound : float or str, optional
        Lowest and highest allowed setting. Default to None.
    observation_location : str
        Id of the observation point.
    ki, kp, kd : float, optional
        Gain factors. Default to 0.001, 0.0 and 0.0.
    max_speed : float, optional
        Maximum speed of change of the setting. Defaults to 0.00033.
    interpolation_option : str, optional
        Interpolation option. Defaults to ``"LINEAR"``.
    extrapolation_option : str, optional
        Extrapolation option. Defaults to ``"BLOCK"``.
    """
    self.pid_controllers[structure_id] = {
        "type": "PID",
        "steering_variable": steering_variable,
        "target_variable": target_variable,
        "setpoint": setpoint,
        "observation_point": observation_location,
        "lower_bound": lower_bound,
        "upper_bound": upper_bound,
        "ki": ki,
        "kp": kp,
        "kd": kd,
        "max_speed": max_speed,
        "interpolation_option": interpolation_option,
        "extrapolation_option": extrapolation_option,
    }
add_time_controller(structure_id: str, steering_variable: str, data: pd.Series, interpolation_option: str = 'LINEAR', extrapolation_option: str = 'BLOCK') -> None

Add a time controller to a structure.

Parameters

structure_id : str Structure id. steering_variable : str Variable that is controlled, usually the crest level. data : pd.Series Time series of the setting. interpolation_option : str, optional Interpolation option. Defaults to "LINEAR". extrapolation_option : str, optional Extrapolation option. Defaults to "BLOCK".

Source code in hydrolib/dhydamo/core/drtc.py
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_time_controller(
    self,
    structure_id: str,
    steering_variable: str,
    data: pd.Series,
    interpolation_option: str = "LINEAR",
    extrapolation_option: str = "BLOCK",
) -> None:
    """Add a time controller to a structure.

    Parameters
    ----------
    structure_id : str
        Structure id.
    steering_variable : str
        Variable that is controlled, usually the crest level.
    data : pd.Series
        Time series of the setting.
    interpolation_option : str, optional
        Interpolation option. Defaults to ``"LINEAR"``.
    extrapolation_option : str, optional
        Extrapolation option. Defaults to ``"BLOCK"``.
    """
    self.time_controllers[structure_id] = {
        "type": "Time",
        "data": data,
        "steering_variable": steering_variable,
        "interpolation_option": interpolation_option,
        "extrapolation_option": extrapolation_option,
    }
allow_struct(cc_id: str, allow_observations: bool = False, allow_if_filter_inactive: bool = True, allow_if_not_referenced: bool = False) -> bool

Return whether a structure id is allowed by the complex-controller filter.

Parameters

cc_id : str Structure or observation id to evaluate. allow_observations : bool, optional Pass through observation ids that exist in the HyDAMO model. Defaults to False. allow_if_filter_inactive : bool, optional Return value when no complex controller filter is active (cc_referenced_ids or cc_id_limit is None). Defaults to True. allow_if_not_referenced : bool, optional Return value when filtering is active, but cc_id is not in cc_referenced_ids. Defaults to False.

Returns

bool Whether the id is allowed.

Source code in hydrolib/dhydamo/core/drtc.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def allow_struct(
    self,
    cc_id: str,
    allow_observations: bool = False,
    allow_if_filter_inactive: bool = True,
    allow_if_not_referenced: bool = False,
) -> bool:
    """Return whether a structure id is allowed by the complex-controller filter.

    Parameters
    ----------
    cc_id : str
        Structure or observation id to evaluate.
    allow_observations : bool, optional
        Pass through observation ids that exist in the HyDAMO model. Defaults to
        False.
    allow_if_filter_inactive : bool, optional
        Return value when no complex controller filter is active
        (``cc_referenced_ids`` or ``cc_id_limit`` is None). Defaults to True.
    allow_if_not_referenced : bool, optional
        Return value when filtering is active, but ``cc_id`` is not in
        ``cc_referenced_ids``. Defaults to False.

    Returns
    -------
    bool
        Whether the id is allowed.
    """
    allow, _ = self._allow_struct_with_reason(
        cc_id=cc_id,
        allow_observations=allow_observations,
        allow_if_filter_inactive=allow_if_filter_inactive,
        allow_if_not_referenced=allow_if_not_referenced,
    )
    return allow
check_timeseries(timeseries: pd.DataFrame) -> None

Warn for each structure with a controller in hydamo.management but no time series.

Parameters

timeseries : pd.DataFrame Time series, with the structure ids as columns.

Source code in hydrolib/dhydamo/core/drtc.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def check_timeseries(self, timeseries: pd.DataFrame) -> None:
    """Warn for each structure with a controller in ``hydamo.management`` but no time series.

    Parameters
    ----------
    timeseries : pd.DataFrame
        Time series, with the structure ids as columns.
    """
    all_management = self.hydamo.management
    # The resolver raises for rows referencing neither a pump nor a management device.
    hydamo_controllers = all_management[
        all_management[DamoRelations.MANAGEMENT_PUMP.foreign_key].notna()
        | all_management[DamoRelations.MANAGEMENT_DEVICE.foreign_key].notna()
    ]
    for _, management in hydamo_controllers.iterrows():
        resolved = self._resolve_management_structure(management)
        if resolved is None:
            continue
        _, structure_id = resolved
        if structure_id not in timeseries.columns:
            logger.warning(
                "For %s a controller is defined in hydamo.management, but no timeseries is provided for it.",
                structure_id,
            )
find_complex_controller_ids(complex_controllers_folder: list[str | Path] | str | Path, hydamo: HyDAMO) -> set[str] staticmethod

Return the ids of the structures that the complex controllers refer to.

Only structures that exist in the HyDAMO model are returned; observation points are left out.

Parameters

complex_controllers_folder : list[str or Path], str or Path Folder(s) with the complex controllers (their dimr_config.xml). hydamo : HyDAMO The HyDAMO data, with the structures.

Returns

set[str] Structure ids.

Source code in hydrolib/dhydamo/core/drtc.py
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
@staticmethod
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def find_complex_controller_ids(
    complex_controllers_folder: list[str | Path] | str | Path,
    hydamo: HyDAMO,
) -> set[str]:
    """Return the ids of the structures that the complex controllers refer to.

    Only structures that exist in the HyDAMO model are returned; observation points
    are left out.

    Parameters
    ----------
    complex_controllers_folder : list[str or Path], str or Path
        Folder(s) with the complex controllers (their ``dimr_config.xml``).
    hydamo : HyDAMO
        The HyDAMO data, with the structures.

    Returns
    -------
    set[str]
        Structure ids.
    """
    # Do not log validation warnings in this method
    struct_ids_by_type = DRTCModel._get_struct_ids_by_type(hydamo)
    cc_structs, _, _ = DRTCModel._load_complex_controller_structs(
        complex_controllers_folder,
        struct_ids_by_type,
        log_validation=False,
    )
    # Do not return observation point IDs in this method
    cc_ids = {
        cc.struct_name for cc in cc_structs if cc.struct_type != "observations"
    }

    return cc_ids
finish_file(xmlroot: ET.Element, filename: Path | str) -> None staticmethod

Write an XML tree to a file, with an XML declaration, pretty-printed.

Parameters

xmlroot : ET.Element Root of the XML tree. filename : Path or str File to write.

Source code in hydrolib/dhydamo/core/drtc.py
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
@staticmethod
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def finish_file(xmlroot: ET.Element, filename: Path | str) -> None:
    """Write an XML tree to a file, with an XML declaration, pretty-printed.

    Parameters
    ----------
    xmlroot : ET.Element
        Root of the XML tree.
    filename : Path or str
        File to write.
    """
    xmlbytes = bytes(
        '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>',
        encoding="utf-8",
    ) + ET.tostring(xmlroot)
    xmlstring = xmlbytes.decode("utf-8").replace("\n", "").replace("  ", "")
    with open(filename, "w+") as f:
        f.write(xmlstring)
    with open(filename) as f:
        temp = xml.dom.minidom.parseString(f.read())
    with open(filename, "w+") as f:
        f.write(temp.toprettyxml())
from_hydamo(pid_settings: dict | None = None, interval_settings: dict | None = None, timeseries: pd.DataFrame | None = None) -> None

Add the time, PID and interval controllers of hydamo.management.

The settings that HyDAMO lacks are keyed by D-Flow FM structure id: the weir, orifice, pump or culvert code, or for a weir with several openings the id of the opening's structure (e.g. S_98740_3). Structures without their own key get the settings under "global". Keys that match no structure with that type of controller are listed in one warning per settings dict.

A structure gets one controller: when several Sturing rows with a supported controller type (PID, interval or time) resolve to the same structure, the first of them is used and the others are skipped with a warning. Rows with another type are skipped with a warning before any other check.

Parameters

pid_settings : dict, optional ki, kp, kd and maxspeed of the PID controllers, per structure id and under "global". Defaults to None. interval_settings : dict, optional deadband and maxspeed of the interval controllers, per structure id and under "global". Defaults to None. timeseries : pd.DataFrame, optional Time series of the time controllers, with the structure ids as columns. Defaults to None.

Raises

ValueError For inconsistent input, e.g. a PID controller without pid_settings.

Source code in hydrolib/dhydamo/core/drtc.py
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def from_hydamo(
    self,
    pid_settings: dict | None = None,
    interval_settings: dict | None = None,
    timeseries: pd.DataFrame | None = None,
) -> None:
    """Add the time, PID and interval controllers of ``hydamo.management``.

    The settings that HyDAMO lacks are keyed by D-Flow FM structure id: the weir,
    orifice, pump or culvert code, or for a weir with several openings the id of
    the opening's structure (e.g. ``S_98740_3``). Structures without their own key
    get the settings under ``"global"``. Keys that match no structure with that
    type of controller are listed in one warning per settings dict.

    A structure gets one controller: when several Sturing rows with a supported
    controller type (PID, interval or time) resolve to the same structure, the
    first of them is used and the others are skipped with a warning. Rows with
    another type are skipped with a warning before any other check.

    Parameters
    ----------
    pid_settings : dict, optional
        ``ki``, ``kp``, ``kd`` and ``maxspeed`` of the PID controllers, per structure
        id and under ``"global"``. Defaults to None.
    interval_settings : dict, optional
        ``deadband`` and ``maxspeed`` of the interval controllers, per structure id
        and under ``"global"``. Defaults to None.
    timeseries : pd.DataFrame, optional
        Time series of the time controllers, with the structure ids as columns.
        Defaults to None.

    Raises
    ------
    ValueError
        For inconsistent input, e.g. a PID controller without ``pid_settings``.
    """
    # the Sturing code of the row that controls each structure: the first wins
    controlled_by: dict[str, str] = {}
    pid_structures: set[str] = set()
    interval_structures: set[str] = set()
    for _, management in self.hydamo.management.iterrows():
        resolved = self._resolve_management_structure(management)
        if resolved is None:
            continue
        structype, struc_id = resolved
        # only rows that create a controller compete for a structure
        if management.typecontroller not in ("PID", "interval", "time"):
            logger.warning(
                f"{management.typecontroller} is not a valid controller type - skipped."
            )
            continue
        if struc_id in controlled_by:
            logger.warning(
                "Structure %s is controlled by Sturing %s and %s. Using %s.",
                struc_id,
                controlled_by[struc_id],
                management.code,
                controlled_by[struc_id],
            )
            continue
        if (
            structype == "weir"
            and management.stuurvariabele == "bovenkant afsluitmiddel"
        ):
            steering_variable = CREST_LEVEL
        elif structype == "weir" and management.stuurvariabele == "hoogte opening":
            steering_variable = GATE_LOWER_EDGE_LEVEL
        elif structype == "pump" and management.stuurvariabele == "pompdebiet":
            steering_variable = CAPACITY
        elif (
            structype == "culvert" and management.stuurvariabele == "hoogte opening"
        ):
            steering_variable = VALVE_OPENING
        else:
            raise ValueError(
                f"Invalid value for steering variable of {struc_id}: {management.stuurvariabele}. Allowed values are 'bovenkant afsluitmiddel' for weirs, 'hoogte opening' for oroficies and culverts, and 'pompdebiet' for pumps."
            )

        if management.doelvariabele == "waterstand":
            target_variable = "Water level (op)"
        elif management.doelvariabele == "debiet":
            target_variable = "Discharge (op)"
        else:
            raise ValueError(
                f"Invalid value for target variable of {struc_id}: {management.doelvariabele}."
            )

        if management.typecontroller == "PID":
            if pid_settings is None:
                raise ValueError(
                    f"{management.code} contains a PID controller, but no pid_settings are provided. Please do so."
                )
            pid_structures.add(struc_id)
            pid = _settings_for("pid_settings", pid_settings, struc_id)
            self.add_pid_controller(
                structure_id=struc_id,
                steering_variable=steering_variable,
                target_variable=target_variable,
                ki=pid["ki"],
                kp=pid["kp"],
                kd=pid["kd"],
                max_speed=pid["maxspeed"],
                setpoint=management.streefwaarde,
                lower_bound=management.ondergrens,
                upper_bound=management.bovengrens,
                observation_location=management.meetlocatieid,
            )

        elif management.typecontroller == "interval":
            if interval_settings is None:
                raise ValueError(
                    f"{management.code} contains an interval controller, but no interval_settings are provided. Please do so."
                )
            interval_structures.add(struc_id)
            interval = _settings_for(
                "interval_settings", interval_settings, struc_id
            )
            self.add_interval_controller(
                structure_id=struc_id,
                steering_variable=steering_variable,
                target_variable=target_variable,
                deadband=interval["deadband"],
                setting_above=management.bovengrens,
                setting_below=management.ondergrens,
                max_speed=interval["maxspeed"],
                setpoint=management.streefwaarde,
                observation_location=management.meetlocatieid,
            )

        elif management.typecontroller == "time":
            if timeseries is None:
                raise ValueError(
                    f"{management.code} contains a time controller, but no time series are provided. Please do so."
                )
            else:
                data = timeseries.loc[:, struc_id]
                self.add_time_controller(
                    structure_id=struc_id,
                    steering_variable=steering_variable,
                    data=data,
                )
        controlled_by[struc_id] = management.code

    _warn_unknown_settings_keys("pid_settings", pid_settings, pid_structures)
    _warn_unknown_settings_keys(
        "interval_settings", interval_settings, interval_structures
    )
get_item_pair(item: ET.Element) -> tuple[str, str] | None staticmethod

Return the source and target name of a DIMR coupler item.

Parameters

item : ET.Element An item element of a coupler.

Returns

tuple[str, str] or None (sourceName, targetName), or None if one of them is missing.

Source code in hydrolib/dhydamo/core/drtc.py
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
@staticmethod
def get_item_pair(item: ET.Element) -> tuple[str, str] | None:
    """Return the source and target name of a DIMR coupler item.

    Parameters
    ----------
    item : ET.Element
        An ``item`` element of a coupler.

    Returns
    -------
    tuple[str, str] or None
        ``(sourceName, targetName)``, or None if one of them is missing.
    """
    source = item.find(".//{*}sourceName")
    target = item.find(".//{*}targetName")
    if (
        source is None
        or target is None
        or source.text is None
        or target.text is None
    ):
        return None
    return source.text, target.text
parse_complex_controller(xml_folder: Path | str) -> ComplexControllers

Read user-specified 'complex' controllers from the RTC XML files in a folder.

Items that refer to structures that are not allowed (see allow_struct) are skipped and logged.

Parameters

xml_folder : Path or str Folder with the custom XML files.

Returns

ComplexControllers The XML fragments per RTC file, and the parsed DIMR config.

Source code in hydrolib/dhydamo/core/drtc.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def parse_complex_controller(self, xml_folder: Path | str) -> ComplexControllers:
    """Read user-specified 'complex' controllers from the RTC XML files in a folder.

    Items that refer to structures that are not allowed (see `allow_struct`) are
    skipped and logged.

    Parameters
    ----------
    xml_folder : Path or str
        Folder with the custom XML files.

    Returns
    -------
    ComplexControllers
        The XML fragments per RTC file, and the parsed DIMR config.
    """
    files = [p for p in Path(xml_folder).iterdir() if p.suffix == ".xml"]
    savedict: ComplexControllers = {
        "dataconfig_import": [],
        "dataconfig_export": [],
        "toolsconfig_rules": [],
        "toolsconfig_triggers": [],
        "timeseries": [],
        "state": [],
        "dimr_config": [],
    }

    handlers = {
        RTC_DATA_CONFIG_XML: self._parse_cc_rtc_dataconfig,
        RTC_TOOLS_CONFIG_XML: self._parse_cc_rtc_toolsconfig,
        TIMESERIES_IMPORT_XML: self._parse_cc_timeseries,
        STATE_IMPORT_XML: self._parse_cc_state,
        "dimr_config.xml": self._parse_cc_dimr_config,
    }

    for filepath in files:
        handler = handlers.get(filepath.name)
        if handler is None:
            continue
        root = ET.parse(filepath).getroot()
        savedict = handler(root, savedict)

    return savedict
set_initial_state(values: dict[str, float]) -> None

Set the initial setting of controlled structures, e.g. {"S_96840": 16.2}.

The value is written to state_import.xml for the steered variable of the structure. It overrides the default initial setting and a state read with set_state_from_file.

Parameters

values : dict[str, float] Initial setting per structure id.

Source code in hydrolib/dhydamo/core/drtc.py
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
def set_initial_state(self, values: dict[str, float]) -> None:
    """Set the initial setting of controlled structures, e.g. {"S_96840": 16.2}.

    The value is written to state_import.xml for the steered variable of the structure. It overrides the
    default initial setting and a state read with set_state_from_file.

    Parameters
    ----------
    values : dict[str, float]
        Initial setting per structure id.
    """
    self.initial_state.update(
        {str(key): float(value) for key, value in values.items()}
    )
set_state_from_file(state_export: str | Path, check_time: bool = True) -> None

Use the RTC state of an earlier model run as initial state (warm start).

The state_export.xml of the earlier run is written as state_import.xml, including the internal state of the rules (e.g. the integral term of PID controllers). This assumes that the RTC configuration is the same as in the earlier run: state items that do not occur in the new rtcDataConfig.xml are skipped, and controllers that are missing in the state keep their default initial setting. Both are reported as a warning.

Parameters

state_export : str or Path Path to state_export.xml, or the rtc folder of the earlier run. check_time : bool, optional Compare the time of the state (from statePI.xml next to the state file) with the start time of this model, and warn if they differ. Defaults to True.

Source code in hydrolib/dhydamo/core/drtc.py
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
def set_state_from_file(
    self, state_export: str | Path, check_time: bool = True
) -> None:
    """Use the RTC state of an earlier model run as initial state (warm start).

    The state_export.xml of the earlier run is written as state_import.xml, including the internal
    state of the rules (e.g. the integral term of PID controllers). This assumes that the RTC configuration
    is the same as in the earlier run: state items that do not occur in the new rtcDataConfig.xml are
    skipped, and controllers that are missing in the state keep their default initial setting. Both
    are reported as a warning.

    Parameters
    ----------
    state_export : str or Path
        Path to state_export.xml, or the rtc folder of the earlier run.
    check_time : bool, optional
        Compare the time of the state (from statePI.xml next to the state file) with
        the start time of this model, and warn if they differ. Defaults to True.
    """
    path = Path(state_export)
    if path.is_dir():
        path = path / "state_export.xml"
    if not path.exists():
        raise FileNotFoundError(f"RTC state file {path} not found.")

    leaves = self._read_state_leaves(path)
    if not leaves:
        raise ValueError(f"No state items (treeVectorLeaf) found in {path}.")
    self.state_from_file = leaves
    logger.info(f"Read {len(leaves)} RTC state items from {path}.")

    if not check_time:
        return
    statepi = path.parent / "statePI.xml"
    state_time = self._read_state_time(statepi) if statepi.exists() else None
    if state_time is None:
        logger.info(
            f"No time found for the RTC state in {statepi}; the time of the state is not checked."
        )
    elif state_time != self.time_settings["start"]:
        logger.warning(
            f"The RTC state is valid for {state_time}, but the model starts at {self.time_settings['start']}."
        )
set_state_from_modelrun(his_path: str | Path, time: dt | pd.Timestamp | str | None = None, netcdf_index: int | None = None) -> dict[str, float]

Use the structure settings of an earlier model run (his-file) as initial setting of the controllers.

For every controlled structure, the steered variable (crest level, gate lower edge level, valve opening or pump capacity) is read from the his-file at the given time and passed to set_initial_state. Unlike set_state_from_file, any time step can be used, but the internal state of the rules (e.g. the integral term of PID controllers) is not restored.

Parameters

his_path : str or Path Path to the his file of the earlier run. time : datetime, pd.Timestamp or str, optional Time of the settings; the nearest time step is used. Defaults to None. netcdf_index : int, optional Time index instead of a time. Defaults to None: without a time, the last time step.

Returns

dict[str, float] Initial setting per structure id.

Source code in hydrolib/dhydamo/core/drtc.py
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
def set_state_from_modelrun(
    self,
    his_path: str | Path,
    time: dt | pd.Timestamp | str | None = None,
    netcdf_index: int | None = None,
) -> dict[str, float]:
    """Use the structure settings of an earlier model run (his-file) as initial setting of the controllers.

    For every controlled structure, the steered variable (crest level, gate lower edge level, valve
    opening or pump capacity) is read from the his-file at the given time and passed to set_initial_state.
    Unlike set_state_from_file, any time step can be used, but the internal state of the rules (e.g. the
    integral term of PID controllers) is not restored.

    Parameters
    ----------
    his_path : str or Path
        Path to the his file of the earlier run.
    time : datetime, pd.Timestamp or str, optional
        Time of the settings; the nearest time step is used. Defaults to None.
    netcdf_index : int, optional
        Time index instead of a time. Defaults to None: without a time, the last
        time step.

    Returns
    -------
    dict[str, float]
        Initial setting per structure id.
    """
    if time is not None and netcdf_index is not None:
        raise ValueError("Provide either time or netcdf_index, not both.")
    if time is None and netcdf_index is None:
        logger.info(f"No time given; the last time step in {his_path} is used.")
    controllers = {
        **self.time_controllers,
        **self.interval_controllers,
        **self.pid_controllers,
    }
    kinds = {
        kind for sources in HIS_SETTING_VARIABLES.values() for kind, _ in sources
    }

    values, missing = {}, []
    with Dataset(his_path) as his:
        if time is not None:
            index = time_index(his, time)
        else:
            index = -1 if netcdf_index is None else netcdf_index
        names = {
            kind: [n.strip() for n in chartostring(his[f"{kind}_name"][:])]
            for kind in kinds
            if f"{kind}_name" in his.variables
        }
        for structure_id, controller in controllers.items():
            value = self._read_structure_setting(
                his, names, structure_id, controller["steering_variable"], index
            )
            if value is None:
                missing.append(structure_id)
            else:
                values[structure_id] = value

    if missing:
        logger.warning(
            f"No setting found in {his_path} for {len(missing)} controlled structure(s), "
            f"these keep their default initial setting: {missing}"
        )
    logger.info(
        f"Initial setting of {len(values)} controlled structures read from {his_path}."
    )
    self.set_initial_state(values)
    return values
write_dataconfig() -> None

Write rtcDataConfig.xml, from the template, with the series of all controllers.

Source code in hydrolib/dhydamo/core/drtc.py
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
def write_dataconfig(self) -> None:
    """Write rtcDataConfig.xml, from the template, with the series of all controllers."""
    generalname = "http://www.wldelft.nl/fews"
    xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
    gn_brackets = "{" + generalname + "}"
    m3unit = "m^3/s"
    munit = "m"

    # registering namespaces
    ET.register_namespace("", generalname)
    ET.register_namespace("xsi", xsi_name)

    # Parsing xml file
    configfile = ET.parse(self.template_dir / "rtcDataConfig_empty.xml")
    myroot = configfile.getroot()

    timeseries_length = len(
        ET.parse(self.output_path / "timeseries_import.xml").getroot()
    )

    # implementing standard settings import and exportdata
    a0 = ET.SubElement(myroot[1], gn_brackets + "CSVTimeSeriesFile")
    a0.set("decimalSeparator", ".")
    a0.set("delimiter", ",")
    a0.set("adjointOutput", "false")

    a1 = ET.SubElement(myroot[1], gn_brackets + "PITimeSeriesFile")

    a2 = ET.SubElement(a1, gn_brackets + "timeSeriesFile")
    a2.text = "timeseries_export.xml"

    a3 = ET.SubElement(a1, gn_brackets + "useBinFile")
    a3.text = "false"

    # implementing standard settings import and exportdata
    if timeseries_length > 0:
        # only if timeseries are written to the import
        a4 = ET.SubElement(myroot[0], gn_brackets + "PITimeSeriesFile")
        a5 = ET.SubElement(a4, gn_brackets + "timeSeriesFile")
        a5.text = TIMESERIES_IMPORT_XML
        a6 = ET.SubElement(a4, gn_brackets + "useBinFile")
        a6.text = "false"

    # weir dependable data
    for ikey, key in enumerate(self.all_controllers.keys()):
        controller = self.all_controllers[key]
        # For simple controllers: skip only when this id has an allowed complex controller.
        # If filtering is inactive or the id is not a referenced complex id, do not skip.
        if self.allow_struct(
            cc_id=key,
            allow_observations=False,
            allow_if_filter_inactive=False,
            allow_if_not_referenced=False,
        ):
            logger.warning(
                f"{RTC_DATA_CONFIG_XML}: Skipped writing {controller['type']} control for {key}, complex controller already present"
            )
            continue

        # te importeren data
        if controller["type"] == "PID":
            input_id = (
                INPUT_PREFIX
                + controller["observation_point"]
                + "/"
                + controller["target_variable"]
            )

            if myroot[0].find(f".//*[@id='{input_id}']") is None:
                a = ET.SubElement(myroot[0], gn_brackets + "timeSeries")
                a.set("id", input_id)

                b = ET.SubElement(a, gn_brackets + "OpenMIExchangeItem")

                c = ET.SubElement(b, gn_brackets + "elementId")
                c.text = controller["observation_point"]

                d = ET.SubElement(b, gn_brackets + "quantityId")
                d.text = controller["target_variable"]

                e = ET.SubElement(b, gn_brackets + "unit")
                e.text = (
                    munit
                    if controller["target_variable"] == "Water level (op)"
                    else m3unit
                )

            else:
                logger.warning(
                    f"{RTC_DATA_CONFIG_XML}: Skipped writing {input_id}, observation point already present"
                )

            # If a time dependent setpoint is required, add the Time Rule
            if type(controller["setpoint"]) is pd.Series:
                a2 = ET.SubElement(myroot[0], gn_brackets + "timeSeries")

                a2.set("id", f"[SP]Control group {key}/PID Rule")
                b2 = ET.SubElement(a2, gn_brackets + "PITimeSeries")

                c2 = ET.SubElement(b2, gn_brackets + "locationId")
                c2.text = f"[PID]Control group {key}/PID Rule"

                d2 = ET.SubElement(b2, gn_brackets + "parameterId")
                d2.text = "SP"

                e2 = ET.SubElement(b2, gn_brackets + "interpolationOption")
                e2.text = controller["interpolation_option"]

                e2 = ET.SubElement(b2, gn_brackets + "extrapolationOption")
                e2.text = controller[
                    "extrapolation_option"
                ]  # Changed from Block: HL

        elif controller["type"] == "Interval":
            input_id = (
                INPUT_PREFIX
                + controller["observation_point"]
                + "/"
                + controller["target_variable"]
            )
            if myroot.find(f".//*[@id='{input_id}']") is None:
                a = ET.SubElement(myroot[0], gn_brackets + "timeSeries")

                a.set("id", input_id)

                b = ET.SubElement(a, gn_brackets + "OpenMIExchangeItem")

                c = ET.SubElement(b, gn_brackets + "elementId")
                c.text = controller["observation_point"]

                d = ET.SubElement(b, gn_brackets + "quantityId")
                d.text = controller["target_variable"]

                e = ET.SubElement(b, gn_brackets + "unit")
                e.text = (
                    munit
                    if controller["target_variable"] == "Water level (op)"
                    else m3unit
                )
            else:
                logger.warning(
                    f"{RTC_DATA_CONFIG_XML}: Skipped writing {input_id}, observation point already present"
                )

            if type(controller["setpoint"]) is pd.Series:
                a2 = ET.SubElement(myroot[0], gn_brackets + "timeSeries")

                a2.set("id", f"[SP]Control group {key}/Interval Rule")
                b3 = ET.SubElement(a2, gn_brackets + "PITimeSeries")

                c3 = ET.SubElement(b3, gn_brackets + "locationId")
                c3.text = f"[IntervalRule]Control group {key}/Interval Rule"

                d3 = ET.SubElement(b3, gn_brackets + "parameterId")
                d3.text = "SP"

                e3 = ET.SubElement(b3, gn_brackets + "interpolationOption")
                e3.text = controller["interpolation_option"]

                f3 = ET.SubElement(b3, gn_brackets + "extrapolationOption")
                f3.text = controller[
                    "extrapolation_option"
                ]  # Changed from Block: HL

        else:
            a = ET.SubElement(myroot[0], gn_brackets + "timeSeries")
            a.set("id", "Control group " + str(key) + "/Time Rule")
            b = ET.SubElement(a, gn_brackets + "PITimeSeries")

            c = ET.SubElement(b, gn_brackets + "locationId")
            c.text = f"[TimeRule]Control group {key}/Time Rule"

            d = ET.SubElement(b, gn_brackets + "parameterId")
            d.text = "TimeSeries"

            e = ET.SubElement(b, gn_brackets + "interpolationOption")
            e.text = controller["interpolation_option"]

            e = ET.SubElement(b, gn_brackets + "extrapolationOption")
            e.text = controller["extrapolation_option"]  # Changed from Block: HL

        # te exporteren data:
        f = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
        f.set(
            "id", OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
        )

        g = ET.SubElement(f, gn_brackets + "OpenMIExchangeItem")

        h = ET.SubElement(g, gn_brackets + "elementId")
        h.text = str(key)

        j = ET.SubElement(g, gn_brackets + "quantityId")
        j.text = controller["steering_variable"]

        k = ET.SubElement(g, gn_brackets + "unit")
        k.text = m3unit if controller["steering_variable"] == CAPACITY else munit

    for ikey, key in enumerate(self.all_controllers.keys()):
        controller = self.all_controllers[key]

        if controller["type"] == "PID":
            i = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
            i.set("id", "[IP]Control group " + str(key) + "/PID Rule")

            j = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
            j.set("id", "[DP]Control group " + str(key) + "/PID Rule")

        elif (
            controller["type"] == "Interval"
        ):  # Change slightly when working with Interval rule
            j = ET.SubElement(myroot[1], gn_brackets + "timeSeries")
            j.set("id", "[Status]Control group " + str(key) + "/Interval Rule")

    # the parsed complex controllers should be inserted at the right place
    if self.complex_controllers is not None:
        self._append_unique_elements(
            parent=myroot[0],
            elements=self.complex_controllers["dataconfig_import"],
            key_getter=self._dataconfig_timeseries_key,
            file_label=RTC_DATA_CONFIG_XML,
        )
        self._append_unique_elements(
            parent=myroot[1],
            elements=self.complex_controllers["dataconfig_export"],
            key_getter=self._dataconfig_timeseries_key,
            file_label=RTC_DATA_CONFIG_XML,
        )

    self.finish_file(myroot, self.output_path / RTC_DATA_CONFIG_XML)
    self._written_dataconfig_ids = self._element_ids(myroot)
write_runtimeconfig() -> None

Write rtcRuntimeConfig.xml, from the template, with the model period and time step.

Source code in hydrolib/dhydamo/core/drtc.py
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
def write_runtimeconfig(self) -> None:
    """Write rtcRuntimeConfig.xml, from the template, with the model period and time step."""
    # namespaces for all other xml files
    generalname = "http://www.wldelft.nl/fews"
    xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
    gn_brackets = "{" + generalname + "}"

    # registering namespaces
    ET.register_namespace("", generalname)
    ET.register_namespace("xsi", xsi_name)

    # parsing xml file to python and get the root of the existing xml file
    configfile = ET.parse(
        os.path.join(self.template_dir, "rtcRuntimeConfig_empty.xml")
    )
    myroot = configfile.getroot()

    # convert date and runtime to required input for runtimeconfig file

    # replace start/stop dates and times in xml file
    for x in myroot.iter(gn_brackets + "startDate"):
        x.set("date", self.time_settings["start"].strftime("%Y-%m-%d"))
        x.set("time", self.time_settings["start"].strftime("%H:%M:%S"))
    for x in myroot.iter(gn_brackets + "endDate"):
        x.set("date", self.time_settings["end"].strftime("%Y-%m-%d"))
        x.set("time", self.time_settings["end"].strftime("%H:%M:%S"))
    for x in myroot.iter(gn_brackets + "timeStep"):
        x.set("unit", "second")
        x.set("divider", "1")
        x.set("multiplier", str(int(self.time_settings["step"])))

    # write new xml file
    self.finish_file(myroot, self.output_path / "rtcRuntimeConfig.xml")
write_state_import() -> None

Write state_import.xml, from the template, with the initial state of the controllers.

Source code in hydrolib/dhydamo/core/drtc.py
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
def write_state_import(self) -> None:
    """Write state_import.xml, from the template, with the initial state of the controllers."""
    generalname = "http://www.openda.org"
    xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
    gn_brackets = "{" + generalname + "}"

    # registering namespaces
    ET.register_namespace("", generalname)
    ET.register_namespace("xsi", xsi_name)

    # Parsing xml file
    configfile = ET.parse(self.template_dir / "state_import_empty.xml")
    myroot = configfile.getroot()

    a0 = ET.SubElement(myroot, gn_brackets + "treeVector")

    for key in self.all_controllers:
        controller = self.all_controllers[key]
        # For simple controllers: skip only when this id has an allowed complex controller.
        # If filtering is inactive or the id is not a referenced complex id, do not skip.
        if self.allow_struct(
            cc_id=key,
            allow_observations=False,
            allow_if_filter_inactive=False,
            allow_if_not_referenced=False,
        ):
            logger.warning(
                f"{STATE_IMPORT_XML}: Skipped writing {controller['type']} control for {key}, complex controller already present"
            )
            continue

        # te importeren data
        a = ET.SubElement(a0, gn_brackets + "treeVectorLeaf")
        a.attrib = {
            "id": OUTPUT_PREFIX + key + "/" + controller["steering_variable"]
        }
        b = ET.SubElement(a, gn_brackets + "vector")
        if controller["type"] == "PID":
            b.text = str(self._initial_pid_setting(key, controller))
        elif controller["type"] == "Interval":
            # Take the maximum value as a starting value
            b.text = str(
                max(
                    float(controller["setting_above"]),
                    float(controller["setting_below"]),
                )
            )
        else:
            b.text = str(controller["data"].to_numpy()[0])

    # the parsed complex controllers should be inserted at the right place
    if self.complex_controllers is not None:
        self._append_unique_elements(
            parent=myroot[0],
            elements=self.complex_controllers["state"],
            key_getter=self._state_leaf_key,
            file_label=STATE_IMPORT_XML,
        )

    # a state from an earlier model run and user-defined initial settings override the defaults
    self._apply_state_overrides(myroot[0], gn_brackets)

    self.finish_file(myroot, self.output_path / STATE_IMPORT_XML)
write_timeseries_import() -> None

Write timeseries_import.xml, from the template, with the time series of the controllers.

Source code in hydrolib/dhydamo/core/drtc.py
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
def write_timeseries_import(self) -> None:
    """Write timeseries_import.xml, from the template, with the time series of the controllers."""
    generalname = "http://www.wldelft.nl/fews/PI"
    xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
    gn_brackets = "{" + generalname + "}"

    # registering namespaces
    ET.register_namespace("", generalname)
    ET.register_namespace("xsi", xsi_name)

    # Parsing xml file
    configfile = ET.parse(self.template_dir / "timeseries_import_empty.xml")
    myroot = configfile.getroot()

    for key in self.all_controllers:
        controller = self.all_controllers[key]
        # For simple controllers: skip only when this id has an allowed complex controller.
        # If filtering is inactive or the id is not a referenced complex id, do not skip.
        if self.allow_struct(
            cc_id=key,
            allow_observations=False,
            allow_if_filter_inactive=False,
            allow_if_not_referenced=False,
        ):
            logger.warning(
                f"{TIMESERIES_IMPORT_XML}: Skipped writing {controller['type']} control for {key}, complex controller already present"
            )
            continue

        if controller["type"] == "Time":
            # te importeren data
            dates = pd.to_datetime(controller["data"].index).strftime("%Y-%m-%d")
            times = pd.to_datetime(controller["data"].index).strftime("%H:%M:%S")
            timestep = (
                pd.to_datetime(controller["data"].index)[1]
                - pd.to_datetime(controller["data"].index)[0]
            ).total_seconds()
            a = ET.SubElement(myroot, gn_brackets + "series")
            b = ET.SubElement(a, gn_brackets + "header")
            c = ET.SubElement(b, gn_brackets + "type")
            c.text = "instantaneous"
            d = ET.SubElement(b, gn_brackets + "locationId")
            d.text = f"[TimeRule]Control group {key}/Time Rule"
            e = ET.SubElement(b, gn_brackets + "parameterId")
            e.text = "TimeSeries"
            f = ET.SubElement(b, gn_brackets + "timeStep")
            f.attrib = {
                "unit": "minute",
                "multiplier": str(int(timestep / 60.0)),
                "divider": str(1),
            }
            g = ET.SubElement(b, gn_brackets + "startDate")
            g.attrib = {"date": dates[0], "time": times[0]}
            h = ET.SubElement(b, gn_brackets + "endDate")
            h.attrib = {"date": dates[-1], "time": times[-1]}
            i = ET.SubElement(b, gn_brackets + "missVal")
            i.text = "-999.0"
            j = ET.SubElement(b, gn_brackets + "stationName")
            j.text = ""
            for event_date, event_time, value in zip(
                dates, times, controller["data"].to_numpy()
            ):
                k = ET.SubElement(a, gn_brackets + "event")
                k.attrib = {
                    "date": event_date,
                    "time": event_time,
                    "value": str(value),
                }
        elif controller["type"] == "Interval":
            setpoint = controller["setpoint"]
            if isinstance(setpoint, float):
                setpoint = pd.Series(
                    [setpoint, setpoint],
                    index=[self.time_settings["start"], self.time_settings["end"]],
                )
                controller["setpoint"] = setpoint
            if isinstance(setpoint, str):
                raise TypeError(
                    f"Setpoint {setpoint!r} of interval controller {key} must be a number or a pd.Series."
                )

            # te importeren data
            dates = pd.to_datetime(setpoint.index).strftime("%Y-%m-%d")
            times = pd.to_datetime(setpoint.index).strftime("%H:%M:%S")
            timestep = (
                pd.to_datetime(f"{dates[1]} {times[1]}")
                - pd.to_datetime(f"{dates[0]} {times[0]}")
            ).total_seconds()

            a = ET.SubElement(myroot, gn_brackets + "series")
            b = ET.SubElement(a, gn_brackets + "header")
            c = ET.SubElement(b, gn_brackets + "type")
            c.text = "instantaneous"

            d = ET.SubElement(b, gn_brackets + "locationId")
            d.text = f"[IntervalRule]Control group {key}/Interval Rule"

            e = ET.SubElement(b, gn_brackets + "parameterId")
            e.text = "SP"
            f = ET.SubElement(b, gn_brackets + "timeStep")
            f.attrib = {
                "unit": "minute",
                "multiplier": str(int(timestep / 60.0)),
                "divider": str(1),
            }
            g = ET.SubElement(b, gn_brackets + "startDate")
            g.attrib = {"date": dates[0], "time": times[0]}
            h = ET.SubElement(b, gn_brackets + "endDate")
            h.attrib = {"date": dates[-1], "time": times[-1]}
            i = ET.SubElement(b, gn_brackets + "missVal")
            i.text = "-999.0"
            for event_date, event_time, value in zip(
                dates, times, setpoint.to_numpy()
            ):
                k = ET.SubElement(a, gn_brackets + "event")
                k.attrib = {
                    "date": event_date,
                    "time": event_time,
                    "value": str(value),
                }

        # Create a timeseries import if a time-dependent setpoint is used
        elif controller["type"] == "PID" and isinstance(
            controller["setpoint"], pd.Series
        ):
            # te importeren data
            dates = pd.to_datetime(controller["setpoint"].index).strftime(
                "%Y-%m-%d"
            )
            times = pd.to_datetime(controller["setpoint"].index).strftime(
                "%H:%M:%S"
            )
            timestep = (
                pd.to_datetime(controller["setpoint"].index)[1]
                - pd.to_datetime(controller["setpoint"].index)[0]
            ).total_seconds()
            a = ET.SubElement(myroot, gn_brackets + "series")
            b = ET.SubElement(a, gn_brackets + "header")
            c = ET.SubElement(b, gn_brackets + "type")
            c.text = "instantaneous"

            d = ET.SubElement(b, gn_brackets + "locationId")
            d.text = f"[PID]Control group {key}/PID Rule"

            e = ET.SubElement(b, gn_brackets + "parameterId")
            e.text = "SP"
            f = ET.SubElement(b, gn_brackets + "timeStep")
            f.attrib = {
                "unit": "minute",
                "multiplier": str(int(timestep / 60.0)),
                "divider": str(1),
            }
            g = ET.SubElement(b, gn_brackets + "startDate")
            g.attrib = {"date": dates[0], "time": times[0]}
            h = ET.SubElement(b, gn_brackets + "endDate")
            h.attrib = {"date": dates[-1], "time": times[-1]}
            i = ET.SubElement(b, gn_brackets + "missVal")
            i.text = "-999.0"
            j = ET.SubElement(b, gn_brackets + "stationName")
            j.text = ""
            for event_date, event_time, value in zip(
                dates, times, controller["setpoint"].to_numpy()
            ):
                k = ET.SubElement(a, gn_brackets + "event")
                k.attrib = {
                    "date": event_date,
                    "time": event_time,
                    "value": str(value),
                }

    if self.complex_controllers is not None:
        self._append_unique_elements(
            parent=myroot,
            elements=self.complex_controllers["timeseries"],
            key_getter=self._timeseries_series_key,
            file_label=TIMESERIES_IMPORT_XML,
        )

    self.finish_file(myroot, self.output_path / TIMESERIES_IMPORT_XML)
write_toolsconfig() -> None

Write rtcToolsConfig.xml, from the template, with the rules of all controllers.

Source code in hydrolib/dhydamo/core/drtc.py
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
def write_toolsconfig(self) -> None:
    """Write rtcToolsConfig.xml, from the template, with the rules of all controllers."""
    generalname = "http://www.wldelft.nl/fews"
    xsi_name = "http://www.w3.org/2001/XMLSchema-instance"
    gn_brackets = "{" + generalname + "}"

    # registering namespaces
    ET.register_namespace("", generalname)
    ET.register_namespace("xsi", xsi_name)

    # parsing xml file
    configfile = ET.parse(self.template_dir / "rtcToolsConfig_empty.xml")
    myroot = configfile.getroot()

    self.all_controllers: dict[
        str, TimeController | PIDController | IntervalController
    ] = {
        **self.time_controllers,
        **self.pid_controllers,
        **self.interval_controllers,
    }

    to_remove = []
    for key in self.all_controllers:
        controller = self.all_controllers[key]
        # For simple controllers: skip only when this id has an allowed complex controller.
        # If filtering is inactive or the id is not a referenced complex id, do not skip.
        if self.allow_struct(
            cc_id=key,
            allow_observations=False,
            allow_if_filter_inactive=False,
            allow_if_not_referenced=False,
        ):
            logger.warning(
                f"RtcToolsConfig.xml: Skipped writing {controller['type']} control for {key}, complex controller already present"
            )
            to_remove.append(key)
            continue

        a = ET.SubElement(myroot[1], gn_brackets + "rule")
        if controller["type"] == "PID":
            # rule type (PID)
            b = ET.SubElement(a, gn_brackets + "pid")
            b.set("id", "[PID]" + "Control group " + str(key) + "/PID Rule")

            # standard settings
            c = ET.SubElement(b, gn_brackets + "mode")
            c.text = "PIDVEL"

            d = ET.SubElement(b, gn_brackets + "settingMin")
            d.text = str(controller["lower_bound"])

            e = ET.SubElement(b, gn_brackets + "settingMax")
            e.text = str(controller["upper_bound"])

            f = ET.SubElement(b, gn_brackets + "settingMaxSpeed")
            f.text = str(controller["max_speed"])

            g = ET.SubElement(b, gn_brackets + "kp")
            g.text = str(controller["kp"])

            h = ET.SubElement(b, gn_brackets + "ki")
            h.text = str(controller["ki"])

            i = ET.SubElement(b, gn_brackets + "kd")
            i.text = str(controller["kd"])

            # input
            j = ET.SubElement(b, gn_brackets + "input")

            k = ET.SubElement(j, gn_brackets + "x")
            k.text = (
                INPUT_PREFIX
                + controller["observation_point"]
                + "/"
                + controller["target_variable"]
            )

            # If setpoint varies in time
            if isinstance(controller["setpoint"], pd.Series):
                ll = ET.SubElement(j, gn_brackets + "setpointSeries")
                ll.text = "[SP]" + "Control group " + str(key) + "/PID Rule"
            # Else fixed setpoint
            else:
                ll = ET.SubElement(j, gn_brackets + "setpointValue")
                ll.text = str(controller["setpoint"])

            # output
            m = ET.SubElement(b, gn_brackets + "output")

            o = ET.SubElement(m, gn_brackets + "y")
            o.text = (
                OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
            )

            p = ET.SubElement(m, gn_brackets + "integralPart")
            p.text = "[IP]" + "Control group " + str(key) + "/PID Rule"

            q = ET.SubElement(m, gn_brackets + "differentialPart")
            q.text = "[DP]" + "Control group " + str(key) + "/PID Rule"

        elif controller["type"] == "Interval":
            # Interval RTC
            # rule type (Interval)
            b = ET.SubElement(a, gn_brackets + "interval")
            b.set(
                "id",
                "[IntervalRule]" + "Control group " + str(key) + "/Interval Rule",
            )

            # standard settings
            d = ET.SubElement(b, gn_brackets + "settingBelow")
            d.text = str(controller["setting_below"])

            e = ET.SubElement(b, gn_brackets + "settingAbove")
            e.text = str(controller["setting_above"])

            f = ET.SubElement(b, gn_brackets + "settingMaxSpeed")
            f.text = str(controller["max_speed"])

            g = ET.SubElement(b, gn_brackets + "deadbandSetpointAbsolute")
            g.text = str(controller["deadband"])

            # input
            j = ET.SubElement(b, gn_brackets + "input")

            k = ET.SubElement(
                j, gn_brackets + "x"
            )  # leave ref = "EXPLICIT" out for now
            k.text = (
                INPUT_PREFIX
                + controller["observation_point"]
                + "/"
                + controller["target_variable"]
            )
            # If setpoint varies in time
            ll = ET.SubElement(j, gn_brackets + "setpoint")
            ll.text = "[SP]" + "Control group " + str(key) + "/Interval Rule"

            # output
            m = ET.SubElement(b, gn_brackets + "output")

            o = ET.SubElement(m, gn_brackets + "y")
            o.text = (
                OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
            )

            p = ET.SubElement(m, gn_brackets + "status")
            p.text = "[Status]" + "Control group " + str(key) + "/Interval Rule"
        # Add time rule
        else:
            # rule type (timeabsolute)
            b = ET.SubElement(a, gn_brackets + "timeAbsolute")
            b.set("id", "[TimeRule]" + "Control group " + str(key) + "/Time Rule")

            # input
            c = ET.SubElement(b, gn_brackets + "input")

            d = ET.SubElement(c, gn_brackets + "x")
            d.text = "Control group " + str(key) + "/Time Rule"

            e = ET.SubElement(b, gn_brackets + "output")

            f = ET.SubElement(e, gn_brackets + "y")
            f.text = (
                OUTPUT_PREFIX + str(key) + "/" + controller["steering_variable"]
            )

    # remove controllers that have complex controllers
    for key in to_remove:
        del self.all_controllers[key]

    # elements that are parsed from user specified files should be inserted at the right place.
    if self.complex_controllers is not None:
        for ctl in self.complex_controllers["toolsconfig_rules"]:
            myroot[1].append(ET.fromstring(ctl))
        for ctl in self.complex_controllers["toolsconfig_triggers"]:
            # no trigger block present yet
            if len(myroot) == 2:
                trigger = ET.Element(gn_brackets + "triggers")
                myroot.append(trigger)
                myroot[2].append(ET.fromstring(ctl))
            else:
                myroot[2].append(ET.fromstring(ctl))

    self.finish_file(myroot, self.output_path / RTC_TOOLS_CONFIG_XML)
write_xml_v1() -> None

Write all RTC XML files.

Source code in hydrolib/dhydamo/core/drtc.py
1923
1924
1925
1926
1927
1928
1929
def write_xml_v1(self) -> None:
    """Write all RTC XML files."""
    self.write_runtimeconfig()
    self.write_toolsconfig()
    self.write_timeseries_import()
    self.write_dataconfig()
    self.write_state_import()

DRTCStructure dataclass

A flow structure referenced in a complex controller.

Source code in hydrolib/dhydamo/core/drtc.py
147
148
149
150
151
152
153
@dataclass
class DRTCStructure:
    """A flow structure referenced in a complex controller."""

    struct_type: str
    struct_name: str
    struct_property: str

IntervalController

Bases: TypedDict

Interval controller of a structure, added with DRTCModel.add_interval_controller.

Source code in hydrolib/dhydamo/core/drtc.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
class IntervalController(TypedDict):
    """Interval controller of a structure, added with ``DRTCModel.add_interval_controller``."""

    type: Literal["Interval"]
    steering_variable: str
    target_variable: str
    setpoint: float | str | pd.Series
    observation_point: str
    setting_below: float | str
    setting_above: float | str
    max_speed: float | str | None
    deadband: float | str | None
    interpolation_option: str
    extrapolation_option: str

PIDController

Bases: TypedDict

PID controller of a structure, added with DRTCModel.add_pid_controller.

Source code in hydrolib/dhydamo/core/drtc.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class PIDController(TypedDict):
    """PID controller of a structure, added with ``DRTCModel.add_pid_controller``."""

    type: Literal["PID"]
    steering_variable: str
    target_variable: str
    setpoint: float | str | pd.Series
    observation_point: str
    lower_bound: float | str | None
    upper_bound: float | str | None
    ki: float
    kp: float
    kd: float
    max_speed: float
    interpolation_option: str
    extrapolation_option: str

TimeController

Bases: TypedDict

Time controller of a structure, added with DRTCModel.add_time_controller.

Source code in hydrolib/dhydamo/core/drtc.py
103
104
105
106
107
108
109
110
class TimeController(TypedDict):
    """Time controller of a structure, added with ``DRTCModel.add_time_controller``."""

    type: Literal["Time"]
    data: pd.Series
    steering_variable: str
    interpolation_option: str
    extrapolation_option: str

TimeSettings

Bases: TypedDict

Start and end time of the model, and the RTC time step in seconds.

Source code in hydrolib/dhydamo/core/drtc.py
 95
 96
 97
 98
 99
100
class TimeSettings(TypedDict):
    """Start and end time of the model, and the RTC time step in seconds."""

    start: pd.Timestamp
    end: pd.Timestamp
    step: float

hydamo

The HyDAMO data model: input data, cross sections, structures, forcings and storage nodes.

CrossSections

Cross section definitions and locations of the model.

Parameters

hydamo : HyDAMO The HyDAMO object they belong to.

Source code in hydrolib/dhydamo/core/hydamo.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
class CrossSections:
    """Cross section definitions and locations of the model.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO object they belong to.
    """

    def __init__(self, hydamo: HyDAMO) -> None:
        """Create empty cross section definitions and locations."""
        self.hydamo = hydamo
        self.crosssections: list = []
        self.default_definition: str | None = None
        self.default_definition_shift = 0.0
        self.default_location = ""

        self.crosssection_loc: dict[str, dict] = {}
        self.crosssection_def: dict[str, dict] = {}

        self.get_roughnessname = self.get_roughness_description

        self.convert = CrossSectionsIO(self)

    def get_roughness_description(self, roughnesstype: str, value: float) -> str:
        """Return the name of a roughness definition, added if it is new.

        Parameters
        ----------
        roughnesstype : str
            HyDAMO roughness type, mapped to the D-HYDRO type.
        value : float
            Roughness value.

        Returns
        -------
        str
            Name of the definition, e.g. ``"Manning_0.03"``.

        Raises
        ------
        ValueError
            If the value is NaN.
        """
        if np.isnan(float(value)):
            raise ValueError("Roughness value should not be NaN.")

        # map HyDAMO definition to D-Hydro definition
        roughnesstype = self.hydamo.roughness_mapping[roughnesstype]

        # Get name
        name = f"{roughnesstype}_{float(value)}"

        # Check if the description is already known
        if name.lower() in map(str.lower, self.hydamo.roughness_definitions.keys()):
            return name

        # Add to dict
        self.hydamo.roughness_definitions[name] = {
            "frictionid": name,
            "frictiontype": roughnesstype,
            "frictionvalue": value,
        }

        return name

    def set_default_definition(self, definition: str, shift: float = 0.0) -> None:
        """Set the cross section definition for branches without a cross section.

        It is used by ``Df2HydrolibModel(assign_default_profiles=True)``.

        Parameters
        ----------
        definition : str
            Name of an existing cross section definition.
        shift : float, optional
            Vertical shift of the definition. Defaults to 0.0.

        Raises
        ------
        KeyError
            If the definition does not exist.
        """
        if definition not in self.crosssection_def:
            raise KeyError(f'Cross section definition "{definition}" not found."')

        self.default_definition = definition
        self.default_definition_shift = shift

    def set_default_locations(self, locations: list[str]) -> None:
        """Set the branches that get the default cross section definition.

        Parameters
        ----------
        locations : list[str]
            Branch ids.
        """
        self.default_locations = locations

    def add_yz_definition(
        self,
        yz: np.ndarray | None = None,
        thalweg: float | None = None,
        roughnesstype: str | None = None,
        roughnessvalue: float | None = None,
        name: str | None = None,
    ) -> str:
        """Add a yz cross section definition.

        Parameters
        ----------
        code : str
            Id of cross section
        branch : str
            Name of branch
        offset : float
            Position of cross section along branch. If not given, the position is determined
            from the branches in the network. These should thus be given in this case.
        crds : np.array
            Nx2 array with y, z coordinates
        """
        if (
            yz is None
            or thalweg is None
            or roughnesstype is None
            or roughnessvalue is None
        ):
            raise ValueError(
                "yz, thalweg, roughnesstype and roughnessvalue are required."
            )
        # get coordinates
        length, z = yz.T
        if name is None:
            name = f"yz_{yz}:08d"

        # Get roughnessname
        roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

        # Add to dictionary
        self.crosssection_def[name] = {
            "id": name,
            "type": "yz",
            "thalweg": np.round(thalweg, decimals=3),
            "yzcount": len(z),
            "ycoordinates": self.hydamo.list_to_str(length),
            "zcoordinates": self.hydamo.list_to_str(z),
            "sectioncount": 1,
            "frictionids": roughnessname,
            "frictionpositions": self.hydamo.list_to_str([length[0], length[-1]]),
        }

        return name

    def add_circle_definition(
        self,
        diameter: float,
        roughnesstype: str,
        roughnessvalue: float,
        name: str | None = None,
    ) -> str:
        """Add a circle cross section definition.

        Without a name, the name is derived from the shape only, so a definition with the
        same shape but another roughness replaces the earlier one.
        """
        # Get name if not given
        if name is None:
            name = f"circ_d{diameter:.3f}"

        # Get roughnessname
        roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

        # Add to dictionary
        self.crosssection_def[name] = {
            "id": name,
            "type": "circle",
            "thalweg": 0.0,
            "diameter": diameter,
            "frictionid": roughnessname,
        }

        return name

    def add_rectangle_definition(
        self,
        height: float,
        width: float,
        closed: bool | int,
        roughnesstype: str,
        roughnessvalue: float,
        name: str | None = None,
    ) -> str:
        """Add a rectangle cross section definition.

        Without a name, the name is derived from the shape only, so a definition with the
        same shape but another roughness replaces the earlier one.
        """
        # Get name if not given
        if name is None:
            name = f"rect_h{height:.3f}_w{width:.3f}"

        # Get roughnessname
        roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

        # Add to dictionary
        self.crosssection_def[name] = {
            "id": name,
            "type": "rectangle",
            "thalweg": 0.0,
            "height": height,
            "width": width,
            "closed": int(closed),
            "frictionid": roughnessname,
        }

        return name

    def add_trapezium_definition(
        self,
        slope: float,
        maximumflowwidth: float,
        bottomwidth: float,
        closed: bool | int,
        roughnesstype: str,
        roughnessvalue: float,
        bottomlevel: float | None = None,
        name: str | None = None,
    ) -> str:
        """Add a trapezium cross section definition.

        Without a name, the name is derived from the shape only, so a definition with the
        same shape but another roughness replaces the earlier one.
        """
        # Get name if not given
        if name is None:
            name = f"trapz_s{slope:.1f}_bw{bottomwidth:.1f}_bw{maximumflowwidth:.1f}"

        # Get roughnessname
        roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

        if bottomlevel is None:
            bottomlevel = 0.0

        if not closed:
            # an open profile ends at the bank top (maximumflowwidth); above it D-Flow FM continues vertically
            dh = (maximumflowwidth - bottomwidth) / (2.0 * slope)
            if np.isfinite(dh) and dh > 0:
                levels = f"{bottomlevel} {bottomlevel + dh:.3f}"
                flowwidths = f"{bottomwidth:.2f} {maximumflowwidth:.2f}"
            else:
                # bank height missing or below the bed: widen the profile up to a level of 100 m instead (as before)
                logger.warning(
                    f"Trapezium profile {name}: no valid height up to the bank top (maximum flow width "
                    f"{maximumflowwidth}, bottom width {bottomwidth}, slope {slope}). The profile is widened up to "
                    "a level of 100 m instead; check the bank heights (hoogte insteek) in the data."
                )
                levels = f"{bottomlevel} 100"
                flowwidths = f"{bottomwidth:.2f} {bottomwidth + 2.0 * ((100.0 - bottomlevel) * slope):.2f}"
        else:
            levels = f"0 {((maximumflowwidth - bottomwidth) / 2.0) / slope:.2f}"
            flowwidths = f"{bottomwidth:.2f} {maximumflowwidth:.2f}"

        # Add to dictionary
        self.crosssection_def[name] = {
            "id": name,
            "type": "zw",
            "thalweg": 0.0,
            "numlevels": 2,
            "levels": levels,
            "flowwidths": flowwidths,
            "totalwidths": flowwidths,
            "frictionid": roughnessname,
        }

        return name

    def add_zw_definition(
        self,
        numLevels: int,
        levels: str,
        flowWidths: str,
        totalWidths: str,
        roughnesstype: str,
        roughnessvalue: float,
        name: str | None = None,
    ) -> str:
        """Add a zw cross section definition.

        Give a name: without one, building the name raises an error.
        """
        # Get name if not given
        if name is None:
            name = f"zw_h{levels.replace(' ', '_'):.1f}_w{flowWidths.replace(' ', '_'):.1f}"

        # Get roughnessname
        roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

        # Add to dictionary
        self.crosssection_def[name] = {
            "id": name,
            "type": "zw",
            "thalweg": 0.0,
            "numlevels": int(numLevels),
            "levels": levels,
            "flowwidths": flowWidths,
            "totalwidths": totalWidths,
            "frictionid": roughnessname,
        }

        return name

    def add_crosssection_location(
        self,
        branchid: str,
        chainage: float,
        definition: str,
        minz: float = np.nan,
        shift: float = 0.0,
    ) -> None:
        """Add a cross section location, with the id ``{branchid}_{chainage:.1f}``.

        Parameters
        ----------
        branchid : str
            Branch id.
        chainage : float
            Chainage on the branch.
        definition : str
            Name of the cross section definition.
        minz : float, optional
            Not used. Defaults to NaN.
        shift : float, optional
            Vertical shift of the definition. Defaults to 0.0.
        """
        descr = f"{branchid}_{chainage:.1f}"
        # Add cross section location
        self.crosssection_loc[descr] = {
            "id": descr,
            "branchid": branchid,
            "chainage": chainage,
            "shift": shift,
            "definitionId": definition,
        }

    def get_branches_without_crosssection(self) -> list[str]:
        """Return the ids of the branches without a cross section location."""
        # First find all branches that match a cross section
        branch_ids = {dct["branchid"] for _, dct in self.crosssection_loc.items()}
        # Select the branch-ids that do nog have a matching cross section
        branches = self.hydamo.branches
        no_crosssection = branches.index[~np.isin(branches.index, list(branch_ids))]

        return no_crosssection.tolist()

    def get_structures_without_crosssection(self) -> list[str]:
        """Return the cross section definition ids of bridges and culverts that do not exist."""
        csdef_ids = [dct["id"] for _, dct in self.crosssection_def.items()]
        no_crosssection: list[str] = []
        bridge_ids = [
            dct["csdefid"] for _, dct in self.hydamo.structures.bridges_df.iterrows()
        ]
        no_cross_bridge = np.asarray(bridge_ids)[
            ~np.isin(bridge_ids, csdef_ids)
        ].tolist()
        no_crosssection = no_crosssection + no_cross_bridge
        culvert_ids = [
            dct["csdefid"] for _, dct in self.hydamo.structures.culverts_df.iterrows()
        ]
        no_cross_culvert = np.asarray(culvert_ids)[
            ~np.isin(culvert_ids, csdef_ids)
        ].tolist()
        no_crosssection = no_crosssection + no_cross_culvert
        return no_crosssection

    # legacy from delft3dfmpy, not used and not working here (self.dflowfmmodel does not exist): mypy skips it
    @no_type_check
    def get_bottom_levels(self):
        """Determine bottom levels from cross sections (legacy from delft3dfmpy, not working)."""
        # Initialize lists
        data = []
        geometry = []

        for css in self.crosssection_loc.values():
            # Get location
            geometry.append(
                self.dflowfmmodel.network.schematised.loc[
                    css["branchid"], "geometry"
                ].interpolate(css["chainage"])
            )
            shift = css["shift"]

            # Get depth from definition if yz and shift
            definition = self.crosssection_def[css["definitionId"]]
            minz = shift
            if definition["type"] == "yz":
                minz += min(float(z) for z in definition["zCoordinates"].split())

            data.append([css["branchid"], css["chainage"], minz])

        # Add to geodataframe
        gdf = gpd.GeoDataFrame(
            data=data, columns=["branchid", "chainage", "minz"], geometry=geometry
        )
        return gdf

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def crosssection_to_yzprofiles(
        self,
        crosssections: gpd.GeoDataFrame | ExtendedGeoDataFrame,
        roughness: ExtendedDataFrame,
        branches: ExtendedGeoDataFrame | None,
        roughness_variant: RoughnessVariant | None = None,
    ) -> dict:
        """Convert the HyDAMO cross sections (dwarsprofiel) to D-Flow FM input.

        Parameters
        ----------
        crosssections : gpd.GeoDataFrame
            GeoDataFrame with x,y,z-coordinates of cross sections

        Returns
        -------
        dictionary
            Dictionary with attributes of cross sections, usable for dflowfm
        """
        cssdct = {}

        css_columns = zip(
            crosssections["code"],
            crosssections.geometry,
            crosssections["branch_id"],
            crosssections["branch_offset"],
            crosssections["globalid"],
        )
        for code, geometry, branch_id, branch_offset, globalid in css_columns:
            # The cross sections from hydamo are all yz profiles

            # Determine yz_values
            xyz = np.vstack(geometry.coords[:])
            length = np.r_[
                0, np.cumsum(np.hypot(np.diff(xyz[:, 0]), np.diff(xyz[:, 1])))
            ]
            yz = np.c_[length, xyz[:, -1]]
            # the GUI cannot cope with identical y-coordinates. Add 1 cm to a 2nd duplicate.
            yz[:, 0] = np.round(yz[:, 0], 3)
            for i in range(1, yz.shape[0]):
                if yz[i, 0] <= yz[i - 1, 0]:
                    yz[i, 0] = yz[i - 1, 0] + 0.01

            # determine thalweg
            if branches is not None:
                branch_geom = branches.geometry[branches.code == branch_id].iloc[0]
                crossing = geometry.intersection(branch_geom)
                if crossing.geom_type == "MultiPoint":
                    crossing = crossing.geoms[0]
                thalweg_xyz = crossing.coords[0]
                # and the Y-coordinate of the thalweg
                thalweg = np.hypot(
                    thalweg_xyz[0] - xyz[0, 0], thalweg_xyz[1] - xyz[0, 1]
                )
            else:
                thalweg = 0.0

            if roughness_variant == RoughnessVariant.HIGH:
                ruwheid = roughness[roughness["profielpuntid"] == globalid].ruwheidhoog
            if roughness_variant == RoughnessVariant.LOW:
                ruwheid = roughness[roughness["profielpuntid"] == globalid].ruwheidlaag

            # Add to dictionary
            cssdct[code] = {
                "branchid": branch_id,
                "chainage": branch_offset,
                "yz": yz,
                "thalweg": thalweg,
                "typeruwheid": roughness[
                    roughness["profielpuntid"] == globalid
                ].typeruwheid.to_numpy()[0],
                "ruwheid": float(ruwheid.iloc[0]),
            }

        return cssdct

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def parametrised_to_profiles(
        self,
        parametrised: ExtendedDataFrame,
        parametrised_values: ExtendedDataFrame,
        branches: list,
        roughness_variant: RoughnessVariant | None = None,
        with_crosssection: Collection[Hashable] = (),
    ) -> dict:
        """Generate the parametrised cross sections of *branches*.

        Each link row gives its branch a profile, so a profile linked to several
        branches applies to each of them. A branch linked to several profiles gets
        the first, with a warning. A link is resolved against all *branches*; if
        its branch is in *with_crosssection*, it is skipped. Links to other
        branches are skipped too.

        A profile without ``taludhelling linkerzijde`` is a rectangle, otherwise
        a trapezium. A profile that lacks a dimension it needs (a bottom width and
        both bottom levels, and for a trapezium also the right slope and both
        insteek heights) is skipped with a warning.

        Parameters
        ----------
        parametrised : ExtendedDataFrame
            The links of branches to their parametrised profile
            (``hydroobject_normgp``): ``hydroobjectid`` and ``normgeparamprofielid``.
        parametrised_values : ExtendedDataFrame
            The values of the profiles (NormgeparamProfielWaarde).
        branches : list
            The branches, as rows of ``DataFrame.itertuples``.
        roughness_variant : RoughnessVariant, optional
            Use the high or the low roughness value of the profiles.
        with_crosssection : Collection[Hashable], optional
            The indices of the branches that already have a cross section, and so
            get no parametrised one. Default is none.

        Returns
        -------
        dict
            The attributes of the cross section of each branch, by branch index,
            usable for D-Flow FM.
        """
        cssdct = {}
        values_relation = DamoRelations.PARAM_PROFILE_VALUES
        chosen = _param_profile_of_branch(parametrised, branches, with_crosssection)
        for index, param in chosen.items():
            profile_id = param[values_relation.parent_key]
            values = values_relation.children_of(
                param.to_frame().T, parametrised_values
            )
            crosssection = _param_cross_section(
                values, profile_id, index, roughness_variant
            )
            if crosssection is not None:
                cssdct[index] = crosssection
        return cssdct
__init__(hydamo: HyDAMO) -> None

Create empty cross section definitions and locations.

Source code in hydrolib/dhydamo/core/hydamo.py
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
def __init__(self, hydamo: HyDAMO) -> None:
    """Create empty cross section definitions and locations."""
    self.hydamo = hydamo
    self.crosssections: list = []
    self.default_definition: str | None = None
    self.default_definition_shift = 0.0
    self.default_location = ""

    self.crosssection_loc: dict[str, dict] = {}
    self.crosssection_def: dict[str, dict] = {}

    self.get_roughnessname = self.get_roughness_description

    self.convert = CrossSectionsIO(self)
add_circle_definition(diameter: float, roughnesstype: str, roughnessvalue: float, name: str | None = None) -> str

Add a circle cross section definition.

Without a name, the name is derived from the shape only, so a definition with the same shape but another roughness replaces the earlier one.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def add_circle_definition(
    self,
    diameter: float,
    roughnesstype: str,
    roughnessvalue: float,
    name: str | None = None,
) -> str:
    """Add a circle cross section definition.

    Without a name, the name is derived from the shape only, so a definition with the
    same shape but another roughness replaces the earlier one.
    """
    # Get name if not given
    if name is None:
        name = f"circ_d{diameter:.3f}"

    # Get roughnessname
    roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

    # Add to dictionary
    self.crosssection_def[name] = {
        "id": name,
        "type": "circle",
        "thalweg": 0.0,
        "diameter": diameter,
        "frictionid": roughnessname,
    }

    return name
add_crosssection_location(branchid: str, chainage: float, definition: str, minz: float = np.nan, shift: float = 0.0) -> None

Add a cross section location, with the id {branchid}_{chainage:.1f}.

Parameters

branchid : str Branch id. chainage : float Chainage on the branch. definition : str Name of the cross section definition. minz : float, optional Not used. Defaults to NaN. shift : float, optional Vertical shift of the definition. Defaults to 0.0.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def add_crosssection_location(
    self,
    branchid: str,
    chainage: float,
    definition: str,
    minz: float = np.nan,
    shift: float = 0.0,
) -> None:
    """Add a cross section location, with the id ``{branchid}_{chainage:.1f}``.

    Parameters
    ----------
    branchid : str
        Branch id.
    chainage : float
        Chainage on the branch.
    definition : str
        Name of the cross section definition.
    minz : float, optional
        Not used. Defaults to NaN.
    shift : float, optional
        Vertical shift of the definition. Defaults to 0.0.
    """
    descr = f"{branchid}_{chainage:.1f}"
    # Add cross section location
    self.crosssection_loc[descr] = {
        "id": descr,
        "branchid": branchid,
        "chainage": chainage,
        "shift": shift,
        "definitionId": definition,
    }
add_rectangle_definition(height: float, width: float, closed: bool | int, roughnesstype: str, roughnessvalue: float, name: str | None = None) -> str

Add a rectangle cross section definition.

Without a name, the name is derived from the shape only, so a definition with the same shape but another roughness replaces the earlier one.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def add_rectangle_definition(
    self,
    height: float,
    width: float,
    closed: bool | int,
    roughnesstype: str,
    roughnessvalue: float,
    name: str | None = None,
) -> str:
    """Add a rectangle cross section definition.

    Without a name, the name is derived from the shape only, so a definition with the
    same shape but another roughness replaces the earlier one.
    """
    # Get name if not given
    if name is None:
        name = f"rect_h{height:.3f}_w{width:.3f}"

    # Get roughnessname
    roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

    # Add to dictionary
    self.crosssection_def[name] = {
        "id": name,
        "type": "rectangle",
        "thalweg": 0.0,
        "height": height,
        "width": width,
        "closed": int(closed),
        "frictionid": roughnessname,
    }

    return name
add_trapezium_definition(slope: float, maximumflowwidth: float, bottomwidth: float, closed: bool | int, roughnesstype: str, roughnessvalue: float, bottomlevel: float | None = None, name: str | None = None) -> str

Add a trapezium cross section definition.

Without a name, the name is derived from the shape only, so a definition with the same shape but another roughness replaces the earlier one.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def add_trapezium_definition(
    self,
    slope: float,
    maximumflowwidth: float,
    bottomwidth: float,
    closed: bool | int,
    roughnesstype: str,
    roughnessvalue: float,
    bottomlevel: float | None = None,
    name: str | None = None,
) -> str:
    """Add a trapezium cross section definition.

    Without a name, the name is derived from the shape only, so a definition with the
    same shape but another roughness replaces the earlier one.
    """
    # Get name if not given
    if name is None:
        name = f"trapz_s{slope:.1f}_bw{bottomwidth:.1f}_bw{maximumflowwidth:.1f}"

    # Get roughnessname
    roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

    if bottomlevel is None:
        bottomlevel = 0.0

    if not closed:
        # an open profile ends at the bank top (maximumflowwidth); above it D-Flow FM continues vertically
        dh = (maximumflowwidth - bottomwidth) / (2.0 * slope)
        if np.isfinite(dh) and dh > 0:
            levels = f"{bottomlevel} {bottomlevel + dh:.3f}"
            flowwidths = f"{bottomwidth:.2f} {maximumflowwidth:.2f}"
        else:
            # bank height missing or below the bed: widen the profile up to a level of 100 m instead (as before)
            logger.warning(
                f"Trapezium profile {name}: no valid height up to the bank top (maximum flow width "
                f"{maximumflowwidth}, bottom width {bottomwidth}, slope {slope}). The profile is widened up to "
                "a level of 100 m instead; check the bank heights (hoogte insteek) in the data."
            )
            levels = f"{bottomlevel} 100"
            flowwidths = f"{bottomwidth:.2f} {bottomwidth + 2.0 * ((100.0 - bottomlevel) * slope):.2f}"
    else:
        levels = f"0 {((maximumflowwidth - bottomwidth) / 2.0) / slope:.2f}"
        flowwidths = f"{bottomwidth:.2f} {maximumflowwidth:.2f}"

    # Add to dictionary
    self.crosssection_def[name] = {
        "id": name,
        "type": "zw",
        "thalweg": 0.0,
        "numlevels": 2,
        "levels": levels,
        "flowwidths": flowwidths,
        "totalwidths": flowwidths,
        "frictionid": roughnessname,
    }

    return name
add_yz_definition(yz: np.ndarray | None = None, thalweg: float | None = None, roughnesstype: str | None = None, roughnessvalue: float | None = None, name: str | None = None) -> str

Add a yz cross section definition.

Parameters

code : str Id of cross section branch : str Name of branch offset : float Position of cross section along branch. If not given, the position is determined from the branches in the network. These should thus be given in this case. crds : np.array Nx2 array with y, z coordinates

Source code in hydrolib/dhydamo/core/hydamo.py
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
def add_yz_definition(
    self,
    yz: np.ndarray | None = None,
    thalweg: float | None = None,
    roughnesstype: str | None = None,
    roughnessvalue: float | None = None,
    name: str | None = None,
) -> str:
    """Add a yz cross section definition.

    Parameters
    ----------
    code : str
        Id of cross section
    branch : str
        Name of branch
    offset : float
        Position of cross section along branch. If not given, the position is determined
        from the branches in the network. These should thus be given in this case.
    crds : np.array
        Nx2 array with y, z coordinates
    """
    if (
        yz is None
        or thalweg is None
        or roughnesstype is None
        or roughnessvalue is None
    ):
        raise ValueError(
            "yz, thalweg, roughnesstype and roughnessvalue are required."
        )
    # get coordinates
    length, z = yz.T
    if name is None:
        name = f"yz_{yz}:08d"

    # Get roughnessname
    roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

    # Add to dictionary
    self.crosssection_def[name] = {
        "id": name,
        "type": "yz",
        "thalweg": np.round(thalweg, decimals=3),
        "yzcount": len(z),
        "ycoordinates": self.hydamo.list_to_str(length),
        "zcoordinates": self.hydamo.list_to_str(z),
        "sectioncount": 1,
        "frictionids": roughnessname,
        "frictionpositions": self.hydamo.list_to_str([length[0], length[-1]]),
    }

    return name
add_zw_definition(numLevels: int, levels: str, flowWidths: str, totalWidths: str, roughnesstype: str, roughnessvalue: float, name: str | None = None) -> str

Add a zw cross section definition.

Give a name: without one, building the name raises an error.

Source code in hydrolib/dhydamo/core/hydamo.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
1361
1362
1363
def add_zw_definition(
    self,
    numLevels: int,
    levels: str,
    flowWidths: str,
    totalWidths: str,
    roughnesstype: str,
    roughnessvalue: float,
    name: str | None = None,
) -> str:
    """Add a zw cross section definition.

    Give a name: without one, building the name raises an error.
    """
    # Get name if not given
    if name is None:
        name = f"zw_h{levels.replace(' ', '_'):.1f}_w{flowWidths.replace(' ', '_'):.1f}"

    # Get roughnessname
    roughnessname = self.get_roughnessname(roughnesstype, roughnessvalue)

    # Add to dictionary
    self.crosssection_def[name] = {
        "id": name,
        "type": "zw",
        "thalweg": 0.0,
        "numlevels": int(numLevels),
        "levels": levels,
        "flowwidths": flowWidths,
        "totalwidths": totalWidths,
        "frictionid": roughnessname,
    }

    return name
crosssection_to_yzprofiles(crosssections: gpd.GeoDataFrame | ExtendedGeoDataFrame, roughness: ExtendedDataFrame, branches: ExtendedGeoDataFrame | None, roughness_variant: RoughnessVariant | None = None) -> dict

Convert the HyDAMO cross sections (dwarsprofiel) to D-Flow FM input.

Parameters

crosssections : gpd.GeoDataFrame GeoDataFrame with x,y,z-coordinates of cross sections

Returns

dictionary Dictionary with attributes of cross sections, usable for dflowfm

Source code in hydrolib/dhydamo/core/hydamo.py
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def crosssection_to_yzprofiles(
    self,
    crosssections: gpd.GeoDataFrame | ExtendedGeoDataFrame,
    roughness: ExtendedDataFrame,
    branches: ExtendedGeoDataFrame | None,
    roughness_variant: RoughnessVariant | None = None,
) -> dict:
    """Convert the HyDAMO cross sections (dwarsprofiel) to D-Flow FM input.

    Parameters
    ----------
    crosssections : gpd.GeoDataFrame
        GeoDataFrame with x,y,z-coordinates of cross sections

    Returns
    -------
    dictionary
        Dictionary with attributes of cross sections, usable for dflowfm
    """
    cssdct = {}

    css_columns = zip(
        crosssections["code"],
        crosssections.geometry,
        crosssections["branch_id"],
        crosssections["branch_offset"],
        crosssections["globalid"],
    )
    for code, geometry, branch_id, branch_offset, globalid in css_columns:
        # The cross sections from hydamo are all yz profiles

        # Determine yz_values
        xyz = np.vstack(geometry.coords[:])
        length = np.r_[
            0, np.cumsum(np.hypot(np.diff(xyz[:, 0]), np.diff(xyz[:, 1])))
        ]
        yz = np.c_[length, xyz[:, -1]]
        # the GUI cannot cope with identical y-coordinates. Add 1 cm to a 2nd duplicate.
        yz[:, 0] = np.round(yz[:, 0], 3)
        for i in range(1, yz.shape[0]):
            if yz[i, 0] <= yz[i - 1, 0]:
                yz[i, 0] = yz[i - 1, 0] + 0.01

        # determine thalweg
        if branches is not None:
            branch_geom = branches.geometry[branches.code == branch_id].iloc[0]
            crossing = geometry.intersection(branch_geom)
            if crossing.geom_type == "MultiPoint":
                crossing = crossing.geoms[0]
            thalweg_xyz = crossing.coords[0]
            # and the Y-coordinate of the thalweg
            thalweg = np.hypot(
                thalweg_xyz[0] - xyz[0, 0], thalweg_xyz[1] - xyz[0, 1]
            )
        else:
            thalweg = 0.0

        if roughness_variant == RoughnessVariant.HIGH:
            ruwheid = roughness[roughness["profielpuntid"] == globalid].ruwheidhoog
        if roughness_variant == RoughnessVariant.LOW:
            ruwheid = roughness[roughness["profielpuntid"] == globalid].ruwheidlaag

        # Add to dictionary
        cssdct[code] = {
            "branchid": branch_id,
            "chainage": branch_offset,
            "yz": yz,
            "thalweg": thalweg,
            "typeruwheid": roughness[
                roughness["profielpuntid"] == globalid
            ].typeruwheid.to_numpy()[0],
            "ruwheid": float(ruwheid.iloc[0]),
        }

    return cssdct
get_bottom_levels()

Determine bottom levels from cross sections (legacy from delft3dfmpy, not working).

Source code in hydrolib/dhydamo/core/hydamo.py
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
@no_type_check
def get_bottom_levels(self):
    """Determine bottom levels from cross sections (legacy from delft3dfmpy, not working)."""
    # Initialize lists
    data = []
    geometry = []

    for css in self.crosssection_loc.values():
        # Get location
        geometry.append(
            self.dflowfmmodel.network.schematised.loc[
                css["branchid"], "geometry"
            ].interpolate(css["chainage"])
        )
        shift = css["shift"]

        # Get depth from definition if yz and shift
        definition = self.crosssection_def[css["definitionId"]]
        minz = shift
        if definition["type"] == "yz":
            minz += min(float(z) for z in definition["zCoordinates"].split())

        data.append([css["branchid"], css["chainage"], minz])

    # Add to geodataframe
    gdf = gpd.GeoDataFrame(
        data=data, columns=["branchid", "chainage", "minz"], geometry=geometry
    )
    return gdf
get_branches_without_crosssection() -> list[str]

Return the ids of the branches without a cross section location.

Source code in hydrolib/dhydamo/core/hydamo.py
1398
1399
1400
1401
1402
1403
1404
1405
1406
def get_branches_without_crosssection(self) -> list[str]:
    """Return the ids of the branches without a cross section location."""
    # First find all branches that match a cross section
    branch_ids = {dct["branchid"] for _, dct in self.crosssection_loc.items()}
    # Select the branch-ids that do nog have a matching cross section
    branches = self.hydamo.branches
    no_crosssection = branches.index[~np.isin(branches.index, list(branch_ids))]

    return no_crosssection.tolist()
get_roughness_description(roughnesstype: str, value: float) -> str

Return the name of a roughness definition, added if it is new.

Parameters

roughnesstype : str HyDAMO roughness type, mapped to the D-HYDRO type. value : float Roughness value.

Returns

str Name of the definition, e.g. "Manning_0.03".

Raises

ValueError If the value is NaN.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def get_roughness_description(self, roughnesstype: str, value: float) -> str:
    """Return the name of a roughness definition, added if it is new.

    Parameters
    ----------
    roughnesstype : str
        HyDAMO roughness type, mapped to the D-HYDRO type.
    value : float
        Roughness value.

    Returns
    -------
    str
        Name of the definition, e.g. ``"Manning_0.03"``.

    Raises
    ------
    ValueError
        If the value is NaN.
    """
    if np.isnan(float(value)):
        raise ValueError("Roughness value should not be NaN.")

    # map HyDAMO definition to D-Hydro definition
    roughnesstype = self.hydamo.roughness_mapping[roughnesstype]

    # Get name
    name = f"{roughnesstype}_{float(value)}"

    # Check if the description is already known
    if name.lower() in map(str.lower, self.hydamo.roughness_definitions.keys()):
        return name

    # Add to dict
    self.hydamo.roughness_definitions[name] = {
        "frictionid": name,
        "frictiontype": roughnesstype,
        "frictionvalue": value,
    }

    return name
get_structures_without_crosssection() -> list[str]

Return the cross section definition ids of bridges and culverts that do not exist.

Source code in hydrolib/dhydamo/core/hydamo.py
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
def get_structures_without_crosssection(self) -> list[str]:
    """Return the cross section definition ids of bridges and culverts that do not exist."""
    csdef_ids = [dct["id"] for _, dct in self.crosssection_def.items()]
    no_crosssection: list[str] = []
    bridge_ids = [
        dct["csdefid"] for _, dct in self.hydamo.structures.bridges_df.iterrows()
    ]
    no_cross_bridge = np.asarray(bridge_ids)[
        ~np.isin(bridge_ids, csdef_ids)
    ].tolist()
    no_crosssection = no_crosssection + no_cross_bridge
    culvert_ids = [
        dct["csdefid"] for _, dct in self.hydamo.structures.culverts_df.iterrows()
    ]
    no_cross_culvert = np.asarray(culvert_ids)[
        ~np.isin(culvert_ids, csdef_ids)
    ].tolist()
    no_crosssection = no_crosssection + no_cross_culvert
    return no_crosssection
parametrised_to_profiles(parametrised: ExtendedDataFrame, parametrised_values: ExtendedDataFrame, branches: list, roughness_variant: RoughnessVariant | None = None, with_crosssection: Collection[Hashable] = ()) -> dict

Generate the parametrised cross sections of branches.

Each link row gives its branch a profile, so a profile linked to several branches applies to each of them. A branch linked to several profiles gets the first, with a warning. A link is resolved against all branches; if its branch is in with_crosssection, it is skipped. Links to other branches are skipped too.

A profile without taludhelling linkerzijde is a rectangle, otherwise a trapezium. A profile that lacks a dimension it needs (a bottom width and both bottom levels, and for a trapezium also the right slope and both insteek heights) is skipped with a warning.

Parameters

parametrised : ExtendedDataFrame The links of branches to their parametrised profile (hydroobject_normgp): hydroobjectid and normgeparamprofielid. parametrised_values : ExtendedDataFrame The values of the profiles (NormgeparamProfielWaarde). branches : list The branches, as rows of DataFrame.itertuples. roughness_variant : RoughnessVariant, optional Use the high or the low roughness value of the profiles. with_crosssection : Collection[Hashable], optional The indices of the branches that already have a cross section, and so get no parametrised one. Default is none.

Returns

dict The attributes of the cross section of each branch, by branch index, usable for D-Flow FM.

Source code in hydrolib/dhydamo/core/hydamo.py
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def parametrised_to_profiles(
    self,
    parametrised: ExtendedDataFrame,
    parametrised_values: ExtendedDataFrame,
    branches: list,
    roughness_variant: RoughnessVariant | None = None,
    with_crosssection: Collection[Hashable] = (),
) -> dict:
    """Generate the parametrised cross sections of *branches*.

    Each link row gives its branch a profile, so a profile linked to several
    branches applies to each of them. A branch linked to several profiles gets
    the first, with a warning. A link is resolved against all *branches*; if
    its branch is in *with_crosssection*, it is skipped. Links to other
    branches are skipped too.

    A profile without ``taludhelling linkerzijde`` is a rectangle, otherwise
    a trapezium. A profile that lacks a dimension it needs (a bottom width and
    both bottom levels, and for a trapezium also the right slope and both
    insteek heights) is skipped with a warning.

    Parameters
    ----------
    parametrised : ExtendedDataFrame
        The links of branches to their parametrised profile
        (``hydroobject_normgp``): ``hydroobjectid`` and ``normgeparamprofielid``.
    parametrised_values : ExtendedDataFrame
        The values of the profiles (NormgeparamProfielWaarde).
    branches : list
        The branches, as rows of ``DataFrame.itertuples``.
    roughness_variant : RoughnessVariant, optional
        Use the high or the low roughness value of the profiles.
    with_crosssection : Collection[Hashable], optional
        The indices of the branches that already have a cross section, and so
        get no parametrised one. Default is none.

    Returns
    -------
    dict
        The attributes of the cross section of each branch, by branch index,
        usable for D-Flow FM.
    """
    cssdct = {}
    values_relation = DamoRelations.PARAM_PROFILE_VALUES
    chosen = _param_profile_of_branch(parametrised, branches, with_crosssection)
    for index, param in chosen.items():
        profile_id = param[values_relation.parent_key]
        values = values_relation.children_of(
            param.to_frame().T, parametrised_values
        )
        crosssection = _param_cross_section(
            values, profile_id, index, roughness_variant
        )
        if crosssection is not None:
            cssdct[index] = crosssection
    return cssdct
set_default_definition(definition: str, shift: float = 0.0) -> None

Set the cross section definition for branches without a cross section.

It is used by Df2HydrolibModel(assign_default_profiles=True).

Parameters

definition : str Name of an existing cross section definition. shift : float, optional Vertical shift of the definition. Defaults to 0.0.

Raises

KeyError If the definition does not exist.

Source code in hydrolib/dhydamo/core/hydamo.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
def set_default_definition(self, definition: str, shift: float = 0.0) -> None:
    """Set the cross section definition for branches without a cross section.

    It is used by ``Df2HydrolibModel(assign_default_profiles=True)``.

    Parameters
    ----------
    definition : str
        Name of an existing cross section definition.
    shift : float, optional
        Vertical shift of the definition. Defaults to 0.0.

    Raises
    ------
    KeyError
        If the definition does not exist.
    """
    if definition not in self.crosssection_def:
        raise KeyError(f'Cross section definition "{definition}" not found."')

    self.default_definition = definition
    self.default_definition_shift = shift
set_default_locations(locations: list[str]) -> None

Set the branches that get the default cross section definition.

Parameters

locations : list[str] Branch ids.

Source code in hydrolib/dhydamo/core/hydamo.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
def set_default_locations(self, locations: list[str]) -> None:
    """Set the branches that get the default cross section definition.

    Parameters
    ----------
    locations : list[str]
        Branch ids.
    """
    self.default_locations = locations

ExternalForcings

Boundary conditions, laterals and initial and parameter fields of the model.

Parameters

hydamo : HyDAMO The HyDAMO object they belong to.

Source code in hydrolib/dhydamo/core/hydamo.py
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
class ExternalForcings:
    """Boundary conditions, laterals and initial and parameter fields of the model.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO object they belong to.
    """

    def __init__(self, hydamo: HyDAMO) -> None:
        self.hydamo = hydamo

        self.initial_waterlevel_polygons = gpd.GeoDataFrame(
            columns=["waterlevel", "geometry", "locationtype"]
        )
        self.initial_waterdepth_polygons = gpd.GeoDataFrame(
            columns=["waterdepth", "geometry", "locationtype"]
        )
        self.missing = None
        self.spatial_fields: list[dict] = []
        # number of the next spatial field, used in the generated file names
        self._next_field_number = 0

        self.boundary_nodes: dict[str, dict] = {}
        self.lateral_nodes: dict[str, dict] = {}
        self.pattern = "^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"

        self.convert = ExternalForcingsIO(self)

    def set_initial_waterlevel(
        self,
        initial_values: float | gpd.GeoDataFrame,
        *,
        locationtype: str = "1d",
        value_column: str | None = None,
    ) -> None:
        """Set the initial water level: a uniform value, or a value per polygon.

        A uniform value for 1D (locationtype '1d') is written per branch for all branches, as a spatial field at
        the position of this call: fields added after it override it where they apply, fields added before it are
        overridden. Calling it again replaces the earlier uniform water level. For 2D or 'all', a uniform value is
        written as a [Global] value.

        Polygons (1D only) are passed on to set_spatial_field and written per branch. For other spatially varying
        input, such as a model result, use set_spatial_field directly.

        Parameters
        ----------
        initial_values : float or gpd.GeoDataFrame
            Uniform water level, or polygons with water levels.
        locationtype : str, optional
            ``"1d"``, ``"2d"`` or ``"all"``. Defaults to ``"1d"``.
        value_column : str, optional
            Column with the water levels, required for polygons. Defaults to None.
        """
        self._set_initial("waterlevel", initial_values, locationtype, value_column)

    # legacy from delft3dfmpy, not used and not working here (self.mdu_parameters does not exist): mypy skips it
    @no_type_check
    def set_missing_waterlevel(self, missing):
        """Set the missing value for the water level (legacy from delft3dfmpy, not working).

        This overwrites the water level at missing value in the mdu file.

        Parameters
        ----------
        missing : float
            Water depth
        """
        self.mdu_parameters["WaterLevIni"] = missing

    def set_initial_waterdepth(
        self,
        initial_values: float | gpd.GeoDataFrame,
        *,
        locationtype: str = "1d",
        value_column: str | None = None,
    ) -> None:
        """Set the initial water depth: a uniform value, or a value per polygon.

        A uniform value for 1D (locationtype '1d') is written per branch for all branches, as a spatial field at
        the position of this call: fields added after it override it where they apply, fields added before it are
        overridden. Calling it again replaces the earlier uniform water depth. For 2D or 'all', a uniform value is
        written as a [Global] value; D-HYDRO 2026.02 then lets it override spatial water levels.

        Polygons (1D only) are passed on to set_spatial_field and written per branch. For other spatially varying
        input, such as a model result, use set_spatial_field directly.

        Parameters
        ----------
        initial_values : float or gpd.GeoDataFrame
            Uniform water depth, or polygons with water depths.
        locationtype : str, optional
            ``"1d"``, ``"2d"`` or ``"all"``. Defaults to ``"1d"``.
        value_column : str, optional
            Column with the water depths, required for polygons. Defaults to None.
        """
        self._set_initial("waterdepth", initial_values, locationtype, value_column)

    def _set_initial(
        self,
        quantity: str,
        initial_values: float | gpd.GeoDataFrame,
        locationtype: str,
        value_column: str | None,
    ) -> None:
        """Shared implementation of set_initial_waterlevel and set_initial_waterdepth."""
        if isinstance(initial_values, numbers.Real):
            if locationtype == "1d":
                # a field per branch; it leaves a uniform value for 2D or 'all' untouched
                self._set_uniform_field(quantity, float(initial_values))
            else:
                setattr(
                    self,
                    f"initial_{quantity}_polygons",
                    gpd.GeoDataFrame(
                        {
                            quantity: [float(initial_values)],
                            "geometry": [None],
                            "locationtype": [locationtype],
                        },
                        index=["global"],
                    ),
                )
            return

        if locationtype != "1d":
            raise ValueError(
                f"Initial {quantity} with polygons is only supported for 1D here. "
                "Use hydamo.external_forcings.set_spatial_field() for 2D."
            )
        if value_column is None:
            raise ValueError(
                f"Provide value_column with the initial {quantity} per polygon."
            )
        if not isinstance(initial_values, gpd.GeoDataFrame):
            raise TypeError(
                f"initial_values must be a number or a GeoDataFrame, got {type(initial_values).__name__}."
            )
        self.set_spatial_field(
            initial_values, value_column, quantity=quantity, locationtype="1d"
        )

    def _set_uniform_field(self, quantity: str, value: float) -> None:
        """Add a uniform 1D value as a spatial field per branch over all branches, replacing an earlier one.

        The values per branch are derived from the branches when the model is converted.
        """
        self.spatial_fields = [
            sf
            for sf in self.spatial_fields
            if not (sf.get("uniform") is not None and sf["quantity"] == quantity)
        ]
        self.spatial_fields.append(
            {
                "gdf": None,
                "column": None,
                "uniform": value,
                "quantity": quantity,
                "kind": "initial",
                "filetype": "branch",
                "cellsize": None,
                # "_1d" keeps it apart from the [Global] file of a uniform 2D value (inifields_to_dhydro)
                "filename": f"initial{quantity}_1d.ini",
                "locationtype": "1d",
                "interpolationmethod": None,
                "averagingtype": None,
                "operand": "O",
                "nodata": -999.0,
                "max_snap_distance": None,
            }
        )

    def correct_values_from_modelrun(
        self,
        model_values: gpd.GeoDataFrame,
        correction_polygons: gpd.GeoDataFrame,
        value_column: str,
        boundary_step: float | None = 0.01,
    ) -> gpd.GeoDataFrame:
        """Replace values from a model result by the values of correction polygons.

        All points within the polygons get the value of the polygon.

        If the points have the columns 'branchid' and 'chainage' (as from read_values_from_modelrun) and the HyDAMO
        branches are available, two points are added where a polygon boundary crosses a branch, boundary_step apart:
        the point inside gets the polygon value, the point outside the model value interpolated along the branch.
        The value then changes at the polygon boundary instead of gradually between the nearest model points.

        Parameters
        ----------
        model_values : gpd.GeoDataFrame
            Points with a column ``value``, e.g. from `read_values_from_modelrun`.
        correction_polygons : gpd.GeoDataFrame
            Polygons with the corrected values.
        value_column : str
            Column in ``correction_polygons`` with the corrected values.
        boundary_step : float, optional
            Distance between the two points at a polygon boundary; None adds no points.
            Defaults to 0.01.

        Returns
        -------
        gpd.GeoDataFrame
            Copy of ``model_values`` with corrected values (and the points at the polygon
            boundaries). Where polygons overlap, the last polygon is used.
        """
        model_values_corrected = model_values.copy(deep=True)
        if model_values_corrected.crs is None and correction_polygons.crs is not None:
            model_values_corrected = model_values_corrected.set_crs(
                correction_polygons.crs
            )

        # use a plain GeoDataFrame, an ExtendedGeoDataFrame loses the value column in the spatial join
        joined = gpd.sjoin(
            model_values_corrected[["geometry"]],
            gpd.GeoDataFrame(correction_polygons[[value_column, "geometry"]]),
            how="inner",
            predicate="intersects",
        )
        joined = joined[~joined.index.duplicated(keep="last")]

        model_values_corrected.loc[joined.index, "value"] = joined[value_column]

        branches = getattr(self.hydamo, "branches", None)
        if boundary_step is None or not {"branchid", "chainage"} <= set(
            model_values.columns
        ):
            return model_values_corrected
        if branches is None or branches.empty:
            logger.info(
                "No branches available: no points are added at the boundaries of the correction polygons."
            )
            return model_values_corrected

        boundary_points = self._points_at_polygon_boundaries(
            model_values,
            gpd.GeoDataFrame(
                correction_polygons[[value_column, "geometry"]]
            ).reset_index(drop=True),
            value_column,
            branches,
            boundary_step,
        )
        if boundary_points.empty:
            return model_values_corrected
        logger.info(
            f"{len(boundary_points)} points added at the boundaries of the correction polygons."
        )
        combined = pd.concat(
            [model_values_corrected, boundary_points], ignore_index=True
        )
        return gpd.GeoDataFrame(
            combined, geometry="geometry", crs=model_values_corrected.crs
        )

    @staticmethod
    def _points_at_polygon_boundaries(
        model_values: gpd.GeoDataFrame,
        polygons: gpd.GeoDataFrame,
        value_column: str,
        branches: gpd.GeoDataFrame,
        step: float,
    ) -> gpd.GeoDataFrame:
        """Two points per crossing of a polygon boundary with a branch, step apart, with the value on each side."""
        rows = []
        for branch_id, original in model_values.groupby("branchid"):
            if branch_id not in branches.index:
                continue
            line = branches.geometry.loc[branch_id]
            if not isinstance(line, LineString):
                raise TypeError(
                    f"Branch {branch_id} is a {line.geom_type}, expected a LineString."
                )
            candidates = polygons.iloc[
                polygons.sindex.query(line, predicate="intersects")
            ]
            if candidates.empty:
                continue
            original = original.sort_values("chainage")

            # two chainages per crossing of a polygon boundary, half a step on either side, within the branch
            chainages = [
                chainage
                for crossing in _boundary_crossings(line, candidates)
                for chainage in (crossing - 0.5 * step, crossing + 0.5 * step)
                if 0.0 <= chainage <= line.length
            ]
            for chainage in chainages:
                point = line.interpolate(chainage)
                value = _value_at_chainage(
                    point, chainage, candidates, value_column, original
                )
                rows.append(
                    {
                        "x": point.x,
                        "y": point.y,
                        "value": value,
                        "branchid": branch_id,
                        "chainage": chainage,
                        "geometry": point,
                    }
                )
        if not rows:
            return gpd.GeoDataFrame(
                columns=["x", "y", "value", "branchid", "chainage", "geometry"],
                geometry="geometry",
            )
        return gpd.GeoDataFrame(rows, geometry="geometry", crs=model_values.crs)

    def read_values_from_modelrun(
        self,
        netcdf_path: str | Path,
        netcdf_field: str,
        netcdf_index: int | None = None,
        crs: CRS | str | int | None = None,
        time: datetime | pd.Timestamp | str | None = None,
    ) -> gpd.GeoDataFrame:
        """Read the values of a 1D variable from a model result (map or fou file).

        Variables on the 1D nodes (e.g. 'mesh1d_s1', 'mesh1d_waterdepth') are returned at the node locations,
        variables on the 1D edges/flow links (e.g. 'mesh1d_u1') at the edge locations.

        If 'mesh1d_s1' is requested but the file only contains the water depth, the water level is computed
        as bed level + water depth.

        Missing values (dry nodes or links in a map-file) are replaced by the bed level for water levels,
        and by 0 for water depths, velocities and discharges; for other variables they are left out.

        If the file contains the 1D network topology, the columns 'branchid' and 'chainage' are added, so the
        values can be written per branch with set_spatial_field(..., filetype="branch"). For edge variables,
        the column 'direction' (angle of the link in radians) is added, as used by set_initial_velocity.

        Parameters
        ----------
        netcdf_path : str or Path
            Path to the netCDF file.
        netcdf_field : str
            Variable to read, e.g. ``"mesh1d_s1"`` (map) or ``"mesh1d_fourier001_max"`` (fou).
        netcdf_index : int, optional
            Time index, e.g. 0 for the first time step. Defaults to None: without a
            time, the last time step.
        crs : CRS, str or int, optional
            Coordinate reference system of the model. Defaults to None.
        time : datetime, pd.Timestamp or str, optional
            Time for which the values are read, e.g. ``"2016-06-02 12:00"``; the nearest
            time step is used. Defaults to None.

        Returns
        -------
        gpd.GeoDataFrame
            Points with the columns x, y and value (and branchid, chainage and
            direction, if available).
        """
        logger.info(f"Reading {netcdf_field} from {netcdf_path} ...")
        with Dataset(netcdf_path, "r") as results:  # Open file in read mode
            variable, from_depth = self._select_netcdf_variable(
                results, netcdf_field, netcdf_path
            )
            netcdf_index = self._resolve_netcdf_index(
                results, variable, netcdf_field, netcdf_path, netcdf_index, time
            )
            masked = np.ma.masked_invalid(
                variable[:] if netcdf_index is None else variable[netcdf_index, :]
            )
            if from_depth:
                # dry nodes (missing depth) get the bed level
                bed_level = np.ma.filled(results["mesh1d_flowelem_bl"][:], np.nan)
                masked = np.ma.masked_invalid(bed_level + np.ma.filled(masked, 0.0))

            # location of the variable: 1D nodes or 1D edges (flow links)
            location = "edge" if variable.dimensions[-1] == "mesh1d_nEdges" else "node"
            x = np.array(results[f"mesh1d_{location}_x"][:])
            y = np.array(results[f"mesh1d_{location}_y"][:])
            if masked.ndim != 1 or len(x) != len(masked):
                raise ValueError(
                    f"For {netcdf_field} in {netcdf_path}, length of coordinates and values are not equal."
                )

            topology = self._read_1d_topology(results, location)
            value, missing = self._fill_missing_values(
                masked, results, netcdf_field, location
            )
            if missing.any():
                logger.warning(
                    f"{missing.sum()} {location}s without a value in {netcdf_field} are left out."
                )
                x, y, value = x[~missing], y[~missing], value[~missing]
                topology = {key: values[~missing] for key, values in topology.items()}

        return gpd.GeoDataFrame(
            {"x": x, "y": y, "value": value, **topology},
            geometry=gpd.points_from_xy(x, y),
            crs=crs,
        )

    @staticmethod
    def _select_netcdf_variable(
        results: Dataset, netcdf_field: str, netcdf_path: str | Path
    ) -> tuple[Variable, bool]:
        """Return the variable to read from a model result.

        If 'mesh1d_s1' is requested but the file only contains the water depth, the water depth is returned,
        to compute the water level as bed level + water depth.

        Parameters
        ----------
        results : Dataset
            The opened map- or fou-file.
        netcdf_field : str
            Requested variable, e.g. 'mesh1d_s1'.
        netcdf_path : str | Path
            Path of the file, for messages.

        Returns
        -------
        tuple[Variable, bool]
            The variable, and whether it is the water depth that replaces 'mesh1d_s1'.

        Raises
        ------
        KeyError
            If the variable is not in the file.
        """
        from_depth = (
            netcdf_field == "mesh1d_s1"
            and netcdf_field not in results.variables
            and {"mesh1d_waterdepth", "mesh1d_flowelem_bl"} <= set(results.variables)
        )
        if from_depth:
            logger.info(
                "mesh1d_s1 is not in the file; the water level is computed as bed level + water depth."
            )
            return results["mesh1d_waterdepth"], True
        if netcdf_field in results.variables:
            return results[netcdf_field], False
        raise KeyError(f"{netcdf_field} not found in {netcdf_path}.")

    @staticmethod
    def _resolve_netcdf_index(
        results: Dataset,
        variable: Variable,
        netcdf_field: str,
        netcdf_path: str | Path,
        netcdf_index: int | None,
        time: datetime | pd.Timestamp | str | None,
    ) -> int | None:
        """Time index to read, from netcdf_index or time; the last time step if neither is given.

        Parameters
        ----------
        results : Dataset
            The opened map- or fou-file.
        variable : Variable
            The variable to read.
        netcdf_field : str
            Requested variable, for messages.
        netcdf_path : str | Path
            Path of the file, for messages.
        netcdf_index : int | None
            Requested time index.
        time : datetime | pd.Timestamp | str | None
            Requested time; the nearest time step is used.

        Returns
        -------
        int | None
            The time index, or None for a variable without a time dimension.

        Raises
        ------
        ValueError
            If both netcdf_index and time are given, or one of them for a variable without a time dimension.
        """
        has_time = "time" in variable.dimensions
        if time is not None:
            if netcdf_index is not None:
                raise ValueError("Provide either netcdf_index or time, not both.")
            if not has_time:
                raise ValueError(
                    f"{netcdf_field} in {netcdf_path} has no time dimension."
                )
            return time_index(results, time)
        if netcdf_index is not None and not has_time:
            raise ValueError(
                f"{netcdf_field} in {netcdf_path} has no time dimension; do not provide netcdf_index."
            )
        if netcdf_index is None and has_time:
            n_time = results.dimensions["time"].size
            if n_time != 1:
                logger.info(
                    f"No time given; the last of the {n_time} time steps in {netcdf_path} is used."
                )
            return -1
        return netcdf_index

    @staticmethod
    def _read_1d_topology(results: Dataset, location: str) -> dict[str, np.ndarray]:
        """Branch id and chainage of the 1D nodes or edges, and the direction of the edges, if in the file.

        Parameters
        ----------
        results : Dataset
            The opened map- or fou-file.
        location : str
            'node' or 'edge'.

        Returns
        -------
        dict[str, np.ndarray]
            'branchid' and 'chainage' (if the file contains the 1D network topology), and for edges
            'direction' (angle of the link from its first to its second node, in radians).
        """
        topology = {}
        if all(
            v in results.variables
            for v in (
                f"mesh1d_{location}_branch",
                f"mesh1d_{location}_offset",
                "network1d_branch_id",
            )
        ):
            branch_ids = np.array(
                [b.strip() for b in chartostring(results["network1d_branch_id"][:])],
                dtype=object,
            )
            branch_index = np.array(results[f"mesh1d_{location}_branch"][:]).astype(int)
            branch_index -= int(
                getattr(results[f"mesh1d_{location}_branch"], "start_index", 0)
            )
            topology = {
                "branchid": branch_ids[branch_index],
                "chainage": np.array(results[f"mesh1d_{location}_offset"][:]),
            }
        if location == "edge" and "mesh1d_edge_nodes" in results.variables:
            # direction of the link (from its first to its second node), to decompose velocities in x and y
            edge_nodes = np.array(results["mesh1d_edge_nodes"][:]).astype(int)
            edge_nodes -= int(getattr(results["mesh1d_edge_nodes"], "start_index", 0))
            node_x, node_y = (
                np.array(results["mesh1d_node_x"][:]),
                np.array(results["mesh1d_node_y"][:]),
            )
            topology["direction"] = np.arctan2(
                node_y[edge_nodes[:, 1]] - node_y[edge_nodes[:, 0]],
                node_x[edge_nodes[:, 1]] - node_x[edge_nodes[:, 0]],
            )
        return topology

    @staticmethod
    def _fill_missing_values(
        masked: np.ma.MaskedArray, results: Dataset, netcdf_field: str, location: str
    ) -> tuple[np.ndarray, np.ndarray]:
        """Fill missing values (dry nodes or links) where a fill value is known.

        Water levels get the bed level, and water depths, velocities and discharges get 0. Other variables
        are not filled.

        Parameters
        ----------
        masked : np.ma.MaskedArray
            Values, with missing values masked.
        results : Dataset
            The opened map- or fou-file, for the bed level.
        netcdf_field : str
            Requested variable, which determines the fill value.
        location : str
            'node' or 'edge'; values on edges (velocities, discharges) are filled with 0.

        Returns
        -------
        tuple[np.ndarray, np.ndarray]
            The values (NaN where still missing), and a boolean array that is True where values are missing.
        """
        missing = np.ma.getmaskarray(masked)
        if not missing.any():
            return np.ma.filled(masked, np.nan), missing
        name = netcdf_field.lower()
        if "depth" in name or location == "edge" or "velocity" in name:
            fill, label = np.zeros(len(masked)), "0"
        elif (
            name.endswith("_s1") or "waterlevel" in name
        ) and "mesh1d_flowelem_bl" in results.variables:
            fill, label = (
                np.ma.filled(results["mesh1d_flowelem_bl"][:], np.nan),
                "the bed level",
            )
        else:
            return np.ma.filled(masked, np.nan), missing
        logger.info(
            f"{missing.sum()} {location}s without a value (dry) in {netcdf_field}, set to {label}."
        )
        value = np.where(missing, fill, np.ma.filled(masked, np.nan))
        return value, np.isnan(value)

    def set_initial_velocity(
        self, velocities: gpd.GeoDataFrame, column: str = "value"
    ) -> None:
        """Set the initial velocity on the 1D flow links from a model result.

        E.g. ``"mesh1d_u1"`` read with `read_values_from_modelrun`.

        D-Flow FM (2026.02) does not accept 'initialvelocity' in the initial fields file, only the components
        'initialvelocityx' and 'initialvelocityy'. The velocity along each link is therefore decomposed with
        the link direction and written as two sample files (triangulation). Tested with DIMR: on links that
        are in both models, the initial velocity equals the velocity of the model result within 1 cm/s.
        The effect of an initial velocity is short: the flow adapts within the first minutes.

        Parameters
        ----------
        velocities : gpd.GeoDataFrame
            Points at the link locations with the velocity and the column ``direction``
            (angle of the link in radians), as returned by `read_values_from_modelrun`.
        column : str, optional
            Column with the velocity along the link. Defaults to ``"value"``.
        """
        if "direction" not in velocities.columns:
            raise ValueError(
                "The column 'direction' (angle of the link) is required. Read the velocity with "
                "read_values_from_modelrun from a file with 'mesh1d_edge_nodes'."
            )
        speed = velocities[column].astype(float).to_numpy()
        angle = velocities["direction"].astype(float).to_numpy()
        for component, values in (
            ("x", speed * np.cos(angle)),
            ("y", speed * np.sin(angle)),
        ):
            self.set_spatial_field(
                velocities.assign(_component=values)[["_component", "geometry"]],
                "_component",
                quantity=f"initialvelocity{component}",
                filetype="sample",
                interpolationmethod="triangulation",
            )

    def set_spatial_field(
        self,
        gdf: gpd.GeoDataFrame | Path | str,
        column: str | None = None,
        quantity: str = "waterlevel",
        kind: str = "initial",
        filetype: str | None = None,
        cellsize: float | None = None,
        locationtype: str = "1d",
        interpolationmethod: str | None = None,
        averagingtype: str = "nearestNb",
        operand: str = "O",
        nodata: float = -999.0,
        max_snap_distance: float = 5.0,
        averagingrelsize: float | None = None,
        averagingnummin: int | None = None,
        averagingpercentile: float | None = None,
        extrapolationmethod: bool | None = None,
    ) -> None:
        """Add a spatially varying field to the initial fields file (initialFields.ini).

        By default, values are written per branch and chainage in a 1dField file (filetype 'branch'), for
        polygons and points. D-Flow FM interpolates them linearly along each branch only, and keeps them
        constant beyond the first and last chainage of a branch. For polygons, each part of a branch inside a
        polygon gets the polygon value, with a step at the polygon boundary. For points, the columns 'branchid'
        and 'chainage' are used if present (e.g. from read_values_from_modelrun); otherwise points are snapped to
        the nearest branch within max_snap_distance. In DIMR tests (D-HYDRO 2026.02) this gave the most reliable
        result for polygons, for model results on the same network and on a changed 1D grid, and for combining
        water level and water depth.

        Advanced: the other file types are kept for special cases (e.g. 2D, or if a future D-Flow FM version
        does not accept 1dField files), but are not recommended for 1D:

        - 'sample': points as samples (.xyz) with triangulation, which fills the convex hull of the points, so
          values spread to other branches.
        - 'polygon': .pol files with interpolationMethod=constant, one file and block per distinct value.
        - 'raster': polygons rasterized to a GeoTIFF (.tif) or ArcInfo grid (.asc), requires a cellsize. D-Flow FM
          (2026.02) uses the nodata value as data.

        Tested with D-HYDRO 2026.02 on 1D nodes: interpolationMethod=averaging assigns no values, so it is
        refused for locationtype '1d'; triangulation fills the convex hull of the samples; nodes that get no
        value from any field keep the default water level (WaterLevIni in the MDU), which leaves them dry when it
        is below the bed level, so cover all nodes. Fields are applied in the order they are added (the last
        one wins). A uniform 1D value from set_initial_waterlevel/-depth is a field per branch over all branches, at
        the position of that call, so use it first as a background. A water depth from polygons or samples removes earlier water levels from polygons
        or samples everywhere, also outside its own area; water levels per branch are kept. Add water depth
        fields before water level fields.

        For samples and rasters on 2D cells, choose the interpolation by the density of the data: 'averaging' for
        dense data (several values per cell, e.g. a point cloud or a fine raster), 'triangulation' for sparse data
        (fewer values than cells, e.g. measured points). Averaging combines the values inside each cell, as set by
        averagingtype and the averaging settings below; triangulation interpolates linearly between the values, and
        only within their convex hull unless extrapolationmethod is True. Settings left at None are not written, so
        D-Flow FM uses its defaults.

        The data files are written by Df2HydrolibModel.write_initial_fields().

        Parameters
        ----------
        gdf : gpd.GeoDataFrame or Path or str
            Polygons or points with values, or the path to an existing .xyz file (x, y
            and value per line). An .xyz file becomes a sample field (filetype
            ``"sample"``, no column) and is copied unchanged under the generated name
            when the model is written. For initial water levels and depths, only with
            locationtype ``"2d"``: D-HyDAMO does not read its values, so it cannot check
            them against other water level and depth fields on the 1D nodes.
        column : str, optional
            Column with the values. For points, None means the Z coordinate is used.
        quantity : str, optional
            D-Flow FM quantity, e.g. ``"waterlevel"`` or ``"waterdepth"``. For velocities,
            use `set_initial_velocity`. Defaults to ``"waterlevel"``.
        kind : str, optional
            ``"initial"`` ([Initial] block) or ``"parameter"`` ([Parameter] block).
            Defaults to ``"initial"``.
        filetype : str, optional
            ``"branch"`` (default), or the advanced types ``"sample"``, ``"polygon"`` or
            ``"raster"``.
        cellsize : float, optional
            Raster cell size, required for filetype ``"raster"``.
        locationtype : str, optional
            ``"1d"``, ``"2d"`` or ``"all"``. Defaults to ``"1d"``.
        interpolationmethod : str, optional
            ``"constant"`` (polygon), ``"triangulation"`` or ``"averaging"``. Not used for
            ``"branch"``. Defaults to ``"triangulation"`` for samples, ``"constant"`` for
            polygon files, and ``"averaging"`` for rasters (2D) or ``"triangulation"`` (1D).
        averagingtype : str, optional
            Averaging type, if interpolationmethod is ``"averaging"``. Defaults to
            ``"nearestNb"``.
        operand : str, optional
            How the field is combined with previous fields. Defaults to ``"O"`` (override).
        nodata : float, optional
            Nodata value for rasters, and the [Global] value of 1dField files (branch),
            which D-Flow FM treats as no value. Defaults to -999.0.
        max_snap_distance : float, optional
            Maximum distance to snap points to a branch for filetype ``"branch"``. Defaults
            to 5.0.
        averagingrelsize : float, optional
            With ``"averaging"``, the size of the area around a cell that is searched for
            values, relative to the cell size (D-Flow FM default 1.01). Larger values
            smooth more, and fill cells with few values. Defaults to None (not written).
        averagingnummin : int, optional
            With ``"averaging"``, the minimum number of values in that area; a cell with
            fewer gets no value from this field (D-Flow FM default 1). Defaults to None
            (not written).
        averagingpercentile : float, optional
            With ``"averaging"``, the percentile of the values to use instead of all
            values, e.g. a low percentile for the lowest part of a cell (D-Flow FM
            default 0, off). Defaults to None (not written).
        extrapolationmethod : bool, optional
            With ``"triangulation"``, True also gives values outside the convex hull of
            the data. Defaults to None: not set, which hydrolib-core writes as
            ``extrapolationMethod = 0``.
        """
        if kind not in ("initial", "parameter"):
            raise ValueError(f"kind should be 'initial' or 'parameter', not '{kind}'.")
        if quantity.lower() == "initialvelocity":
            raise ValueError(
                "D-Flow FM (2026.02) does not support 'initialvelocity' in the initial fields file. "
                "Use set_initial_velocity, which writes the x and y components."
            )

        xyz_file: Path | None = None
        field_gdf: gpd.GeoDataFrame | None = None
        if isinstance(gdf, (str, Path)):
            if column is not None:
                raise ValueError(
                    "An .xyz file has its values in the third column; do not pass a column."
                )
            if filetype not in {None, "sample"}:
                raise ValueError(
                    f"An .xyz file is a sample field, not filetype '{filetype}'."
                )
            if level_or_depth(quantity) is not None and locationtype != "2d":
                raise ValueError(
                    "An .xyz file for an initial water level or depth is only supported for locationtype '2d'. "
                    "D-HyDAMO does not read the file, so on 1D nodes it cannot check the field against other water "
                    "level and depth fields or export it with initial_conditions_at_nodes. Read the points into a "
                    "GeoDataFrame and pass that instead (filetype 'branch' is the default for 1D)."
                )
            xyz_file = self._xyz_file(gdf)
            filetype = "sample"
        else:
            if gdf.empty:
                raise ValueError("The provided GeoDataFrame is empty.")
            geomtypes = set(gdf.geom_type)
            filetype = self._resolve_filetype(geomtypes, filetype)
            if filetype == "branch" and locationtype != "1d":
                raise ValueError(
                    "Filetype 'branch' is only available for locationtype '1d'."
                )
            if filetype == "raster" and cellsize is None:
                raise ValueError("A cellsize is required to rasterize polygons.")
            self._warn_spatial_field_options(gdf, filetype, locationtype)
            gdf, column = self._value_column(gdf, column, geomtypes)
            columns = [column, "geometry"]
            if filetype == "branch" and {"branchid", "chainage"} <= set(gdf.columns):
                columns = ["branchid", "chainage"] + columns
            field_gdf = gpd.GeoDataFrame(gdf[columns].copy())

        interpolationmethod = self._resolve_interpolation(
            filetype, locationtype, interpolationmethod
        )
        sample_settings = {
            "averagingrelsize": averagingrelsize,
            "averagingnummin": averagingnummin,
            "averagingpercentile": averagingpercentile,
            "extrapolationmethod": extrapolationmethod,
        }
        self._warn_sample_settings(interpolationmethod, sample_settings)
        filename = self._next_field_filename(kind, quantity, filetype)

        self.spatial_fields.append(
            {
                "gdf": field_gdf,
                "xyz_file": xyz_file,
                "column": column,
                "quantity": quantity,
                "kind": kind,
                "filetype": filetype,
                "cellsize": cellsize,
                "filename": filename,
                "locationtype": locationtype,
                "interpolationmethod": interpolationmethod,
                "averagingtype": averagingtype,
                "operand": operand,
                "nodata": nodata,
                "max_snap_distance": max_snap_distance,
                "sample_settings": sample_settings,
            }
        )

    @staticmethod
    def _xyz_file(path: Path | str) -> Path:
        """Check an existing .xyz file for a spatial field, without reading the whole file.

        Parameters
        ----------
        path : Path or str
            Path to the .xyz file.

        Returns
        -------
        Path
            The absolute path to the file.

        Raises
        ------
        ValueError
            If the first data line does not start with three numbers.
        FileNotFoundError
            If the file does not exist.
        """
        path = Path(path)
        if not path.is_file():
            raise FileNotFoundError(f"The .xyz file {path} does not exist.")
        first_line = ""
        with path.open(encoding="utf-8", errors="replace") as file:
            for line in file:
                # like hydrolib-core's XYZ parser: skip empty lines and comment lines
                # starting with '*'
                if line.strip() and not line.lstrip().startswith("*"):
                    first_line = line
                    break
        values = first_line.split()[:3]
        try:
            for value in values:
                float(value)
        except ValueError:
            values = []
        if len(values) < 3:
            raise ValueError(
                f"The first data line of {path} should start with three numbers (x, y, value), "
                f"not {first_line.strip()!r}."
            )
        return path.resolve()

    @staticmethod
    def _resolve_filetype(geomtypes: set[str], filetype: str | None) -> str:
        """Check the filetype for the geometry type of a spatial field; the default is 'branch'.

        Parameters
        ----------
        geomtypes : set[str]
            Geometry types in the GeoDataFrame.
        filetype : str | None
            Requested filetype, or None for the default.

        Returns
        -------
        str
            The filetype.

        Raises
        ------
        ValueError
            If the geometries are not all (multi)polygons or all points, or the filetype is not
            available for them.
        """
        if geomtypes <= {"Polygon", "MultiPolygon"}:
            filetype = "branch" if filetype is None else filetype
            if filetype not in ("branch", "polygon", "raster"):
                raise ValueError(
                    f"For polygons, filetype should be 'branch', 'polygon' or 'raster', not '{filetype}'."
                )
        elif geomtypes <= {"Point"}:
            filetype = "branch" if filetype is None else filetype
            if filetype not in ("sample", "branch"):
                raise ValueError(
                    f"For points, filetype should be 'sample' or 'branch', not '{filetype}'."
                )
        else:
            raise ValueError(
                f"Only (multi)polygons or points are supported, found: {geomtypes}."
            )
        return filetype

    @staticmethod
    def _resolve_interpolation(
        filetype: str, locationtype: str, interpolationmethod: str | None
    ) -> str | None:
        """Interpolation method of a spatial field, with the default per filetype and location type.

        Parameters
        ----------
        filetype : str
            'branch', 'polygon', 'raster' or 'sample'.
        locationtype : str
            '1d', '2d' or 'all'.
        interpolationmethod : str | None
            Requested interpolation method, or None for the default.

        Returns
        -------
        str | None
            None for 'branch' (not used for 1dField files); otherwise the requested method, or
            'constant' (polygon), 'averaging' (raster, not 1D) or 'triangulation'.

        Raises
        ------
        ValueError
            For polygon files with a method other than 'constant', and for 'averaging' on 1D nodes.
        """
        if filetype == "branch":
            return None
        if interpolationmethod is None:
            if filetype == "polygon":
                interpolationmethod = "constant"
            elif filetype == "raster" and locationtype != "1d":
                interpolationmethod = "averaging"
            else:
                interpolationmethod = "triangulation"
        if filetype == "polygon" and interpolationmethod != "constant":
            raise ValueError(
                "Polygon files only support interpolationmethod 'constant'."
            )
        if interpolationmethod == "averaging" and locationtype == "1d":
            raise ValueError(
                "interpolationmethod 'averaging' assigns no values to 1D nodes (D-HYDRO 2026.02). "
                "Use filetype 'branch' or 'polygon' for polygons, or 'triangulation' for samples."
            )
        return interpolationmethod

    @staticmethod
    def _warn_sample_settings(
        interpolationmethod: str | None, sample_settings: dict
    ) -> None:
        """Warn for sample settings that do not apply to the interpolation method.

        Such a setting is still written, but has no effect. The values themselves are
        checked by hydrolib-core when the field is converted.

        Parameters
        ----------
        interpolationmethod : str or None
            The resolved interpolation method, or None for ``"branch"``.
        sample_settings : dict
            averagingrelsize, averagingnummin, averagingpercentile and
            extrapolationmethod, None when not set.
        """
        if interpolationmethod != "averaging":
            for name in ["averagingrelsize", "averagingnummin", "averagingpercentile"]:
                if sample_settings[name] is not None:
                    logger.warning(
                        "averagingrelsize, averagingnummin and averagingpercentile only apply to "
                        f"interpolationmethod 'averaging', not {interpolationmethod!r}, and have no effect."
                    )
                    break
        if (
            sample_settings["extrapolationmethod"] is not None
            and interpolationmethod != "triangulation"
        ):
            logger.warning(
                "extrapolationmethod only applies to interpolationmethod 'triangulation', "
                f"not {interpolationmethod!r}, and has no effect."
            )

    @staticmethod
    def _warn_spatial_field_options(
        gdf: gpd.GeoDataFrame, filetype: str, locationtype: str
    ) -> None:
        """Warn for options that work, but may not give the intended result.

        Parameters
        ----------
        gdf : gpd.GeoDataFrame
            Polygons or points with values.
        filetype : str
            'branch', 'polygon', 'raster' or 'sample'.
        locationtype : str
            '1d', '2d' or 'all'.
        """
        if filetype == "raster" and locationtype in ("1d", "all"):
            logger.warning(
                "D-Flow FM uses the raster nodata value as data, which affects 1D nodes near polygon edges. "
                "Consider filetype 'branch' for 1D."
            )
        if (
            filetype == "polygon"
            and (
                shapely.get_num_interior_rings(gdf.geometry.explode().to_numpy()) > 0
            ).any()
        ):
            logger.warning(
                "Polygon files do not support holes; interiors of the polygons are ignored."
            )

    @staticmethod
    def _value_column(
        gdf: gpd.GeoDataFrame, column: str | None, geomtypes: set[str]
    ) -> tuple[gpd.GeoDataFrame, str]:
        """Column with the values of a spatial field; without a column, the Z-coordinate of points is used.

        Parameters
        ----------
        gdf : gpd.GeoDataFrame
            Polygons or points with values.
        column : str | None
            Column with values, or None to use the Z-coordinate of points.
        geomtypes : set[str]
            Geometry types in the GeoDataFrame.

        Returns
        -------
        tuple[gpd.GeoDataFrame, str]
            The GeoDataFrame (with a column '_z' if the Z-coordinate is used) and the value column.

        Raises
        ------
        ValueError
            If there is no column and no Z-coordinate, or the column has missing values.
        """
        if column is None:
            if "Point" not in geomtypes or not gdf.has_z.all():
                raise ValueError(
                    "Provide a value column, or use points with a Z-coordinate."
                )
            gdf = gdf.assign(_z=gdf.geometry.z)
            column = "_z"

        if gdf[column].isna().any():
            raise ValueError(
                f"Column {column} not filled for all features. Please provide valid values."
            )
        return gdf, column

    def _next_field_filename(self, kind: str, quantity: str, filetype: str) -> str:
        """Return a file name that is unique per field, e.g. initial_waterlevel_00.ini.

        Uniform values (set_initial_waterlevel/-depth) use other names.

        Parameters
        ----------
        kind : str
            'initial' or 'parameter'.
        quantity : str
            D-Flow FM quantity, e.g. 'waterlevel'.
        filetype : str
            'branch', 'polygon', 'raster' or 'sample'.

        Returns
        -------
        str
            The file name.
        """
        ext = {"branch": ".ini", "polygon": ".pol", "raster": ".tif", "sample": ".xyz"}[
            filetype
        ]
        name = quantity.lower().removeprefix(kind)
        filename = f"{kind}_{name}_{self._next_field_number:02d}{ext}"
        self._next_field_number += 1
        return filename

    # legacy from delft3dfmpy, not used and not working here (self.boundaries does not exist): mypy skips it
    @no_type_check
    def add_rainfall_2D(self, fName, bctype="rainfall"):
        """Add 2D rainfall from a netCDF file (legacy from delft3dfmpy, not working).

        Parameters
        ----------
        fName : str
            Location of netcdf file containing rainfall rasters
        bctype : str
            Type of boundary condition. Currently only rainfall is supported
        """
        assert bctype in ["rainfall"]

        # Add boundary condition
        self.boundaries["rainfall_2D"] = {
            "file_name": fName,
            "bctype": bctype + "bnd",
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_boundary_condition(
        self,
        name: str,
        pt: tuple[float, float] | Point,
        quantity: str,
        value: float | pd.Series | dict[str, list[float]],
        mesh1d: netmodels.Network | None = None,
    ) -> None:
        """Add a boundary condition at the 1D node nearest to a location.

        Parameters
        ----------
        name : str
            Id of the boundary condition.
        pt : tuple[float, float] or Point
            Location of the boundary condition.
        quantity : str
            ``"dischargebnd"``, ``"waterlevelbnd"`` or ``"qhbnd"``.
        value : float, pd.Series or dict[str, list[float]]
            A constant, a time series with a datetime index, or a Q-H table
            ``{"Q": [...], "H": [...]}``.
        mesh1d : Network, optional
            Network with the 1D mesh. Required; the default None raises a ValueError.

        Raises
        ------
        KeyError
            If a boundary condition with this name exists, or the network has no 1D mesh.
        ValueError
            If no network is given.
        """
        assert quantity in ["dischargebnd", "waterlevelbnd", "qhbnd"]

        if isinstance(value, pd.Series):
            vec1: list[float] | None = (
                (value.index - value.index[0]).total_seconds() / 60.0
            ).tolist()
            vec2: list[float] | float = value.to_numpy().tolist()
            startdate = value.index[0].strftime("%Y-%m-%d %H:%M:%S")
            unit1 = f"minutes since {startdate}"
            unit2 = "m3/s" if quantity == "dischargebnd" else "m"
        elif isinstance(value, float):
            vec1 = None
            vec2 = float(value)
            startdate = "0000-00-00 00:00:00"
            unit1 = f"minutes since {startdate}"
            unit2 = "m3/s" if quantity == "dischargebnd" else "m"
        else:
            vec1 = value["Q"]
            vec2 = value["H"]
            unit1 = "m3/s"
            unit2 = "m"

        if name in self.boundary_nodes:
            raise KeyError(
                f'A boundary condition with name "{name}" is already present.'
            )

        if isinstance(pt, tuple):
            pt = Point(*pt)

        # Find the nearest node
        if mesh1d is None:
            raise ValueError("Provide the network with the 1d mesh (mesh1d).")
        if len(mesh1d._mesh1d.mesh1d_node_id) == 0:
            raise KeyError(
                "To find the closest node a 1d mesh should be created first."
            )
        nodes1d = np.asarray(
            [
                n
                for n in zip(
                    mesh1d._mesh1d.mesh1d_node_x,
                    mesh1d._mesh1d.mesh1d_node_y,
                    mesh1d._mesh1d.mesh1d_node_id,
                )
            ]
        )
        get_nearest = KDTree(nodes1d[:, 0:2])
        _, idx_nearest = get_nearest.query(pt.coords[:])
        nodeid = f"{float(nodes1d[idx_nearest[0], 0]):12.6f}_{float(nodes1d[idx_nearest[0], 1]):12.6f}"

        # Add boundary condition
        self.boundary_nodes[name] = {
            "id": name,
            "quantity": quantity,
            "vec1": vec1,
            "vec2": vec2,
            "unit1": unit1,
            "unit2": unit2,
            "nodeid": nodeid,
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_rain_series(self, name: str, values: list, times: list) -> None:
        """Add a rain series as a boundary condition.

        Parameters
        ----------
        name : str
            ID of the condition
        values : list of floats
            Values of the rain intensity
        times : list of datetime
            Times for the values
        """
        # Add boundary condition
        self.boundary_nodes[name] = {
            "code": name,
            "bctype": "rainfall",
            "filetype": 1,
            "method": 1,
            "operand": "O",
            "value": values,
            "time": times,
            "geometry": None,
            "branchid": None,
        }

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_lateral(
        self,
        id: str,
        branchid: str,
        chainage: str,
        discharge: Annotated[
            pd.Series | float | str, Field(union_mode="left_to_right")
        ],
    ) -> None:
        """Add a lateral.

        Parameters
        ----------
        id : str
            Id of the lateral.
        branchid : str
            Branch on which the lateral lies.
        chainage : str
            Chainage on the branch.
        discharge : pd.Series, float or str
            ``"realtime"`` when coupled to RR, a constant discharge, or a time series with
            a datetime index.
        """
        # Convert time to minutes
        if isinstance(discharge, pd.Series):
            times = (
                (discharge.index - discharge.index[0]).total_seconds() / 60.0
            ).tolist()
            values = discharge.to_numpy().tolist()
            startdate = discharge.index[0].strftime("%Y-%m-%d %H:%M:%S")
        else:
            times = None
            values = None
            startdate = "0000-00-00 00:00:00"

        self.lateral_nodes[id] = {
            "id": id,
            "type": "discharge",
            "locationtype": "1d",
            "branchid": branchid,
            "chainage": chainage,
            "time": times,
            "time_unit": f"minutes since {startdate}",
            "value_unit": "m3/s",
            "value": values,
            "discharge": discharge,
        }
add_boundary_condition(name: str, pt: tuple[float, float] | Point, quantity: str, value: float | pd.Series | dict[str, list[float]], mesh1d: netmodels.Network | None = None) -> None

Add a boundary condition at the 1D node nearest to a location.

Parameters

name : str Id of the boundary condition. pt : tuple[float, float] or Point Location of the boundary condition. quantity : str "dischargebnd", "waterlevelbnd" or "qhbnd". value : float, pd.Series or dict[str, list[float]] A constant, a time series with a datetime index, or a Q-H table {"Q": [...], "H": [...]}. mesh1d : Network, optional Network with the 1D mesh. Required; the default None raises a ValueError.

Raises

KeyError If a boundary condition with this name exists, or the network has no 1D mesh. ValueError If no network is given.

Source code in hydrolib/dhydamo/core/hydamo.py
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_boundary_condition(
    self,
    name: str,
    pt: tuple[float, float] | Point,
    quantity: str,
    value: float | pd.Series | dict[str, list[float]],
    mesh1d: netmodels.Network | None = None,
) -> None:
    """Add a boundary condition at the 1D node nearest to a location.

    Parameters
    ----------
    name : str
        Id of the boundary condition.
    pt : tuple[float, float] or Point
        Location of the boundary condition.
    quantity : str
        ``"dischargebnd"``, ``"waterlevelbnd"`` or ``"qhbnd"``.
    value : float, pd.Series or dict[str, list[float]]
        A constant, a time series with a datetime index, or a Q-H table
        ``{"Q": [...], "H": [...]}``.
    mesh1d : Network, optional
        Network with the 1D mesh. Required; the default None raises a ValueError.

    Raises
    ------
    KeyError
        If a boundary condition with this name exists, or the network has no 1D mesh.
    ValueError
        If no network is given.
    """
    assert quantity in ["dischargebnd", "waterlevelbnd", "qhbnd"]

    if isinstance(value, pd.Series):
        vec1: list[float] | None = (
            (value.index - value.index[0]).total_seconds() / 60.0
        ).tolist()
        vec2: list[float] | float = value.to_numpy().tolist()
        startdate = value.index[0].strftime("%Y-%m-%d %H:%M:%S")
        unit1 = f"minutes since {startdate}"
        unit2 = "m3/s" if quantity == "dischargebnd" else "m"
    elif isinstance(value, float):
        vec1 = None
        vec2 = float(value)
        startdate = "0000-00-00 00:00:00"
        unit1 = f"minutes since {startdate}"
        unit2 = "m3/s" if quantity == "dischargebnd" else "m"
    else:
        vec1 = value["Q"]
        vec2 = value["H"]
        unit1 = "m3/s"
        unit2 = "m"

    if name in self.boundary_nodes:
        raise KeyError(
            f'A boundary condition with name "{name}" is already present.'
        )

    if isinstance(pt, tuple):
        pt = Point(*pt)

    # Find the nearest node
    if mesh1d is None:
        raise ValueError("Provide the network with the 1d mesh (mesh1d).")
    if len(mesh1d._mesh1d.mesh1d_node_id) == 0:
        raise KeyError(
            "To find the closest node a 1d mesh should be created first."
        )
    nodes1d = np.asarray(
        [
            n
            for n in zip(
                mesh1d._mesh1d.mesh1d_node_x,
                mesh1d._mesh1d.mesh1d_node_y,
                mesh1d._mesh1d.mesh1d_node_id,
            )
        ]
    )
    get_nearest = KDTree(nodes1d[:, 0:2])
    _, idx_nearest = get_nearest.query(pt.coords[:])
    nodeid = f"{float(nodes1d[idx_nearest[0], 0]):12.6f}_{float(nodes1d[idx_nearest[0], 1]):12.6f}"

    # Add boundary condition
    self.boundary_nodes[name] = {
        "id": name,
        "quantity": quantity,
        "vec1": vec1,
        "vec2": vec2,
        "unit1": unit1,
        "unit2": unit2,
        "nodeid": nodeid,
    }
add_lateral(id: str, branchid: str, chainage: str, discharge: Annotated[pd.Series | float | str, Field(union_mode='left_to_right')]) -> None

Add a lateral.

Parameters

id : str Id of the lateral. branchid : str Branch on which the lateral lies. chainage : str Chainage on the branch. discharge : pd.Series, float or str "realtime" when coupled to RR, a constant discharge, or a time series with a datetime index.

Source code in hydrolib/dhydamo/core/hydamo.py
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_lateral(
    self,
    id: str,
    branchid: str,
    chainage: str,
    discharge: Annotated[
        pd.Series | float | str, Field(union_mode="left_to_right")
    ],
) -> None:
    """Add a lateral.

    Parameters
    ----------
    id : str
        Id of the lateral.
    branchid : str
        Branch on which the lateral lies.
    chainage : str
        Chainage on the branch.
    discharge : pd.Series, float or str
        ``"realtime"`` when coupled to RR, a constant discharge, or a time series with
        a datetime index.
    """
    # Convert time to minutes
    if isinstance(discharge, pd.Series):
        times = (
            (discharge.index - discharge.index[0]).total_seconds() / 60.0
        ).tolist()
        values = discharge.to_numpy().tolist()
        startdate = discharge.index[0].strftime("%Y-%m-%d %H:%M:%S")
    else:
        times = None
        values = None
        startdate = "0000-00-00 00:00:00"

    self.lateral_nodes[id] = {
        "id": id,
        "type": "discharge",
        "locationtype": "1d",
        "branchid": branchid,
        "chainage": chainage,
        "time": times,
        "time_unit": f"minutes since {startdate}",
        "value_unit": "m3/s",
        "value": values,
        "discharge": discharge,
    }
add_rain_series(name: str, values: list, times: list) -> None

Add a rain series as a boundary condition.

Parameters

name : str ID of the condition values : list of floats Values of the rain intensity times : list of datetime Times for the values

Source code in hydrolib/dhydamo/core/hydamo.py
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_rain_series(self, name: str, values: list, times: list) -> None:
    """Add a rain series as a boundary condition.

    Parameters
    ----------
    name : str
        ID of the condition
    values : list of floats
        Values of the rain intensity
    times : list of datetime
        Times for the values
    """
    # Add boundary condition
    self.boundary_nodes[name] = {
        "code": name,
        "bctype": "rainfall",
        "filetype": 1,
        "method": 1,
        "operand": "O",
        "value": values,
        "time": times,
        "geometry": None,
        "branchid": None,
    }
add_rainfall_2D(fName, bctype='rainfall')

Add 2D rainfall from a netCDF file (legacy from delft3dfmpy, not working).

Parameters

fName : str Location of netcdf file containing rainfall rasters bctype : str Type of boundary condition. Currently only rainfall is supported

Source code in hydrolib/dhydamo/core/hydamo.py
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
@no_type_check
def add_rainfall_2D(self, fName, bctype="rainfall"):
    """Add 2D rainfall from a netCDF file (legacy from delft3dfmpy, not working).

    Parameters
    ----------
    fName : str
        Location of netcdf file containing rainfall rasters
    bctype : str
        Type of boundary condition. Currently only rainfall is supported
    """
    assert bctype in ["rainfall"]

    # Add boundary condition
    self.boundaries["rainfall_2D"] = {
        "file_name": fName,
        "bctype": bctype + "bnd",
    }
correct_values_from_modelrun(model_values: gpd.GeoDataFrame, correction_polygons: gpd.GeoDataFrame, value_column: str, boundary_step: float | None = 0.01) -> gpd.GeoDataFrame

Replace values from a model result by the values of correction polygons.

All points within the polygons get the value of the polygon.

If the points have the columns 'branchid' and 'chainage' (as from read_values_from_modelrun) and the HyDAMO branches are available, two points are added where a polygon boundary crosses a branch, boundary_step apart: the point inside gets the polygon value, the point outside the model value interpolated along the branch. The value then changes at the polygon boundary instead of gradually between the nearest model points.

Parameters

model_values : gpd.GeoDataFrame Points with a column value, e.g. from read_values_from_modelrun. correction_polygons : gpd.GeoDataFrame Polygons with the corrected values. value_column : str Column in correction_polygons with the corrected values. boundary_step : float, optional Distance between the two points at a polygon boundary; None adds no points. Defaults to 0.01.

Returns

gpd.GeoDataFrame Copy of model_values with corrected values (and the points at the polygon boundaries). Where polygons overlap, the last polygon is used.

Source code in hydrolib/dhydamo/core/hydamo.py
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
def correct_values_from_modelrun(
    self,
    model_values: gpd.GeoDataFrame,
    correction_polygons: gpd.GeoDataFrame,
    value_column: str,
    boundary_step: float | None = 0.01,
) -> gpd.GeoDataFrame:
    """Replace values from a model result by the values of correction polygons.

    All points within the polygons get the value of the polygon.

    If the points have the columns 'branchid' and 'chainage' (as from read_values_from_modelrun) and the HyDAMO
    branches are available, two points are added where a polygon boundary crosses a branch, boundary_step apart:
    the point inside gets the polygon value, the point outside the model value interpolated along the branch.
    The value then changes at the polygon boundary instead of gradually between the nearest model points.

    Parameters
    ----------
    model_values : gpd.GeoDataFrame
        Points with a column ``value``, e.g. from `read_values_from_modelrun`.
    correction_polygons : gpd.GeoDataFrame
        Polygons with the corrected values.
    value_column : str
        Column in ``correction_polygons`` with the corrected values.
    boundary_step : float, optional
        Distance between the two points at a polygon boundary; None adds no points.
        Defaults to 0.01.

    Returns
    -------
    gpd.GeoDataFrame
        Copy of ``model_values`` with corrected values (and the points at the polygon
        boundaries). Where polygons overlap, the last polygon is used.
    """
    model_values_corrected = model_values.copy(deep=True)
    if model_values_corrected.crs is None and correction_polygons.crs is not None:
        model_values_corrected = model_values_corrected.set_crs(
            correction_polygons.crs
        )

    # use a plain GeoDataFrame, an ExtendedGeoDataFrame loses the value column in the spatial join
    joined = gpd.sjoin(
        model_values_corrected[["geometry"]],
        gpd.GeoDataFrame(correction_polygons[[value_column, "geometry"]]),
        how="inner",
        predicate="intersects",
    )
    joined = joined[~joined.index.duplicated(keep="last")]

    model_values_corrected.loc[joined.index, "value"] = joined[value_column]

    branches = getattr(self.hydamo, "branches", None)
    if boundary_step is None or not {"branchid", "chainage"} <= set(
        model_values.columns
    ):
        return model_values_corrected
    if branches is None or branches.empty:
        logger.info(
            "No branches available: no points are added at the boundaries of the correction polygons."
        )
        return model_values_corrected

    boundary_points = self._points_at_polygon_boundaries(
        model_values,
        gpd.GeoDataFrame(
            correction_polygons[[value_column, "geometry"]]
        ).reset_index(drop=True),
        value_column,
        branches,
        boundary_step,
    )
    if boundary_points.empty:
        return model_values_corrected
    logger.info(
        f"{len(boundary_points)} points added at the boundaries of the correction polygons."
    )
    combined = pd.concat(
        [model_values_corrected, boundary_points], ignore_index=True
    )
    return gpd.GeoDataFrame(
        combined, geometry="geometry", crs=model_values_corrected.crs
    )
read_values_from_modelrun(netcdf_path: str | Path, netcdf_field: str, netcdf_index: int | None = None, crs: CRS | str | int | None = None, time: datetime | pd.Timestamp | str | None = None) -> gpd.GeoDataFrame

Read the values of a 1D variable from a model result (map or fou file).

Variables on the 1D nodes (e.g. 'mesh1d_s1', 'mesh1d_waterdepth') are returned at the node locations, variables on the 1D edges/flow links (e.g. 'mesh1d_u1') at the edge locations.

If 'mesh1d_s1' is requested but the file only contains the water depth, the water level is computed as bed level + water depth.

Missing values (dry nodes or links in a map-file) are replaced by the bed level for water levels, and by 0 for water depths, velocities and discharges; for other variables they are left out.

If the file contains the 1D network topology, the columns 'branchid' and 'chainage' are added, so the values can be written per branch with set_spatial_field(..., filetype="branch"). For edge variables, the column 'direction' (angle of the link in radians) is added, as used by set_initial_velocity.

Parameters

netcdf_path : str or Path Path to the netCDF file. netcdf_field : str Variable to read, e.g. "mesh1d_s1" (map) or "mesh1d_fourier001_max" (fou). netcdf_index : int, optional Time index, e.g. 0 for the first time step. Defaults to None: without a time, the last time step. crs : CRS, str or int, optional Coordinate reference system of the model. Defaults to None. time : datetime, pd.Timestamp or str, optional Time for which the values are read, e.g. "2016-06-02 12:00"; the nearest time step is used. Defaults to None.

Returns

gpd.GeoDataFrame Points with the columns x, y and value (and branchid, chainage and direction, if available).

Source code in hydrolib/dhydamo/core/hydamo.py
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
def read_values_from_modelrun(
    self,
    netcdf_path: str | Path,
    netcdf_field: str,
    netcdf_index: int | None = None,
    crs: CRS | str | int | None = None,
    time: datetime | pd.Timestamp | str | None = None,
) -> gpd.GeoDataFrame:
    """Read the values of a 1D variable from a model result (map or fou file).

    Variables on the 1D nodes (e.g. 'mesh1d_s1', 'mesh1d_waterdepth') are returned at the node locations,
    variables on the 1D edges/flow links (e.g. 'mesh1d_u1') at the edge locations.

    If 'mesh1d_s1' is requested but the file only contains the water depth, the water level is computed
    as bed level + water depth.

    Missing values (dry nodes or links in a map-file) are replaced by the bed level for water levels,
    and by 0 for water depths, velocities and discharges; for other variables they are left out.

    If the file contains the 1D network topology, the columns 'branchid' and 'chainage' are added, so the
    values can be written per branch with set_spatial_field(..., filetype="branch"). For edge variables,
    the column 'direction' (angle of the link in radians) is added, as used by set_initial_velocity.

    Parameters
    ----------
    netcdf_path : str or Path
        Path to the netCDF file.
    netcdf_field : str
        Variable to read, e.g. ``"mesh1d_s1"`` (map) or ``"mesh1d_fourier001_max"`` (fou).
    netcdf_index : int, optional
        Time index, e.g. 0 for the first time step. Defaults to None: without a
        time, the last time step.
    crs : CRS, str or int, optional
        Coordinate reference system of the model. Defaults to None.
    time : datetime, pd.Timestamp or str, optional
        Time for which the values are read, e.g. ``"2016-06-02 12:00"``; the nearest
        time step is used. Defaults to None.

    Returns
    -------
    gpd.GeoDataFrame
        Points with the columns x, y and value (and branchid, chainage and
        direction, if available).
    """
    logger.info(f"Reading {netcdf_field} from {netcdf_path} ...")
    with Dataset(netcdf_path, "r") as results:  # Open file in read mode
        variable, from_depth = self._select_netcdf_variable(
            results, netcdf_field, netcdf_path
        )
        netcdf_index = self._resolve_netcdf_index(
            results, variable, netcdf_field, netcdf_path, netcdf_index, time
        )
        masked = np.ma.masked_invalid(
            variable[:] if netcdf_index is None else variable[netcdf_index, :]
        )
        if from_depth:
            # dry nodes (missing depth) get the bed level
            bed_level = np.ma.filled(results["mesh1d_flowelem_bl"][:], np.nan)
            masked = np.ma.masked_invalid(bed_level + np.ma.filled(masked, 0.0))

        # location of the variable: 1D nodes or 1D edges (flow links)
        location = "edge" if variable.dimensions[-1] == "mesh1d_nEdges" else "node"
        x = np.array(results[f"mesh1d_{location}_x"][:])
        y = np.array(results[f"mesh1d_{location}_y"][:])
        if masked.ndim != 1 or len(x) != len(masked):
            raise ValueError(
                f"For {netcdf_field} in {netcdf_path}, length of coordinates and values are not equal."
            )

        topology = self._read_1d_topology(results, location)
        value, missing = self._fill_missing_values(
            masked, results, netcdf_field, location
        )
        if missing.any():
            logger.warning(
                f"{missing.sum()} {location}s without a value in {netcdf_field} are left out."
            )
            x, y, value = x[~missing], y[~missing], value[~missing]
            topology = {key: values[~missing] for key, values in topology.items()}

    return gpd.GeoDataFrame(
        {"x": x, "y": y, "value": value, **topology},
        geometry=gpd.points_from_xy(x, y),
        crs=crs,
    )
set_initial_velocity(velocities: gpd.GeoDataFrame, column: str = 'value') -> None

Set the initial velocity on the 1D flow links from a model result.

E.g. "mesh1d_u1" read with read_values_from_modelrun.

D-Flow FM (2026.02) does not accept 'initialvelocity' in the initial fields file, only the components 'initialvelocityx' and 'initialvelocityy'. The velocity along each link is therefore decomposed with the link direction and written as two sample files (triangulation). Tested with DIMR: on links that are in both models, the initial velocity equals the velocity of the model result within 1 cm/s. The effect of an initial velocity is short: the flow adapts within the first minutes.

Parameters

velocities : gpd.GeoDataFrame Points at the link locations with the velocity and the column direction (angle of the link in radians), as returned by read_values_from_modelrun. column : str, optional Column with the velocity along the link. Defaults to "value".

Source code in hydrolib/dhydamo/core/hydamo.py
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
def set_initial_velocity(
    self, velocities: gpd.GeoDataFrame, column: str = "value"
) -> None:
    """Set the initial velocity on the 1D flow links from a model result.

    E.g. ``"mesh1d_u1"`` read with `read_values_from_modelrun`.

    D-Flow FM (2026.02) does not accept 'initialvelocity' in the initial fields file, only the components
    'initialvelocityx' and 'initialvelocityy'. The velocity along each link is therefore decomposed with
    the link direction and written as two sample files (triangulation). Tested with DIMR: on links that
    are in both models, the initial velocity equals the velocity of the model result within 1 cm/s.
    The effect of an initial velocity is short: the flow adapts within the first minutes.

    Parameters
    ----------
    velocities : gpd.GeoDataFrame
        Points at the link locations with the velocity and the column ``direction``
        (angle of the link in radians), as returned by `read_values_from_modelrun`.
    column : str, optional
        Column with the velocity along the link. Defaults to ``"value"``.
    """
    if "direction" not in velocities.columns:
        raise ValueError(
            "The column 'direction' (angle of the link) is required. Read the velocity with "
            "read_values_from_modelrun from a file with 'mesh1d_edge_nodes'."
        )
    speed = velocities[column].astype(float).to_numpy()
    angle = velocities["direction"].astype(float).to_numpy()
    for component, values in (
        ("x", speed * np.cos(angle)),
        ("y", speed * np.sin(angle)),
    ):
        self.set_spatial_field(
            velocities.assign(_component=values)[["_component", "geometry"]],
            "_component",
            quantity=f"initialvelocity{component}",
            filetype="sample",
            interpolationmethod="triangulation",
        )
set_initial_waterdepth(initial_values: float | gpd.GeoDataFrame, *, locationtype: str = '1d', value_column: str | None = None) -> None

Set the initial water depth: a uniform value, or a value per polygon.

A uniform value for 1D (locationtype '1d') is written per branch for all branches, as a spatial field at the position of this call: fields added after it override it where they apply, fields added before it are overridden. Calling it again replaces the earlier uniform water depth. For 2D or 'all', a uniform value is written as a [Global] value; D-HYDRO 2026.02 then lets it override spatial water levels.

Polygons (1D only) are passed on to set_spatial_field and written per branch. For other spatially varying input, such as a model result, use set_spatial_field directly.

Parameters

initial_values : float or gpd.GeoDataFrame Uniform water depth, or polygons with water depths. locationtype : str, optional "1d", "2d" or "all". Defaults to "1d". value_column : str, optional Column with the water depths, required for polygons. Defaults to None.

Source code in hydrolib/dhydamo/core/hydamo.py
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
def set_initial_waterdepth(
    self,
    initial_values: float | gpd.GeoDataFrame,
    *,
    locationtype: str = "1d",
    value_column: str | None = None,
) -> None:
    """Set the initial water depth: a uniform value, or a value per polygon.

    A uniform value for 1D (locationtype '1d') is written per branch for all branches, as a spatial field at
    the position of this call: fields added after it override it where they apply, fields added before it are
    overridden. Calling it again replaces the earlier uniform water depth. For 2D or 'all', a uniform value is
    written as a [Global] value; D-HYDRO 2026.02 then lets it override spatial water levels.

    Polygons (1D only) are passed on to set_spatial_field and written per branch. For other spatially varying
    input, such as a model result, use set_spatial_field directly.

    Parameters
    ----------
    initial_values : float or gpd.GeoDataFrame
        Uniform water depth, or polygons with water depths.
    locationtype : str, optional
        ``"1d"``, ``"2d"`` or ``"all"``. Defaults to ``"1d"``.
    value_column : str, optional
        Column with the water depths, required for polygons. Defaults to None.
    """
    self._set_initial("waterdepth", initial_values, locationtype, value_column)
set_initial_waterlevel(initial_values: float | gpd.GeoDataFrame, *, locationtype: str = '1d', value_column: str | None = None) -> None

Set the initial water level: a uniform value, or a value per polygon.

A uniform value for 1D (locationtype '1d') is written per branch for all branches, as a spatial field at the position of this call: fields added after it override it where they apply, fields added before it are overridden. Calling it again replaces the earlier uniform water level. For 2D or 'all', a uniform value is written as a [Global] value.

Polygons (1D only) are passed on to set_spatial_field and written per branch. For other spatially varying input, such as a model result, use set_spatial_field directly.

Parameters

initial_values : float or gpd.GeoDataFrame Uniform water level, or polygons with water levels. locationtype : str, optional "1d", "2d" or "all". Defaults to "1d". value_column : str, optional Column with the water levels, required for polygons. Defaults to None.

Source code in hydrolib/dhydamo/core/hydamo.py
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
def set_initial_waterlevel(
    self,
    initial_values: float | gpd.GeoDataFrame,
    *,
    locationtype: str = "1d",
    value_column: str | None = None,
) -> None:
    """Set the initial water level: a uniform value, or a value per polygon.

    A uniform value for 1D (locationtype '1d') is written per branch for all branches, as a spatial field at
    the position of this call: fields added after it override it where they apply, fields added before it are
    overridden. Calling it again replaces the earlier uniform water level. For 2D or 'all', a uniform value is
    written as a [Global] value.

    Polygons (1D only) are passed on to set_spatial_field and written per branch. For other spatially varying
    input, such as a model result, use set_spatial_field directly.

    Parameters
    ----------
    initial_values : float or gpd.GeoDataFrame
        Uniform water level, or polygons with water levels.
    locationtype : str, optional
        ``"1d"``, ``"2d"`` or ``"all"``. Defaults to ``"1d"``.
    value_column : str, optional
        Column with the water levels, required for polygons. Defaults to None.
    """
    self._set_initial("waterlevel", initial_values, locationtype, value_column)
set_missing_waterlevel(missing)

Set the missing value for the water level (legacy from delft3dfmpy, not working).

This overwrites the water level at missing value in the mdu file.

Parameters

missing : float Water depth

Source code in hydrolib/dhydamo/core/hydamo.py
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
@no_type_check
def set_missing_waterlevel(self, missing):
    """Set the missing value for the water level (legacy from delft3dfmpy, not working).

    This overwrites the water level at missing value in the mdu file.

    Parameters
    ----------
    missing : float
        Water depth
    """
    self.mdu_parameters["WaterLevIni"] = missing
set_spatial_field(gdf: gpd.GeoDataFrame | Path | str, column: str | None = None, quantity: str = 'waterlevel', kind: str = 'initial', filetype: str | None = None, cellsize: float | None = None, locationtype: str = '1d', interpolationmethod: str | None = None, averagingtype: str = 'nearestNb', operand: str = 'O', nodata: float = -999.0, max_snap_distance: float = 5.0, averagingrelsize: float | None = None, averagingnummin: int | None = None, averagingpercentile: float | None = None, extrapolationmethod: bool | None = None) -> None

Add a spatially varying field to the initial fields file (initialFields.ini).

By default, values are written per branch and chainage in a 1dField file (filetype 'branch'), for polygons and points. D-Flow FM interpolates them linearly along each branch only, and keeps them constant beyond the first and last chainage of a branch. For polygons, each part of a branch inside a polygon gets the polygon value, with a step at the polygon boundary. For points, the columns 'branchid' and 'chainage' are used if present (e.g. from read_values_from_modelrun); otherwise points are snapped to the nearest branch within max_snap_distance. In DIMR tests (D-HYDRO 2026.02) this gave the most reliable result for polygons, for model results on the same network and on a changed 1D grid, and for combining water level and water depth.

Advanced: the other file types are kept for special cases (e.g. 2D, or if a future D-Flow FM version does not accept 1dField files), but are not recommended for 1D:

  • 'sample': points as samples (.xyz) with triangulation, which fills the convex hull of the points, so values spread to other branches.
  • 'polygon': .pol files with interpolationMethod=constant, one file and block per distinct value.
  • 'raster': polygons rasterized to a GeoTIFF (.tif) or ArcInfo grid (.asc), requires a cellsize. D-Flow FM (2026.02) uses the nodata value as data.

Tested with D-HYDRO 2026.02 on 1D nodes: interpolationMethod=averaging assigns no values, so it is refused for locationtype '1d'; triangulation fills the convex hull of the samples; nodes that get no value from any field keep the default water level (WaterLevIni in the MDU), which leaves them dry when it is below the bed level, so cover all nodes. Fields are applied in the order they are added (the last one wins). A uniform 1D value from set_initial_waterlevel/-depth is a field per branch over all branches, at the position of that call, so use it first as a background. A water depth from polygons or samples removes earlier water levels from polygons or samples everywhere, also outside its own area; water levels per branch are kept. Add water depth fields before water level fields.

For samples and rasters on 2D cells, choose the interpolation by the density of the data: 'averaging' for dense data (several values per cell, e.g. a point cloud or a fine raster), 'triangulation' for sparse data (fewer values than cells, e.g. measured points). Averaging combines the values inside each cell, as set by averagingtype and the averaging settings below; triangulation interpolates linearly between the values, and only within their convex hull unless extrapolationmethod is True. Settings left at None are not written, so D-Flow FM uses its defaults.

The data files are written by Df2HydrolibModel.write_initial_fields().

Parameters

gdf : gpd.GeoDataFrame or Path or str Polygons or points with values, or the path to an existing .xyz file (x, y and value per line). An .xyz file becomes a sample field (filetype "sample", no column) and is copied unchanged under the generated name when the model is written. For initial water levels and depths, only with locationtype "2d": D-HyDAMO does not read its values, so it cannot check them against other water level and depth fields on the 1D nodes. column : str, optional Column with the values. For points, None means the Z coordinate is used. quantity : str, optional D-Flow FM quantity, e.g. "waterlevel" or "waterdepth". For velocities, use set_initial_velocity. Defaults to "waterlevel". kind : str, optional "initial" ([Initial] block) or "parameter" ([Parameter] block). Defaults to "initial". filetype : str, optional "branch" (default), or the advanced types "sample", "polygon" or "raster". cellsize : float, optional Raster cell size, required for filetype "raster". locationtype : str, optional "1d", "2d" or "all". Defaults to "1d". interpolationmethod : str, optional "constant" (polygon), "triangulation" or "averaging". Not used for "branch". Defaults to "triangulation" for samples, "constant" for polygon files, and "averaging" for rasters (2D) or "triangulation" (1D). averagingtype : str, optional Averaging type, if interpolationmethod is "averaging". Defaults to "nearestNb". operand : str, optional How the field is combined with previous fields. Defaults to "O" (override). nodata : float, optional Nodata value for rasters, and the [Global] value of 1dField files (branch), which D-Flow FM treats as no value. Defaults to -999.0. max_snap_distance : float, optional Maximum distance to snap points to a branch for filetype "branch". Defaults to 5.0. averagingrelsize : float, optional With "averaging", the size of the area around a cell that is searched for values, relative to the cell size (D-Flow FM default 1.01). Larger values smooth more, and fill cells with few values. Defaults to None (not written). averagingnummin : int, optional With "averaging", the minimum number of values in that area; a cell with fewer gets no value from this field (D-Flow FM default 1). Defaults to None (not written). averagingpercentile : float, optional With "averaging", the percentile of the values to use instead of all values, e.g. a low percentile for the lowest part of a cell (D-Flow FM default 0, off). Defaults to None (not written). extrapolationmethod : bool, optional With "triangulation", True also gives values outside the convex hull of the data. Defaults to None: not set, which hydrolib-core writes as extrapolationMethod = 0.

Source code in hydrolib/dhydamo/core/hydamo.py
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
def set_spatial_field(
    self,
    gdf: gpd.GeoDataFrame | Path | str,
    column: str | None = None,
    quantity: str = "waterlevel",
    kind: str = "initial",
    filetype: str | None = None,
    cellsize: float | None = None,
    locationtype: str = "1d",
    interpolationmethod: str | None = None,
    averagingtype: str = "nearestNb",
    operand: str = "O",
    nodata: float = -999.0,
    max_snap_distance: float = 5.0,
    averagingrelsize: float | None = None,
    averagingnummin: int | None = None,
    averagingpercentile: float | None = None,
    extrapolationmethod: bool | None = None,
) -> None:
    """Add a spatially varying field to the initial fields file (initialFields.ini).

    By default, values are written per branch and chainage in a 1dField file (filetype 'branch'), for
    polygons and points. D-Flow FM interpolates them linearly along each branch only, and keeps them
    constant beyond the first and last chainage of a branch. For polygons, each part of a branch inside a
    polygon gets the polygon value, with a step at the polygon boundary. For points, the columns 'branchid'
    and 'chainage' are used if present (e.g. from read_values_from_modelrun); otherwise points are snapped to
    the nearest branch within max_snap_distance. In DIMR tests (D-HYDRO 2026.02) this gave the most reliable
    result for polygons, for model results on the same network and on a changed 1D grid, and for combining
    water level and water depth.

    Advanced: the other file types are kept for special cases (e.g. 2D, or if a future D-Flow FM version
    does not accept 1dField files), but are not recommended for 1D:

    - 'sample': points as samples (.xyz) with triangulation, which fills the convex hull of the points, so
      values spread to other branches.
    - 'polygon': .pol files with interpolationMethod=constant, one file and block per distinct value.
    - 'raster': polygons rasterized to a GeoTIFF (.tif) or ArcInfo grid (.asc), requires a cellsize. D-Flow FM
      (2026.02) uses the nodata value as data.

    Tested with D-HYDRO 2026.02 on 1D nodes: interpolationMethod=averaging assigns no values, so it is
    refused for locationtype '1d'; triangulation fills the convex hull of the samples; nodes that get no
    value from any field keep the default water level (WaterLevIni in the MDU), which leaves them dry when it
    is below the bed level, so cover all nodes. Fields are applied in the order they are added (the last
    one wins). A uniform 1D value from set_initial_waterlevel/-depth is a field per branch over all branches, at
    the position of that call, so use it first as a background. A water depth from polygons or samples removes earlier water levels from polygons
    or samples everywhere, also outside its own area; water levels per branch are kept. Add water depth
    fields before water level fields.

    For samples and rasters on 2D cells, choose the interpolation by the density of the data: 'averaging' for
    dense data (several values per cell, e.g. a point cloud or a fine raster), 'triangulation' for sparse data
    (fewer values than cells, e.g. measured points). Averaging combines the values inside each cell, as set by
    averagingtype and the averaging settings below; triangulation interpolates linearly between the values, and
    only within their convex hull unless extrapolationmethod is True. Settings left at None are not written, so
    D-Flow FM uses its defaults.

    The data files are written by Df2HydrolibModel.write_initial_fields().

    Parameters
    ----------
    gdf : gpd.GeoDataFrame or Path or str
        Polygons or points with values, or the path to an existing .xyz file (x, y
        and value per line). An .xyz file becomes a sample field (filetype
        ``"sample"``, no column) and is copied unchanged under the generated name
        when the model is written. For initial water levels and depths, only with
        locationtype ``"2d"``: D-HyDAMO does not read its values, so it cannot check
        them against other water level and depth fields on the 1D nodes.
    column : str, optional
        Column with the values. For points, None means the Z coordinate is used.
    quantity : str, optional
        D-Flow FM quantity, e.g. ``"waterlevel"`` or ``"waterdepth"``. For velocities,
        use `set_initial_velocity`. Defaults to ``"waterlevel"``.
    kind : str, optional
        ``"initial"`` ([Initial] block) or ``"parameter"`` ([Parameter] block).
        Defaults to ``"initial"``.
    filetype : str, optional
        ``"branch"`` (default), or the advanced types ``"sample"``, ``"polygon"`` or
        ``"raster"``.
    cellsize : float, optional
        Raster cell size, required for filetype ``"raster"``.
    locationtype : str, optional
        ``"1d"``, ``"2d"`` or ``"all"``. Defaults to ``"1d"``.
    interpolationmethod : str, optional
        ``"constant"`` (polygon), ``"triangulation"`` or ``"averaging"``. Not used for
        ``"branch"``. Defaults to ``"triangulation"`` for samples, ``"constant"`` for
        polygon files, and ``"averaging"`` for rasters (2D) or ``"triangulation"`` (1D).
    averagingtype : str, optional
        Averaging type, if interpolationmethod is ``"averaging"``. Defaults to
        ``"nearestNb"``.
    operand : str, optional
        How the field is combined with previous fields. Defaults to ``"O"`` (override).
    nodata : float, optional
        Nodata value for rasters, and the [Global] value of 1dField files (branch),
        which D-Flow FM treats as no value. Defaults to -999.0.
    max_snap_distance : float, optional
        Maximum distance to snap points to a branch for filetype ``"branch"``. Defaults
        to 5.0.
    averagingrelsize : float, optional
        With ``"averaging"``, the size of the area around a cell that is searched for
        values, relative to the cell size (D-Flow FM default 1.01). Larger values
        smooth more, and fill cells with few values. Defaults to None (not written).
    averagingnummin : int, optional
        With ``"averaging"``, the minimum number of values in that area; a cell with
        fewer gets no value from this field (D-Flow FM default 1). Defaults to None
        (not written).
    averagingpercentile : float, optional
        With ``"averaging"``, the percentile of the values to use instead of all
        values, e.g. a low percentile for the lowest part of a cell (D-Flow FM
        default 0, off). Defaults to None (not written).
    extrapolationmethod : bool, optional
        With ``"triangulation"``, True also gives values outside the convex hull of
        the data. Defaults to None: not set, which hydrolib-core writes as
        ``extrapolationMethod = 0``.
    """
    if kind not in ("initial", "parameter"):
        raise ValueError(f"kind should be 'initial' or 'parameter', not '{kind}'.")
    if quantity.lower() == "initialvelocity":
        raise ValueError(
            "D-Flow FM (2026.02) does not support 'initialvelocity' in the initial fields file. "
            "Use set_initial_velocity, which writes the x and y components."
        )

    xyz_file: Path | None = None
    field_gdf: gpd.GeoDataFrame | None = None
    if isinstance(gdf, (str, Path)):
        if column is not None:
            raise ValueError(
                "An .xyz file has its values in the third column; do not pass a column."
            )
        if filetype not in {None, "sample"}:
            raise ValueError(
                f"An .xyz file is a sample field, not filetype '{filetype}'."
            )
        if level_or_depth(quantity) is not None and locationtype != "2d":
            raise ValueError(
                "An .xyz file for an initial water level or depth is only supported for locationtype '2d'. "
                "D-HyDAMO does not read the file, so on 1D nodes it cannot check the field against other water "
                "level and depth fields or export it with initial_conditions_at_nodes. Read the points into a "
                "GeoDataFrame and pass that instead (filetype 'branch' is the default for 1D)."
            )
        xyz_file = self._xyz_file(gdf)
        filetype = "sample"
    else:
        if gdf.empty:
            raise ValueError("The provided GeoDataFrame is empty.")
        geomtypes = set(gdf.geom_type)
        filetype = self._resolve_filetype(geomtypes, filetype)
        if filetype == "branch" and locationtype != "1d":
            raise ValueError(
                "Filetype 'branch' is only available for locationtype '1d'."
            )
        if filetype == "raster" and cellsize is None:
            raise ValueError("A cellsize is required to rasterize polygons.")
        self._warn_spatial_field_options(gdf, filetype, locationtype)
        gdf, column = self._value_column(gdf, column, geomtypes)
        columns = [column, "geometry"]
        if filetype == "branch" and {"branchid", "chainage"} <= set(gdf.columns):
            columns = ["branchid", "chainage"] + columns
        field_gdf = gpd.GeoDataFrame(gdf[columns].copy())

    interpolationmethod = self._resolve_interpolation(
        filetype, locationtype, interpolationmethod
    )
    sample_settings = {
        "averagingrelsize": averagingrelsize,
        "averagingnummin": averagingnummin,
        "averagingpercentile": averagingpercentile,
        "extrapolationmethod": extrapolationmethod,
    }
    self._warn_sample_settings(interpolationmethod, sample_settings)
    filename = self._next_field_filename(kind, quantity, filetype)

    self.spatial_fields.append(
        {
            "gdf": field_gdf,
            "xyz_file": xyz_file,
            "column": column,
            "quantity": quantity,
            "kind": kind,
            "filetype": filetype,
            "cellsize": cellsize,
            "filename": filename,
            "locationtype": locationtype,
            "interpolationmethod": interpolationmethod,
            "averagingtype": averagingtype,
            "operand": operand,
            "nodata": nodata,
            "max_snap_distance": max_snap_distance,
            "sample_settings": sample_settings,
        }
    )

HyDAMO

The HyDAMO input data and the model objects derived from it.

Holds the DAMO tables (branches, structures, profiles, management, catchments, ...) and the cross sections, structures, observation points, storage nodes and external forcings of the model.

Source code in hydrolib/dhydamo/core/hydamo.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
class HyDAMO:
    """The HyDAMO input data and the model objects derived from it.

    Holds the DAMO tables (branches, structures, profiles, management, catchments, ...)
    and the cross sections, structures, observation points, storage nodes and external
    forcings of the model.
    """

    # The tables of the data model (core.data_model), created in __init__.
    # Only their types are declared here, for type checking.
    branches: ExtendedGeoDataFrame
    profile: ExtendedGeoDataFrame
    profile_roughness: ExtendedDataFrame
    profile_line: ExtendedGeoDataFrame
    profile_group: ExtendedDataFrame
    param_profile: ExtendedDataFrame
    param_profile_values: ExtendedDataFrame
    weirs: ExtendedGeoDataFrame
    opening: ExtendedDataFrame
    management_device: ExtendedDataFrame
    bridges: ExtendedGeoDataFrame
    culverts: ExtendedGeoDataFrame
    pumpstations: ExtendedGeoDataFrame
    pumps: ExtendedDataFrame
    management: ExtendedDataFrame
    boundary_conditions: ExtendedGeoDataFrame
    catchments: ExtendedGeoDataFrame
    laterals: ExtendedGeoDataFrame
    overflows: ExtendedGeoDataFrame
    sewer_areas: ExtendedGeoDataFrame
    greenhouse_areas: ExtendedGeoDataFrame
    greenhouse_laterals: ExtendedGeoDataFrame
    storage_areas: ExtendedGeoDataFrame

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def __init__(self, extent_file: Path | str | None = None) -> None:
        """Create an empty HyDAMO object.

        Parameters
        ----------
        extent_file : Path or str, optional
            Model extent, used to clip the data. Defaults to None.
        """
        self.network = Network(self)

        self.structures = Structures(self)

        self.crosssections = CrossSections(self)  # Add all items

        self.observationpoints = ObservationPoints(self)

        self.external_forcings = ExternalForcings(self)

        self.storagenodes = StorageNodes(self)

        self.roughness_mapping = {
            "Chezy": "Chezy",
            "Manning": "Manning",
            "StricklerKn": "StricklerNikuradse",
            "StricklerKs": "Strickler",
            "White Colebrook": "WhiteColebrook",
            "Bos en Bijkerk": "deBosBijkerk",
            "Onbekend": "Strickler",
            "Overig": "Strickler",
        }

        # Dictionary for roughness definitions
        self.roughness_definitions: dict[str, dict] = {}

        # Read geometry to clip data
        self.clipgeo: BaseGeometry | None
        if extent_file is not None:
            self.clipgeo = gpd.read_file(extent_file).union_all()
        else:
            self.clipgeo = None

        # versioning info
        self.version = {
            "number": dhydamo.__version__,
            "date": datetime.strftime(datetime.now(UTC), "%Y-%m-%dT%H:%M:%S.%fZ"),
            "dimr_version": "Deltares, DIMR_EXE Version 2.00.00.140737 (Win64) (Win64)",
            "suite_version": "D-HYDRO Suite 2024.03 1D2D,",
        }
        # the DAMO version the data was loaded as; None until load_from_gpkg
        self.source_damo_version: str | None = None
        self.validation_result: HydamoValidationResult | None = None

        # The DAMO tables and HYDROLIB's own tables, from the data model
        for name, table in TABLES.items():
            setattr(self, name, _new_table(table.geotype, table.required_names))
        for name, own_table in OWN_TABLES.items():
            setattr(
                self, name, _new_table(own_table.geotype, own_table.required_columns)
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def validate_gpkg(
        self,
        gpkg_path: Path | str,
        hydamo_version: str,
        validation_coverages: dict | None = None,
        validation_rules_path: Path | str | None = None,
    ) -> HydamoValidationResult:
        """Validate a GeoPackage without loading its layers.

        Requires Python 3.12 and the optional dependency installed with
        ``pip install "hydrolib[validation]"``.

        Parameters
        ----------
        gpkg_path : str or Path
            Path to the GeoPackage file.
        hydamo_version : str
            DAMO version to validate against, e.g. ``"2.6"``. Required: it selects
            the version; it does not detect the source version. Any version that the
            installed validatiemodule has a schema for is accepted, which can include
            versions that ``load_from_gpkg`` cannot load yet (see
            ``SUPPORTED_HYDAMO_VERSIONS``). For such a version no column counts as
            read by HYDROLIB, so every finding goes into the INFO line.
        validation_coverages : dict, optional
            Coverage dict forwarded to the validator.
        validation_rules_path : str or Path, optional
            Path to a validation-rules JSON file for the requested DAMO version.
            If omitted, generated rules check ID presence on recognized layers
            with an ID column. Supply custom rules for more comprehensive checks.

        Returns
        -------
        HydamoValidationResult
            Also stored as ``self.validation_result``. Inspect ``success``,
            ``status``, ``errors`` and ``syntax_findings`` to handle validation
            failures. Findings in columns HYDROLIB reads are logged as one
            warning per layer by the ``hydrolib.dhydamo.validation`` logger, the
            number of other findings as one INFO line. A reported failure is
            returned rather than raised as ``HyDAMOValidationError``. The
            validatiemodule's own diagnostics are logged by the
            ``hydamo_validation.validator`` logger.

        Raises
        ------
        ImportError
            If the optional validation dependency is unavailable.
        ValueError
            If generated rules are requested for a version unsupported by the
            installed validator's schemas.
        """
        # Without version steps to the version, no column counts as read.
        try:
            read_columns = self._read_columns(source_layers(hydamo_version))
        except ValueError:
            read_columns = {}
        result = validate_or_raise(
            gpkg_path=gpkg_path,
            hydamo_version=hydamo_version,
            validation_mode="warn",
            coverages=validation_coverages,
            validation_rules_path=validation_rules_path,
            read_columns=read_columns,
        )
        assert result is not None
        self.validation_result = result
        return result

    def _read_columns(self, sources: dict[str, SourceLayer]) -> dict[str, set[str]]:
        """Return, per lowercase DAMO layer, the columns HYDROLIB reads.

        The columns are the table's required columns, ``globalid`` and, for a
        spatial table, ``geometry``, under their names in the DAMO version of
        *sources* (from ``source_layers``).
        """
        read_columns: dict[str, set[str]] = {}
        for name, source in sources.items():
            table = getattr(self, name)
            columns = {*table.required_columns, "globalid"}
            if isinstance(table, ExtendedGeoDataFrame):
                columns.add("geometry")
            file_names = {new: old for old, new in source.renames.items()}
            read_columns[source.layer.lower()] = {
                file_names.get(column, column) for column in columns
            }
        return read_columns

    def load_from_gpkg(
        self,
        gpkg_path: Path | str,
        hydamo_version: str,
        clip_layers: dict | None = None,
        check_3d: bool = True,
        validation_mode: ValidationMode = "off",
        validation_coverages: dict | None = None,
        validation_rules_path: Path | str | None = None,
    ) -> HyDAMO:
        """Load HyDAMO data from a GeoPackage of a supported DAMO version.

        Parameters
        ----------
        gpkg_path : str or Path
            Path to the GeoPackage file.
        hydamo_version : str
            DAMO schema version, one of ``SUPPORTED_HYDAMO_VERSIONS`` (2.2 to 2.6),
            e.g. ``"2.6"``. Required: it selects the renames back to DAMO 2.2, the
            names HYDROLIB uses; it does not detect or verify the source schema
            version.
        clip_layers : dict, optional
            Per-table spatial clip. Maps a HyDAMO table name to a
            ``(geometry, cliptype)`` tuple, e.g.
            ``{"branches": (gpd.read_file(extent).union_all(), "clip")}``.
            Layers absent from the dict are loaded without clipping.
        check_3d : bool
            Whether to require Z coordinates on profile points when grouping
            them into lines. Other layers are not checked for Z coordinates.
            Pass ``False`` to allow 2D profile points. Default is ``True``.
        validation_mode : str
            ``"off"`` skips validation (default). Both other modes act on the
            values the syntax check rejected in columns HYDROLIB reads (its
            required columns, ``globalid`` and, for spatial tables, the
            geometry): ``"warn"`` logs them as one warning per layer, by the
            ``hydrolib.dhydamo.validation`` logger, and continues; ``"strict"``
            raises ``HyDAMOValidationError`` before loading layers, as it does
            when the validation run fails. Rejected values in other columns
            only give one INFO line with their number. Inspect
            ``validation_result.syntax_findings`` for all of them. Validation
            setup errors can raise in either enabled mode.
        validation_coverages : dict, optional
            Coverage dict forwarded to the validator.
        validation_rules_path : str or Path, optional
            Path to a custom validation-rules JSON file for the source DAMO
            version. If omitted, generated rules check ID presence on recognized
            layers with an ID column. Strict mode changes failure handling,
            not the rules or their coverage.

        Returns
        -------
        HyDAMO
            This instance, to allow method chaining.

        Raises
        ------
        HyDAMOValidationError
            In ``"strict"`` mode, if the validation run fails or rejected values
            in a column HYDROLIB reads.
        ImportError
            If validation is enabled and its optional dependency is unavailable.
        KeyError
            If a loaded layer lacks a required column, such as the ``code`` of a
            table whose code is its identity; the message names the layer.
        ValueError
            If the DAMO version is unsupported, or generated validation
            rules require a version unsupported by the installed validator. Also
            if the identity (``code``) or the column that groups points into
            lines (``profiellijnid``) is empty in some rows, also when it is only
            whitespace; the message names the layer and the rows by ``globalid``.

        Notes
        -----
        A load replaces every DAMO table, also those whose layer the GeoPackage
        lacks: nothing of an earlier load is left in them. HYDROLIB's own tables
        (sewer areas, overflows, greenhouses, storage areas) are kept, and so are
        model objects built from an earlier load, such as structures and cross
        sections. For a new model, use a new ``HyDAMO``.

        Validation requires Python 3.12 and ``pip install "hydrolib[validation]"``.
        After enabled validation returns normally, ``self.validation_result``
        contains ``success``, ``status``, ``errors`` and ``syntax_findings``
        (per layer, column and error code). It is ``None`` when
        validation is off. Use ``validate_gpkg()`` to inspect validation failures
        without loading data. Comprehensive schema, type, and relation checks
        require appropriate custom rules; selecting a DAMO version or using strict
        mode alone does not establish that the input is valid DAMO data.

        Examples
        --------
        Given a rules file for DAMO 2.2, load and inspect reported failures:

        >>> hydamo = HyDAMO().load_from_gpkg(
        ...     "model.gpkg",
        ...     hydamo_version="2.2",
        ...     validation_mode="warn",
        ...     validation_rules_path="validationrules.json",
        ... )
        >>> result = hydamo.validation_result
        >>> print(result.success, result.status, result.errors)

        Use ``validation_mode="strict"`` to raise ``HyDAMOValidationError``
        instead of loading after a reported validation failure.
        """
        # Resolve the layers first so an unsupported version fails before validation runs.
        sources = source_layers(hydamo_version)

        self.validation_result = None
        self.source_damo_version = hydamo_version
        self.validation_result = validate_or_raise(
            gpkg_path=gpkg_path,
            hydamo_version=hydamo_version,
            validation_mode=validation_mode,
            coverages=validation_coverages,
            validation_rules_path=validation_rules_path,
            read_columns=(
                self._read_columns(sources) if validation_mode != "off" else None
            ),
        )

        self._reset_damo_tables()
        load_layers(
            self,
            gpkg_path,
            sources,
            hydamo_version,
            clip_layers=clip_layers,
            check_3d=check_3d,
        )
        return self

    def _reset_damo_tables(self) -> None:
        """Empty every DAMO table in place, as it is after ``HyDAMO()``.

        In place, so references to the tables stay valid. HYDROLIB's own tables
        (``OWN_TABLES``) are left alone: they are filled from their own files.
        """
        for name, definition in TABLES.items():
            table = getattr(self, name)
            fresh = _new_table(definition.geotype, definition.required_names)
            # inplace: the tables are replaced in place, so references stay valid
            table.drop(index=table.index, inplace=True)  # noqa: PD002
            table.drop(columns=list(table.columns), inplace=True)  # noqa: PD002
            table.index = fresh.index
            for column in fresh.columns:
                table[column] = fresh[column]

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def list_to_str(self, lst: list | np.ndarray) -> str:
        """Return numbers as a space separated string, with 3 decimals.

        Parameters
        ----------
        lst : list or np.ndarray
            Numbers.

        Returns
        -------
        str
            The numbers, or ``str(lst)`` for a single number.
        """
        if len(lst) == 1:
            string = str(lst)
        else:
            string = " ".join([f"{number:6.3f}" for number in lst])
        return string

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def dict_to_dataframe(self, dictionary: dict) -> pd.DataFrame:
        """Return a dictionary of dictionaries as a DataFrame, with the keys as rows.

        Parameters
        ----------
        dictionary : dict
            Input dictionary.

        Returns
        -------
        pd.DataFrame
            Output DataFrame.
        """
        return pd.DataFrame.from_dict(dictionary, orient="index")

    def snap_to_branch_and_drop(
        self,
        extendedgdf: ExtendedGeoDataFrame,
        branches: ExtendedGeoDataFrame,
        snap_method: str,
        maxdist: float = 5,
        drop_related: bool = True,
        source_table: str | None = None,
    ) -> None:
        """Snap geometries to branches and drop loose objects and cascades.

        Parameters
        ----------
        extendedgdf : ExtendedGeoDataFrame
            HyDAMO dataframe to snap and potentially prune.
        branches : ExtendedGeoDataFrame
            Branch geometries used for snapping.
        snap_method : str
            Method passed to :meth:`ExtendedGeoDataFrame.snap_to_branch`.
        maxdist : float, default=5
            Maximum snapping distance passed to ``snap_to_branch``.
        drop_related : bool, default=True
            Whether to drop rows reached through the configured cascade paths.
        source_table : str, optional
            Canonical HyDAMO table name.  If omitted, the name is determined
            from the dataframe object stored on this ``HyDAMO`` instance.
            Supply this when ``extendedgdf`` is a dataframe copy; the named
            table must still exist as an attribute on this instance.
        """
        # Snap the extended geodataframe to branches
        extendedgdf.snap_to_branch(branches, snap_method, maxdist=maxdist)

        # Determine which labels need to be drop for the first object based on
        # nan values for branch_offset.
        drop_idx = extendedgdf.index[pd.isna(extendedgdf.branch_offset)]
        logger.info("dropping objects with indices: %s", drop_idx)

        # Build the complete plan before mutating any dataframe.  This keeps
        # all relation traversals independent from the drops performed below.
        drop_plan: dict[str, pd.Index] = {}
        if drop_related:
            if source_table is None:
                for table_name, table in vars(self).items():
                    if table is extendedgdf:
                        source_table = table_name
                        break
            if source_table is None:
                raise ValueError(
                    "Could not determine the HyDAMO source table for the dataframe; pass source_table explicitly"
                )
            drop_plan = build_cascade_plan(self, source_table, drop_idx)

        # Drop the source and all related rows only after the plan is complete.
        # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
        extendedgdf.drop(labels=drop_idx, inplace=True)  # noqa: PD002
        for target_table, target_index in drop_plan.items():
            logger.info(
                "  - dropping objects from '%s' with indices: %s",
                target_table,
                target_index,
            )
            getattr(self, target_table).drop(labels=target_index, inplace=True)  # noqa: PD002

    def create_laterals(
        self,
        qspec_file: str | Path | None = None,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Create laterals at the catchments, with the mean specific discharge per catchment.

        Parameters
        ----------
        qspec_file : str, optional
            Raster of specific discharge (mm/d). Without it, the discharges are NaN.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a catchment must cover for the pixel to count in
            the zonal statistics. Defaults to 0: every touched pixel.
        coverage_weight : str, optional
            ``"fraction"`` counts pixels by the fraction of them the catchment covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.
        """
        ## Afvoer per gebied bepalen met zonal stats; nodata telt niet mee
        if qspec_file is not None:
            afvoer_per_gebied = zonal.zonal_stats(
                gpd.GeoDataFrame(self.catchments),
                qspec_file,
                statistics=("mean",),
                strategy="feature-sequential",
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
            )

        self.laterals = self.catchments.copy()

        catchment_columns = zip(
            self.catchments.index,
            self.catchments.geometry,
            self.catchments["code"],
            self.catchments["lateraleknoopid"],
        )
        for num, (index, geometry, code, knoopid) in enumerate(catchment_columns):
            ## Koppelen van afvoeren met afwateringsgebieden
            if qspec_file is not None:
                q = afvoer_per_gebied.iloc[num]["mean"]  # mm/d
            else:
                q = np.nan

            area = geometry.area  # m2
            q_m3s = q * area / (1000 * 86400)  # van mm/d naar m3/s
            self.laterals.loc[index, "afvoer"] = q_m3s

            ## Afstand tussen watergang en afwateringsgebied. Als watergang in afwateringsgebied ligt is deze afstand 0.
            distances = self.branches.distance(geometry)
            ## Eén of meer watergangen in afwateringsgebied:
            if sum(distances == 0) > 0:
                ## Watergangen intersecten met afwateringsgebied
                # wg = [watergang for watergang in watergangen.itertuples() if watergang.intersects(geometry]
                selectie = self.branches.intersection(geometry)
                ## Index van de watergang waarop je wilt snappen. Dit is de watergang die in het gebied ligt én het dichtst bij de centroid van het afwateringsgebied is.
                index_watergang = selectie.distance(geometry.centroid).idxmin()
                ## Combineer de ge intersecte watergangen met de index om het stuk watergang te vinden waarop mag worden gesnapt.
                watergang = selectie.loc[index_watergang]
            ## No intersects
            else:
                ## Vind de watergang die het dichtst bij de centroid van het gebied is
                index_watergang = self.branches.distance(geometry.centroid).idxmin()
                ## Selecteer deze watergang om op te mogen snappen
                watergang = self.branches.geometry.loc[index_watergang]

            ## Snap de centroid van het afwateringsgebied op de geselecteerde watergang
            lateral = watergang.interpolate(watergang.project(geometry.centroid))
            ## Schrijf de snap-locatie weg in de geodataframe
            # pandas-stubs does not accept a shapely geometry as value; pandas does
            self.laterals.loc[index, "geometry"] = lateral  # type: ignore[call-overload]
            self.laterals.loc[index, "globalid"] = knoopid
            self.laterals.loc[index, "code"] = f"lat_{code}"

        # Indexed by code, like loaded laterals
        self.laterals.index = pd.Index(self.laterals["code"], name="code")
__init__(extent_file: Path | str | None = None) -> None

Create an empty HyDAMO object.

Parameters

extent_file : Path or str, optional Model extent, used to clip the data. Defaults to None.

Source code in hydrolib/dhydamo/core/hydamo.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def __init__(self, extent_file: Path | str | None = None) -> None:
    """Create an empty HyDAMO object.

    Parameters
    ----------
    extent_file : Path or str, optional
        Model extent, used to clip the data. Defaults to None.
    """
    self.network = Network(self)

    self.structures = Structures(self)

    self.crosssections = CrossSections(self)  # Add all items

    self.observationpoints = ObservationPoints(self)

    self.external_forcings = ExternalForcings(self)

    self.storagenodes = StorageNodes(self)

    self.roughness_mapping = {
        "Chezy": "Chezy",
        "Manning": "Manning",
        "StricklerKn": "StricklerNikuradse",
        "StricklerKs": "Strickler",
        "White Colebrook": "WhiteColebrook",
        "Bos en Bijkerk": "deBosBijkerk",
        "Onbekend": "Strickler",
        "Overig": "Strickler",
    }

    # Dictionary for roughness definitions
    self.roughness_definitions: dict[str, dict] = {}

    # Read geometry to clip data
    self.clipgeo: BaseGeometry | None
    if extent_file is not None:
        self.clipgeo = gpd.read_file(extent_file).union_all()
    else:
        self.clipgeo = None

    # versioning info
    self.version = {
        "number": dhydamo.__version__,
        "date": datetime.strftime(datetime.now(UTC), "%Y-%m-%dT%H:%M:%S.%fZ"),
        "dimr_version": "Deltares, DIMR_EXE Version 2.00.00.140737 (Win64) (Win64)",
        "suite_version": "D-HYDRO Suite 2024.03 1D2D,",
    }
    # the DAMO version the data was loaded as; None until load_from_gpkg
    self.source_damo_version: str | None = None
    self.validation_result: HydamoValidationResult | None = None

    # The DAMO tables and HYDROLIB's own tables, from the data model
    for name, table in TABLES.items():
        setattr(self, name, _new_table(table.geotype, table.required_names))
    for name, own_table in OWN_TABLES.items():
        setattr(
            self, name, _new_table(own_table.geotype, own_table.required_columns)
        )
create_laterals(qspec_file: str | Path | None = None, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Create laterals at the catchments, with the mean specific discharge per catchment.

Parameters

qspec_file : str, optional Raster of specific discharge (mm/d). Without it, the discharges are NaN. min_coverage_frac : float, optional Smallest fraction of a pixel a catchment must cover for the pixel to count in the zonal statistics. Defaults to 0: every touched pixel. coverage_weight : str, optional "fraction" counts pixels by the fraction of them the catchment covers, "none" counts them fully. Defaults to "fraction".

Source code in hydrolib/dhydamo/core/hydamo.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
def create_laterals(
    self,
    qspec_file: str | Path | None = None,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Create laterals at the catchments, with the mean specific discharge per catchment.

    Parameters
    ----------
    qspec_file : str, optional
        Raster of specific discharge (mm/d). Without it, the discharges are NaN.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a catchment must cover for the pixel to count in
        the zonal statistics. Defaults to 0: every touched pixel.
    coverage_weight : str, optional
        ``"fraction"`` counts pixels by the fraction of them the catchment covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.
    """
    ## Afvoer per gebied bepalen met zonal stats; nodata telt niet mee
    if qspec_file is not None:
        afvoer_per_gebied = zonal.zonal_stats(
            gpd.GeoDataFrame(self.catchments),
            qspec_file,
            statistics=("mean",),
            strategy="feature-sequential",
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
        )

    self.laterals = self.catchments.copy()

    catchment_columns = zip(
        self.catchments.index,
        self.catchments.geometry,
        self.catchments["code"],
        self.catchments["lateraleknoopid"],
    )
    for num, (index, geometry, code, knoopid) in enumerate(catchment_columns):
        ## Koppelen van afvoeren met afwateringsgebieden
        if qspec_file is not None:
            q = afvoer_per_gebied.iloc[num]["mean"]  # mm/d
        else:
            q = np.nan

        area = geometry.area  # m2
        q_m3s = q * area / (1000 * 86400)  # van mm/d naar m3/s
        self.laterals.loc[index, "afvoer"] = q_m3s

        ## Afstand tussen watergang en afwateringsgebied. Als watergang in afwateringsgebied ligt is deze afstand 0.
        distances = self.branches.distance(geometry)
        ## Eén of meer watergangen in afwateringsgebied:
        if sum(distances == 0) > 0:
            ## Watergangen intersecten met afwateringsgebied
            # wg = [watergang for watergang in watergangen.itertuples() if watergang.intersects(geometry]
            selectie = self.branches.intersection(geometry)
            ## Index van de watergang waarop je wilt snappen. Dit is de watergang die in het gebied ligt én het dichtst bij de centroid van het afwateringsgebied is.
            index_watergang = selectie.distance(geometry.centroid).idxmin()
            ## Combineer de ge intersecte watergangen met de index om het stuk watergang te vinden waarop mag worden gesnapt.
            watergang = selectie.loc[index_watergang]
        ## No intersects
        else:
            ## Vind de watergang die het dichtst bij de centroid van het gebied is
            index_watergang = self.branches.distance(geometry.centroid).idxmin()
            ## Selecteer deze watergang om op te mogen snappen
            watergang = self.branches.geometry.loc[index_watergang]

        ## Snap de centroid van het afwateringsgebied op de geselecteerde watergang
        lateral = watergang.interpolate(watergang.project(geometry.centroid))
        ## Schrijf de snap-locatie weg in de geodataframe
        # pandas-stubs does not accept a shapely geometry as value; pandas does
        self.laterals.loc[index, "geometry"] = lateral  # type: ignore[call-overload]
        self.laterals.loc[index, "globalid"] = knoopid
        self.laterals.loc[index, "code"] = f"lat_{code}"

    # Indexed by code, like loaded laterals
    self.laterals.index = pd.Index(self.laterals["code"], name="code")
dict_to_dataframe(dictionary: dict) -> pd.DataFrame

Return a dictionary of dictionaries as a DataFrame, with the keys as rows.

Parameters

dictionary : dict Input dictionary.

Returns

pd.DataFrame Output DataFrame.

Source code in hydrolib/dhydamo/core/hydamo.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def dict_to_dataframe(self, dictionary: dict) -> pd.DataFrame:
    """Return a dictionary of dictionaries as a DataFrame, with the keys as rows.

    Parameters
    ----------
    dictionary : dict
        Input dictionary.

    Returns
    -------
    pd.DataFrame
        Output DataFrame.
    """
    return pd.DataFrame.from_dict(dictionary, orient="index")
list_to_str(lst: list | np.ndarray) -> str

Return numbers as a space separated string, with 3 decimals.

Parameters

lst : list or np.ndarray Numbers.

Returns

str The numbers, or str(lst) for a single number.

Source code in hydrolib/dhydamo/core/hydamo.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def list_to_str(self, lst: list | np.ndarray) -> str:
    """Return numbers as a space separated string, with 3 decimals.

    Parameters
    ----------
    lst : list or np.ndarray
        Numbers.

    Returns
    -------
    str
        The numbers, or ``str(lst)`` for a single number.
    """
    if len(lst) == 1:
        string = str(lst)
    else:
        string = " ".join([f"{number:6.3f}" for number in lst])
    return string
load_from_gpkg(gpkg_path: Path | str, hydamo_version: str, clip_layers: dict | None = None, check_3d: bool = True, validation_mode: ValidationMode = 'off', validation_coverages: dict | None = None, validation_rules_path: Path | str | None = None) -> HyDAMO

Load HyDAMO data from a GeoPackage of a supported DAMO version.

Parameters

gpkg_path : str or Path Path to the GeoPackage file. hydamo_version : str DAMO schema version, one of SUPPORTED_HYDAMO_VERSIONS (2.2 to 2.6), e.g. "2.6". Required: it selects the renames back to DAMO 2.2, the names HYDROLIB uses; it does not detect or verify the source schema version. clip_layers : dict, optional Per-table spatial clip. Maps a HyDAMO table name to a (geometry, cliptype) tuple, e.g. {"branches": (gpd.read_file(extent).union_all(), "clip")}. Layers absent from the dict are loaded without clipping. check_3d : bool Whether to require Z coordinates on profile points when grouping them into lines. Other layers are not checked for Z coordinates. Pass False to allow 2D profile points. Default is True. validation_mode : str "off" skips validation (default). Both other modes act on the values the syntax check rejected in columns HYDROLIB reads (its required columns, globalid and, for spatial tables, the geometry): "warn" logs them as one warning per layer, by the hydrolib.dhydamo.validation logger, and continues; "strict" raises HyDAMOValidationError before loading layers, as it does when the validation run fails. Rejected values in other columns only give one INFO line with their number. Inspect validation_result.syntax_findings for all of them. Validation setup errors can raise in either enabled mode. validation_coverages : dict, optional Coverage dict forwarded to the validator. validation_rules_path : str or Path, optional Path to a custom validation-rules JSON file for the source DAMO version. If omitted, generated rules check ID presence on recognized layers with an ID column. Strict mode changes failure handling, not the rules or their coverage.

Returns

HyDAMO This instance, to allow method chaining.

Raises

HyDAMOValidationError In "strict" mode, if the validation run fails or rejected values in a column HYDROLIB reads. ImportError If validation is enabled and its optional dependency is unavailable. KeyError If a loaded layer lacks a required column, such as the code of a table whose code is its identity; the message names the layer. ValueError If the DAMO version is unsupported, or generated validation rules require a version unsupported by the installed validator. Also if the identity (code) or the column that groups points into lines (profiellijnid) is empty in some rows, also when it is only whitespace; the message names the layer and the rows by globalid.

Notes

A load replaces every DAMO table, also those whose layer the GeoPackage lacks: nothing of an earlier load is left in them. HYDROLIB's own tables (sewer areas, overflows, greenhouses, storage areas) are kept, and so are model objects built from an earlier load, such as structures and cross sections. For a new model, use a new HyDAMO.

Validation requires Python 3.12 and pip install "hydrolib[validation]". After enabled validation returns normally, self.validation_result contains success, status, errors and syntax_findings (per layer, column and error code). It is None when validation is off. Use validate_gpkg() to inspect validation failures without loading data. Comprehensive schema, type, and relation checks require appropriate custom rules; selecting a DAMO version or using strict mode alone does not establish that the input is valid DAMO data.

Examples

Given a rules file for DAMO 2.2, load and inspect reported failures:

hydamo = HyDAMO().load_from_gpkg( ... "model.gpkg", ... hydamo_version="2.2", ... validation_mode="warn", ... validation_rules_path="validationrules.json", ... ) result = hydamo.validation_result print(result.success, result.status, result.errors)

Use validation_mode="strict" to raise HyDAMOValidationError instead of loading after a reported validation failure.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def load_from_gpkg(
    self,
    gpkg_path: Path | str,
    hydamo_version: str,
    clip_layers: dict | None = None,
    check_3d: bool = True,
    validation_mode: ValidationMode = "off",
    validation_coverages: dict | None = None,
    validation_rules_path: Path | str | None = None,
) -> HyDAMO:
    """Load HyDAMO data from a GeoPackage of a supported DAMO version.

    Parameters
    ----------
    gpkg_path : str or Path
        Path to the GeoPackage file.
    hydamo_version : str
        DAMO schema version, one of ``SUPPORTED_HYDAMO_VERSIONS`` (2.2 to 2.6),
        e.g. ``"2.6"``. Required: it selects the renames back to DAMO 2.2, the
        names HYDROLIB uses; it does not detect or verify the source schema
        version.
    clip_layers : dict, optional
        Per-table spatial clip. Maps a HyDAMO table name to a
        ``(geometry, cliptype)`` tuple, e.g.
        ``{"branches": (gpd.read_file(extent).union_all(), "clip")}``.
        Layers absent from the dict are loaded without clipping.
    check_3d : bool
        Whether to require Z coordinates on profile points when grouping
        them into lines. Other layers are not checked for Z coordinates.
        Pass ``False`` to allow 2D profile points. Default is ``True``.
    validation_mode : str
        ``"off"`` skips validation (default). Both other modes act on the
        values the syntax check rejected in columns HYDROLIB reads (its
        required columns, ``globalid`` and, for spatial tables, the
        geometry): ``"warn"`` logs them as one warning per layer, by the
        ``hydrolib.dhydamo.validation`` logger, and continues; ``"strict"``
        raises ``HyDAMOValidationError`` before loading layers, as it does
        when the validation run fails. Rejected values in other columns
        only give one INFO line with their number. Inspect
        ``validation_result.syntax_findings`` for all of them. Validation
        setup errors can raise in either enabled mode.
    validation_coverages : dict, optional
        Coverage dict forwarded to the validator.
    validation_rules_path : str or Path, optional
        Path to a custom validation-rules JSON file for the source DAMO
        version. If omitted, generated rules check ID presence on recognized
        layers with an ID column. Strict mode changes failure handling,
        not the rules or their coverage.

    Returns
    -------
    HyDAMO
        This instance, to allow method chaining.

    Raises
    ------
    HyDAMOValidationError
        In ``"strict"`` mode, if the validation run fails or rejected values
        in a column HYDROLIB reads.
    ImportError
        If validation is enabled and its optional dependency is unavailable.
    KeyError
        If a loaded layer lacks a required column, such as the ``code`` of a
        table whose code is its identity; the message names the layer.
    ValueError
        If the DAMO version is unsupported, or generated validation
        rules require a version unsupported by the installed validator. Also
        if the identity (``code``) or the column that groups points into
        lines (``profiellijnid``) is empty in some rows, also when it is only
        whitespace; the message names the layer and the rows by ``globalid``.

    Notes
    -----
    A load replaces every DAMO table, also those whose layer the GeoPackage
    lacks: nothing of an earlier load is left in them. HYDROLIB's own tables
    (sewer areas, overflows, greenhouses, storage areas) are kept, and so are
    model objects built from an earlier load, such as structures and cross
    sections. For a new model, use a new ``HyDAMO``.

    Validation requires Python 3.12 and ``pip install "hydrolib[validation]"``.
    After enabled validation returns normally, ``self.validation_result``
    contains ``success``, ``status``, ``errors`` and ``syntax_findings``
    (per layer, column and error code). It is ``None`` when
    validation is off. Use ``validate_gpkg()`` to inspect validation failures
    without loading data. Comprehensive schema, type, and relation checks
    require appropriate custom rules; selecting a DAMO version or using strict
    mode alone does not establish that the input is valid DAMO data.

    Examples
    --------
    Given a rules file for DAMO 2.2, load and inspect reported failures:

    >>> hydamo = HyDAMO().load_from_gpkg(
    ...     "model.gpkg",
    ...     hydamo_version="2.2",
    ...     validation_mode="warn",
    ...     validation_rules_path="validationrules.json",
    ... )
    >>> result = hydamo.validation_result
    >>> print(result.success, result.status, result.errors)

    Use ``validation_mode="strict"`` to raise ``HyDAMOValidationError``
    instead of loading after a reported validation failure.
    """
    # Resolve the layers first so an unsupported version fails before validation runs.
    sources = source_layers(hydamo_version)

    self.validation_result = None
    self.source_damo_version = hydamo_version
    self.validation_result = validate_or_raise(
        gpkg_path=gpkg_path,
        hydamo_version=hydamo_version,
        validation_mode=validation_mode,
        coverages=validation_coverages,
        validation_rules_path=validation_rules_path,
        read_columns=(
            self._read_columns(sources) if validation_mode != "off" else None
        ),
    )

    self._reset_damo_tables()
    load_layers(
        self,
        gpkg_path,
        sources,
        hydamo_version,
        clip_layers=clip_layers,
        check_3d=check_3d,
    )
    return self
snap_to_branch_and_drop(extendedgdf: ExtendedGeoDataFrame, branches: ExtendedGeoDataFrame, snap_method: str, maxdist: float = 5, drop_related: bool = True, source_table: str | None = None) -> None

Snap geometries to branches and drop loose objects and cascades.

Parameters

extendedgdf : ExtendedGeoDataFrame HyDAMO dataframe to snap and potentially prune. branches : ExtendedGeoDataFrame Branch geometries used for snapping. snap_method : str Method passed to :meth:ExtendedGeoDataFrame.snap_to_branch. maxdist : float, default=5 Maximum snapping distance passed to snap_to_branch. drop_related : bool, default=True Whether to drop rows reached through the configured cascade paths. source_table : str, optional Canonical HyDAMO table name. If omitted, the name is determined from the dataframe object stored on this HyDAMO instance. Supply this when extendedgdf is a dataframe copy; the named table must still exist as an attribute on this instance.

Source code in hydrolib/dhydamo/core/hydamo.py
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
def snap_to_branch_and_drop(
    self,
    extendedgdf: ExtendedGeoDataFrame,
    branches: ExtendedGeoDataFrame,
    snap_method: str,
    maxdist: float = 5,
    drop_related: bool = True,
    source_table: str | None = None,
) -> None:
    """Snap geometries to branches and drop loose objects and cascades.

    Parameters
    ----------
    extendedgdf : ExtendedGeoDataFrame
        HyDAMO dataframe to snap and potentially prune.
    branches : ExtendedGeoDataFrame
        Branch geometries used for snapping.
    snap_method : str
        Method passed to :meth:`ExtendedGeoDataFrame.snap_to_branch`.
    maxdist : float, default=5
        Maximum snapping distance passed to ``snap_to_branch``.
    drop_related : bool, default=True
        Whether to drop rows reached through the configured cascade paths.
    source_table : str, optional
        Canonical HyDAMO table name.  If omitted, the name is determined
        from the dataframe object stored on this ``HyDAMO`` instance.
        Supply this when ``extendedgdf`` is a dataframe copy; the named
        table must still exist as an attribute on this instance.
    """
    # Snap the extended geodataframe to branches
    extendedgdf.snap_to_branch(branches, snap_method, maxdist=maxdist)

    # Determine which labels need to be drop for the first object based on
    # nan values for branch_offset.
    drop_idx = extendedgdf.index[pd.isna(extendedgdf.branch_offset)]
    logger.info("dropping objects with indices: %s", drop_idx)

    # Build the complete plan before mutating any dataframe.  This keeps
    # all relation traversals independent from the drops performed below.
    drop_plan: dict[str, pd.Index] = {}
    if drop_related:
        if source_table is None:
            for table_name, table in vars(self).items():
                if table is extendedgdf:
                    source_table = table_name
                    break
        if source_table is None:
            raise ValueError(
                "Could not determine the HyDAMO source table for the dataframe; pass source_table explicitly"
            )
        drop_plan = build_cascade_plan(self, source_table, drop_idx)

    # Drop the source and all related rows only after the plan is complete.
    # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
    extendedgdf.drop(labels=drop_idx, inplace=True)  # noqa: PD002
    for target_table, target_index in drop_plan.items():
        logger.info(
            "  - dropping objects from '%s' with indices: %s",
            target_table,
            target_index,
        )
        getattr(self, target_table).drop(labels=target_index, inplace=True)  # noqa: PD002
validate_gpkg(gpkg_path: Path | str, hydamo_version: str, validation_coverages: dict | None = None, validation_rules_path: Path | str | None = None) -> HydamoValidationResult

Validate a GeoPackage without loading its layers.

Requires Python 3.12 and the optional dependency installed with pip install "hydrolib[validation]".

Parameters

gpkg_path : str or Path Path to the GeoPackage file. hydamo_version : str DAMO version to validate against, e.g. "2.6". Required: it selects the version; it does not detect the source version. Any version that the installed validatiemodule has a schema for is accepted, which can include versions that load_from_gpkg cannot load yet (see SUPPORTED_HYDAMO_VERSIONS). For such a version no column counts as read by HYDROLIB, so every finding goes into the INFO line. validation_coverages : dict, optional Coverage dict forwarded to the validator. validation_rules_path : str or Path, optional Path to a validation-rules JSON file for the requested DAMO version. If omitted, generated rules check ID presence on recognized layers with an ID column. Supply custom rules for more comprehensive checks.

Returns

HydamoValidationResult Also stored as self.validation_result. Inspect success, status, errors and syntax_findings to handle validation failures. Findings in columns HYDROLIB reads are logged as one warning per layer by the hydrolib.dhydamo.validation logger, the number of other findings as one INFO line. A reported failure is returned rather than raised as HyDAMOValidationError. The validatiemodule's own diagnostics are logged by the hydamo_validation.validator logger.

Raises

ImportError If the optional validation dependency is unavailable. ValueError If generated rules are requested for a version unsupported by the installed validator's schemas.

Source code in hydrolib/dhydamo/core/hydamo.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def validate_gpkg(
    self,
    gpkg_path: Path | str,
    hydamo_version: str,
    validation_coverages: dict | None = None,
    validation_rules_path: Path | str | None = None,
) -> HydamoValidationResult:
    """Validate a GeoPackage without loading its layers.

    Requires Python 3.12 and the optional dependency installed with
    ``pip install "hydrolib[validation]"``.

    Parameters
    ----------
    gpkg_path : str or Path
        Path to the GeoPackage file.
    hydamo_version : str
        DAMO version to validate against, e.g. ``"2.6"``. Required: it selects
        the version; it does not detect the source version. Any version that the
        installed validatiemodule has a schema for is accepted, which can include
        versions that ``load_from_gpkg`` cannot load yet (see
        ``SUPPORTED_HYDAMO_VERSIONS``). For such a version no column counts as
        read by HYDROLIB, so every finding goes into the INFO line.
    validation_coverages : dict, optional
        Coverage dict forwarded to the validator.
    validation_rules_path : str or Path, optional
        Path to a validation-rules JSON file for the requested DAMO version.
        If omitted, generated rules check ID presence on recognized layers
        with an ID column. Supply custom rules for more comprehensive checks.

    Returns
    -------
    HydamoValidationResult
        Also stored as ``self.validation_result``. Inspect ``success``,
        ``status``, ``errors`` and ``syntax_findings`` to handle validation
        failures. Findings in columns HYDROLIB reads are logged as one
        warning per layer by the ``hydrolib.dhydamo.validation`` logger, the
        number of other findings as one INFO line. A reported failure is
        returned rather than raised as ``HyDAMOValidationError``. The
        validatiemodule's own diagnostics are logged by the
        ``hydamo_validation.validator`` logger.

    Raises
    ------
    ImportError
        If the optional validation dependency is unavailable.
    ValueError
        If generated rules are requested for a version unsupported by the
        installed validator's schemas.
    """
    # Without version steps to the version, no column counts as read.
    try:
        read_columns = self._read_columns(source_layers(hydamo_version))
    except ValueError:
        read_columns = {}
    result = validate_or_raise(
        gpkg_path=gpkg_path,
        hydamo_version=hydamo_version,
        validation_mode="warn",
        coverages=validation_coverages,
        validation_rules_path=validation_rules_path,
        read_columns=read_columns,
    )
    assert result is not None
    self.validation_result = result
    return result

Network

Legacy 1D network helpers, taken over from delft3dfmpy. Not functional.

The methods use self.mesh1d, self.branches, self.schematised and self.str2chars, which came from the gridgeom-based network in delft3dfmpy and are never set here: every method raises AttributeError. Nothing in this package, its tests or notebooks uses HyDAMO.network; the 1D network is the hydrolib-core Network (see hydrolib.dhydamo.geometry.mesh).

The methods are marked @no_type_check, so mypy skips them, like the deprecated gridgeom module. Remove this class together with gridgeom.

Source code in hydrolib/dhydamo/core/hydamo.py
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
class Network:
    """Legacy 1D network helpers, taken over from delft3dfmpy. Not functional.

    The methods use ``self.mesh1d``, ``self.branches``, ``self.schematised`` and
    ``self.str2chars``, which came from the gridgeom-based network in delft3dfmpy and
    are never set here: every method raises ``AttributeError``. Nothing in this package,
    its tests or notebooks uses ``HyDAMO.network``; the 1D network is the hydrolib-core
    ``Network`` (see ``hydrolib.dhydamo.geometry.mesh``).

    The methods are marked ``@no_type_check``, so mypy skips them, like the deprecated
    ``gridgeom`` module. Remove this class together with ``gridgeom``.
    """

    @no_type_check
    def __init__(self, hydamo: HyDAMO) -> None:
        """Create the legacy network helpers (not functional, see the class docstring)."""
        self.hydamo = hydamo

        # Mesh 1d offsets
        self.offsets = {}

    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def set_branch_order(self, branchids: list, idx: int | None = None) -> None:
        """Group branch ids so that the cross sections are interpolated along the branch.

        Parameters
        ----------
        branchids : list
            List of branches to group
        idx : int
            Order number with which to update a branch
        """
        # Get the ids (integers) of the branch names given by the user
        branchidx = np.isin(self.mesh1d.description1d["network_branch_ids"], branchids)
        # Get current order
        branchorder = self.mesh1d.get_values("nbranchorder", as_array=True)
        # Update
        if idx is None:
            branchorder[branchidx] = branchorder.max() + 1
        else:
            if not isinstance(idx, int):
                raise TypeError("Expected integer.")
            branchorder[branchidx] = idx
        # Save
        self.mesh1d.set_values("nbranchorder", branchorder)

    @no_type_check
    def set_branch_interpolation_modelwide(self) -> None:
        """Set cross-section interpolation over nodes on all branches model-wide.

        Note:
            - Interpolation will be set using branchorder property.
            - Branches are grouped between bifurcations where multiple branches meet.
            - No interpolation is applied over these type of bifurcations.
            - No branch order is set on branch groups consisting of 1 branch.
        """
        self.get_grouped_branches()
        for group in self.branch_groups.values():
            if len(group) > 1:
                self.set_branch_order(group)

    @no_type_check
    def make_nodes_to_branch_map(self) -> None:
        """Map nodes connected to each branch."""
        # Note: first node is upstream, second node is downstream
        self.nodes_to_branch_map = {
            b: [self.mesh1d.description1d["network_node_ids"][_idx - 1] for _idx in idx]
            for b, idx in zip(
                self.mesh1d.description1d["network_branch_ids"],
                self.mesh1d.get_values("nedge_nodes", as_array=True),
            )
        }

    @no_type_check
    def make_branches_to_node_map(self) -> None:
        """Map branches connected to each node."""
        self.make_nodes_to_branch_map()
        self.branches_to_node_map = {
            n: [k for k, v in self.nodes_to_branch_map.items() if n in v]
            for n in self.mesh1d.description1d["network_node_ids"]
        }

    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def generate_nodes_with_bedlevels(
        self,
        resolve_at_bifurcation_method: str = "min",
        return_reversed_branches: bool = False,
    ):
        """Generate nodes with upstream and downstream bed levels from the cross sections on a branch.

        It takes into account whether or not branch order is specified (so interpolation
        over nodes is set).

        Nodes in between cross-sections on same branch/branch-group are linearly interpolated. Outside are extrapolated
        constant (e.g. end points of branch).

        Branch groups which include branch with reversed direction compared to whole group will be taken into account.
        Use return_reversed_branches=True to return that information

        Specify with resolve_at_bifurcation_method how to resolve bedlevel at bifurcation of more than 2 branches using
        options 'min' (minimum), 'max' (maximum), 'mean' (average).
        """
        assert resolve_at_bifurcation_method in ["min", "max", "mean"], (
            "Incorrect value for 'resolve_at_bifurcation_method' supplied. Either use 'min', 'max' or 'mean'"
        )
        bedlevels_crs_branches = self.hydamo.crosssections.get_bottom_levels()
        branch_order = self.mesh1d.get_values("nbranchorder", as_array=True)
        self.make_branches_to_node_map()
        self.make_nodes_to_branch_map()
        nodes_dict = {n: {"up": [], "down": []} for n in self.branches_to_node_map}
        reserved_branches = []
        for order, (branch, nodes) in tqdm(
            zip(branch_order, self.nodes_to_branch_map.items()),
            total=len(branch_order),
            desc="Getting bedlevels",
        ):
            if order == -1:
                # No branch order so just get upstream and downstream levels
                branch_length = self.branches.loc[branch, "geometry"].length
                subset = bedlevels_crs_branches.loc[
                    bedlevels_crs_branches["branchid"] == branch
                ]
                if subset.empty:
                    continue  # if this happens, crs is not defined. This can be a problem.
                nodes_dict[nodes[0]]["up"].append(
                    np.interp(0.0, subset["chainage"], subset["minz"])
                )
                nodes_dict[nodes[1]]["down"].append(
                    np.interp(branch_length, subset["chainage"], subset["minz"])
                )
            else:
                # In case of branch order, first collect all branches and set in them in order of up- to downstream
                all_branches = [
                    self.mesh1d.description1d["network_branch_ids"][i]
                    for i in np.argwhere(order == branch_order).ravel()
                ]
                all_nodes = [self.nodes_to_branch_map[b] for b in all_branches]
                # First check if any of the branches has a bedlevel from a cross-section profile otherwise skip
                check = all(
                    bedlevels_crs_branches.loc[
                        bedlevels_crs_branches["branchid"] == b
                    ].empty
                    for b in all_branches
                )
                if check:
                    continue  # if this happens, cross-section is not defined. This can be a problem.

                # Check if every branch is from up to down direction. Otherwise fix by reversing
                n = 0
                n_length = len(all_nodes)
                direction = list(np.ones(n_length))
                max_tries = 0
                while n < n_length:
                    up = (
                        np.count_nonzero(
                            all_nodes[n][0] == np.array([x[0] for x in all_nodes])
                        )
                        == 1
                    )
                    down = (
                        np.count_nonzero(
                            all_nodes[n][1] == np.array([x[1] for x in all_nodes])
                        )
                        == 1
                    )
                    if (not up) or (not down):
                        # Reverse
                        all_nodes[n] = list(np.flip(all_nodes[n]))
                        direction[n] = direction[n] * -1
                    n += 1
                    # Check if indeed everything is now in proper direction. Otherwise try again
                    if n == n_length:
                        up = all(
                            np.count_nonzero(
                                node[0] == np.array([x[0] for x in all_nodes])
                            )
                            == 1
                            for node in all_nodes
                        )
                        down = all(
                            np.count_nonzero(
                                node[1] == np.array([x[1] for x in all_nodes])
                            )
                            == 1
                            for node in all_nodes
                        )
                        if (not up) or (not down):
                            n = 0
                            max_tries += 1
                    if max_tries > 500:
                        logger.warning(
                            "Can't fix correct directions branch groups %s",
                            all_branches,
                        )
                        break

                # Add reserved branches to return
                reserved_branches.extend(
                    [b for b, d in zip(all_branches, direction) if d == -1]
                )

                # Get most upstream node. Otherwise just pick i_upstream = 0 as starting point
                i_upstream = [
                    i
                    for i, n in enumerate([x[0] for x in all_nodes])
                    if n not in [x[1] for x in all_nodes]
                ]
                if len(i_upstream) == 1:
                    i_upstream = i_upstream[0]
                else:
                    # It could be that branch order group forms a ring. In this case check first which node has more
                    # than 2 branches (bifurcation) or just 1 branch (boundary) connected.
                    i_upstream = [
                        i
                        for i, n in enumerate([x[0] for x in all_nodes])
                        if (len(self.branches_to_node_map[n]) > 2)
                        or (len(self.branches_to_node_map[n]) == 1)
                    ]
                    if len(i_upstream) == 1:
                        i_upstream = i_upstream[0]
                    else:
                        raise ValueError(
                            f"Something is not right with the branch order group {all_branches}"
                        )

                # Now put branch list in correct order
                all_branches_sorted = []
                all_nodes_sorted = []
                direction_sorted = []
                for _ in range(len(all_branches)):
                    all_branches_sorted.append(all_branches[i_upstream])
                    all_nodes_sorted.append(all_nodes[i_upstream])
                    direction_sorted.append(direction[i_upstream])
                    next_upstream = next(
                        (
                            i
                            for i, n in enumerate([x[0] for x in all_nodes])
                            if [x[1] for x in all_nodes][i_upstream] == n
                        ),
                        None,
                    )
                    if next_upstream is None:
                        break
                    i_upstream = next_upstream
                # Stitch chainages and bedlevels together
                chainage, bedlevel = [], []
                branch_length = 0
                for b, d in zip(all_branches_sorted, direction_sorted):
                    subset = bedlevels_crs_branches.loc[
                        bedlevels_crs_branches["branchid"] == b
                    ]
                    chain, bed = subset["chainage"], subset["minz"]
                    # Reverse chainage and bedlevel arrays
                    if d == -1:
                        chain = np.flip(chain)
                        bed = np.flip(bed)
                    chainage.extend(chain + branch_length)
                    bedlevel.extend(bed)
                    branch_length = self.branches.loc[b, "geometry"].length
                # Get chainage of up- and downstream node of loop branch within the overall branch
                if len(all_branches_sorted) == 1:
                    up_node_chainage = 0
                    down_node_chainage = self.branches.loc[
                        all_branches_sorted[0], "geometry"
                    ].length
                else:
                    i = np.argmax(
                        [
                            1 if ((nodes == n) or (list(np.flip(nodes)) == n)) else 0
                            for n in all_nodes_sorted
                        ]
                    )
                    up_node_chainage = sum(
                        [0]
                        + [
                            self.branches.loc[b, "geometry"].length
                            for b, n in zip(
                                all_branches_sorted[:-1], all_nodes_sorted[:-1]
                            )
                        ][: i + 1]
                    )
                    down_node_chainage = sum(
                        [
                            self.branches.loc[b, "geometry"].length
                            for b, n in zip(all_branches_sorted, all_nodes_sorted)
                        ][: i + 1]
                    )
                # Finally interpolate
                nodes_dict[nodes[0]]["up"].append(
                    np.interp(up_node_chainage, chainage, bedlevel)
                )
                nodes_dict[nodes[1]]["down"].append(
                    np.interp(down_node_chainage, chainage, bedlevel)
                )

        # Summarize everything and save
        nodes = list(nodes_dict.keys())
        node_geom = [
            Point(x, y)
            for x, y in zip(
                self.mesh1d.get_values("nnodex"), self.mesh1d.get_values("nnodey")
            )
        ]
        if resolve_at_bifurcation_method == "min":
            upstream_bedlevel = [
                np.min(v["up"]) if len(v["up"]) > 0 else np.nan
                for v in nodes_dict.values()
            ]
            downstream_bedlevel = [
                np.min(v["down"]) if len(v["down"]) > 0 else np.nan
                for v in nodes_dict.values()
            ]
        elif resolve_at_bifurcation_method == "max":
            upstream_bedlevel = [
                np.max(v["up"]) if len(v["up"]) > 0 else np.nan
                for v in nodes_dict.values()
            ]
            downstream_bedlevel = [
                np.max(v["down"]) if len(v["down"]) > 0 else np.nan
                for v in nodes_dict.values()
            ]
        elif resolve_at_bifurcation_method == "mean":
            upstream_bedlevel = [
                np.average(["up"]) if len(v["up"]) > 0 else np.nan
                for v in nodes_dict.values()
            ]
            downstream_bedlevel = [
                np.average(v["down"]) if len(v["down"]) > 0 else np.nan
                for v in nodes_dict.values()
            ]
        else:
            raise NotImplementedError

        self.nodes = gpd.GeoDataFrame(
            index=nodes_dict.keys(),
            data={
                "code": nodes_dict.keys(),
                "upstream_bedlevel": upstream_bedlevel,
                "downstream_bedlevel": downstream_bedlevel,
            },
            geometry=node_geom,
        )

        if return_reversed_branches:
            return list(np.unique(reserved_branches))

    @no_type_check
    def get_grouped_branches(self) -> None:
        """Get grouped branch ids to use in set_branch_order function."""
        # Get all network data
        branch_ids = self.mesh1d.description1d["network_branch_ids"]
        # node_ids = self.mesh1d.description1d["network_node_ids"]
        # branch_edge_nodes_idx = self.mesh1d.get_values("nedge_nodes", as_array=True)
        # Collect all node ids per branch and all branches per node id
        self.make_nodes_to_branch_map()
        self.make_branches_to_node_map()

        branch_ids_checked = []
        groups = {0: []}
        for branch_id in branch_ids:
            if branch_id in branch_ids_checked:
                continue

            connected_nodes = self.nodes_to_branch_map[branch_id]  # get connected nodes
            for n in connected_nodes:
                b = self.branches_to_node_map[n]  # get connected branches
                if len(b) > 2:
                    continue  # in this case there's a bifurcation so skip
                elif len(b) == 1:
                    groups[list(groups.keys())[-1] + 1] = b  # b is already a list
                    branch_ids_checked.extend(b)
                    continue  # in this case the branch is not connected to other branches. make separate group
                else:
                    # remove branch from connected_branches because we are not interested in it
                    b = next(_b for _b in b if _b != branch_id)
                    if b in branch_ids_checked:
                        # connected branch is already added to a group, so this means that branch should be added to
                        # that group
                        groups[next(k for k, v in groups.items() if b in v)].append(
                            branch_id
                        )
                        branch_ids_checked.extend([branch_id])
                    else:
                        groups[list(groups.keys())[-1] + 1] = [
                            branch_id
                        ]  # otherwise add to group
                        branch_ids_checked.extend([branch_id])
                branch_ids_checked = list(np.unique(branch_ids_checked))
        groups.pop(0)  # remove the 0th group because empty

        # The branches are grouped but not fully connected (although routine above should do the trick in theory).
        # Try merging groups if a branch is in multiple groups.
        # In that case we know that branch groups are connected to eachother and is in fact a bigger group
        for b in branch_ids:
            _groups = groups.copy()  # make copy to apply changes on
            _k = -1  # default index
            # Loop over groups
            for k, v in groups.items():
                if b in v:  # if branch in grouped branches
                    if _k == -1:
                        _k = k  # set index to first group found
                    else:
                        _groups[_k].extend(
                            v
                        )  # otherwise add group to first found group
                        _groups[_k] = list(
                            np.unique(_groups[_k])
                        )  # remove duplicates due to add
                        _groups.pop(k)  # and remove group from groups
            groups = _groups.copy()  # copy changed dict over original
        # One pass over all branches should be sufficient to group everything together. Otherwise raise error
        if (
            max(
                [
                    sum([1 if b in v else 0 for k, v in groups.items()])
                    for b in branch_ids
                ]
            )
            > 1
        ):
            raise ValueError(
                f"Still branches contained in multiple groups. Maximum number of groups where this "
                f"happens: {max([sum([1 if b in v else 0 for k, v in groups.items()]) for b in branch_ids])}"
            )

        # save
        self.branch_groups = groups.copy()

    @no_type_check
    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def get_node_idx_offset(
        self, branch_id: str, pt: shapely.geometry.Point, nnodes: int = 1
    ) -> tuple:
        """Get the index and offset of the nearest node on a 1d branch."""
        # Project the point on the branch
        dist = self.schematised[branch_id].project(pt)

        # Get the branch data from the networkdata
        branchidx = (
            self.mesh1d.description1d["network_branch_ids"].index(
                self.str2chars(branch_id, self.idstrlength)
            )
            + 1
        )
        pt_branch_id = self.mesh1d.get_values("branchidx", as_array=True)
        idx = np.nonzero(pt_branch_id == branchidx)

        # Find nearest offset
        offsets = self.mesh1d.get_values("branchoffset", as_array=True)[idx]
        isorted = np.argsort(np.absolute(offsets - dist))
        isorted = isorted[: min(nnodes, len(isorted))]

        # Get the offset
        offset = [offsets[imin] for imin in isorted]
        # Get the id of the node
        node_id = [idx[0][imin] + 1 for imin in isorted]

        return node_id, offset
__init__(hydamo: HyDAMO) -> None

Create the legacy network helpers (not functional, see the class docstring).

Source code in hydrolib/dhydamo/core/hydamo.py
599
600
601
602
603
604
605
@no_type_check
def __init__(self, hydamo: HyDAMO) -> None:
    """Create the legacy network helpers (not functional, see the class docstring)."""
    self.hydamo = hydamo

    # Mesh 1d offsets
    self.offsets = {}
generate_nodes_with_bedlevels(resolve_at_bifurcation_method: str = 'min', return_reversed_branches: bool = False)

Generate nodes with upstream and downstream bed levels from the cross sections on a branch.

It takes into account whether or not branch order is specified (so interpolation over nodes is set).

Nodes in between cross-sections on same branch/branch-group are linearly interpolated. Outside are extrapolated constant (e.g. end points of branch).

Branch groups which include branch with reversed direction compared to whole group will be taken into account. Use return_reversed_branches=True to return that information

Specify with resolve_at_bifurcation_method how to resolve bedlevel at bifurcation of more than 2 branches using options 'min' (minimum), 'max' (maximum), 'mean' (average).

Source code in hydrolib/dhydamo/core/hydamo.py
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def generate_nodes_with_bedlevels(
    self,
    resolve_at_bifurcation_method: str = "min",
    return_reversed_branches: bool = False,
):
    """Generate nodes with upstream and downstream bed levels from the cross sections on a branch.

    It takes into account whether or not branch order is specified (so interpolation
    over nodes is set).

    Nodes in between cross-sections on same branch/branch-group are linearly interpolated. Outside are extrapolated
    constant (e.g. end points of branch).

    Branch groups which include branch with reversed direction compared to whole group will be taken into account.
    Use return_reversed_branches=True to return that information

    Specify with resolve_at_bifurcation_method how to resolve bedlevel at bifurcation of more than 2 branches using
    options 'min' (minimum), 'max' (maximum), 'mean' (average).
    """
    assert resolve_at_bifurcation_method in ["min", "max", "mean"], (
        "Incorrect value for 'resolve_at_bifurcation_method' supplied. Either use 'min', 'max' or 'mean'"
    )
    bedlevels_crs_branches = self.hydamo.crosssections.get_bottom_levels()
    branch_order = self.mesh1d.get_values("nbranchorder", as_array=True)
    self.make_branches_to_node_map()
    self.make_nodes_to_branch_map()
    nodes_dict = {n: {"up": [], "down": []} for n in self.branches_to_node_map}
    reserved_branches = []
    for order, (branch, nodes) in tqdm(
        zip(branch_order, self.nodes_to_branch_map.items()),
        total=len(branch_order),
        desc="Getting bedlevels",
    ):
        if order == -1:
            # No branch order so just get upstream and downstream levels
            branch_length = self.branches.loc[branch, "geometry"].length
            subset = bedlevels_crs_branches.loc[
                bedlevels_crs_branches["branchid"] == branch
            ]
            if subset.empty:
                continue  # if this happens, crs is not defined. This can be a problem.
            nodes_dict[nodes[0]]["up"].append(
                np.interp(0.0, subset["chainage"], subset["minz"])
            )
            nodes_dict[nodes[1]]["down"].append(
                np.interp(branch_length, subset["chainage"], subset["minz"])
            )
        else:
            # In case of branch order, first collect all branches and set in them in order of up- to downstream
            all_branches = [
                self.mesh1d.description1d["network_branch_ids"][i]
                for i in np.argwhere(order == branch_order).ravel()
            ]
            all_nodes = [self.nodes_to_branch_map[b] for b in all_branches]
            # First check if any of the branches has a bedlevel from a cross-section profile otherwise skip
            check = all(
                bedlevels_crs_branches.loc[
                    bedlevels_crs_branches["branchid"] == b
                ].empty
                for b in all_branches
            )
            if check:
                continue  # if this happens, cross-section is not defined. This can be a problem.

            # Check if every branch is from up to down direction. Otherwise fix by reversing
            n = 0
            n_length = len(all_nodes)
            direction = list(np.ones(n_length))
            max_tries = 0
            while n < n_length:
                up = (
                    np.count_nonzero(
                        all_nodes[n][0] == np.array([x[0] for x in all_nodes])
                    )
                    == 1
                )
                down = (
                    np.count_nonzero(
                        all_nodes[n][1] == np.array([x[1] for x in all_nodes])
                    )
                    == 1
                )
                if (not up) or (not down):
                    # Reverse
                    all_nodes[n] = list(np.flip(all_nodes[n]))
                    direction[n] = direction[n] * -1
                n += 1
                # Check if indeed everything is now in proper direction. Otherwise try again
                if n == n_length:
                    up = all(
                        np.count_nonzero(
                            node[0] == np.array([x[0] for x in all_nodes])
                        )
                        == 1
                        for node in all_nodes
                    )
                    down = all(
                        np.count_nonzero(
                            node[1] == np.array([x[1] for x in all_nodes])
                        )
                        == 1
                        for node in all_nodes
                    )
                    if (not up) or (not down):
                        n = 0
                        max_tries += 1
                if max_tries > 500:
                    logger.warning(
                        "Can't fix correct directions branch groups %s",
                        all_branches,
                    )
                    break

            # Add reserved branches to return
            reserved_branches.extend(
                [b for b, d in zip(all_branches, direction) if d == -1]
            )

            # Get most upstream node. Otherwise just pick i_upstream = 0 as starting point
            i_upstream = [
                i
                for i, n in enumerate([x[0] for x in all_nodes])
                if n not in [x[1] for x in all_nodes]
            ]
            if len(i_upstream) == 1:
                i_upstream = i_upstream[0]
            else:
                # It could be that branch order group forms a ring. In this case check first which node has more
                # than 2 branches (bifurcation) or just 1 branch (boundary) connected.
                i_upstream = [
                    i
                    for i, n in enumerate([x[0] for x in all_nodes])
                    if (len(self.branches_to_node_map[n]) > 2)
                    or (len(self.branches_to_node_map[n]) == 1)
                ]
                if len(i_upstream) == 1:
                    i_upstream = i_upstream[0]
                else:
                    raise ValueError(
                        f"Something is not right with the branch order group {all_branches}"
                    )

            # Now put branch list in correct order
            all_branches_sorted = []
            all_nodes_sorted = []
            direction_sorted = []
            for _ in range(len(all_branches)):
                all_branches_sorted.append(all_branches[i_upstream])
                all_nodes_sorted.append(all_nodes[i_upstream])
                direction_sorted.append(direction[i_upstream])
                next_upstream = next(
                    (
                        i
                        for i, n in enumerate([x[0] for x in all_nodes])
                        if [x[1] for x in all_nodes][i_upstream] == n
                    ),
                    None,
                )
                if next_upstream is None:
                    break
                i_upstream = next_upstream
            # Stitch chainages and bedlevels together
            chainage, bedlevel = [], []
            branch_length = 0
            for b, d in zip(all_branches_sorted, direction_sorted):
                subset = bedlevels_crs_branches.loc[
                    bedlevels_crs_branches["branchid"] == b
                ]
                chain, bed = subset["chainage"], subset["minz"]
                # Reverse chainage and bedlevel arrays
                if d == -1:
                    chain = np.flip(chain)
                    bed = np.flip(bed)
                chainage.extend(chain + branch_length)
                bedlevel.extend(bed)
                branch_length = self.branches.loc[b, "geometry"].length
            # Get chainage of up- and downstream node of loop branch within the overall branch
            if len(all_branches_sorted) == 1:
                up_node_chainage = 0
                down_node_chainage = self.branches.loc[
                    all_branches_sorted[0], "geometry"
                ].length
            else:
                i = np.argmax(
                    [
                        1 if ((nodes == n) or (list(np.flip(nodes)) == n)) else 0
                        for n in all_nodes_sorted
                    ]
                )
                up_node_chainage = sum(
                    [0]
                    + [
                        self.branches.loc[b, "geometry"].length
                        for b, n in zip(
                            all_branches_sorted[:-1], all_nodes_sorted[:-1]
                        )
                    ][: i + 1]
                )
                down_node_chainage = sum(
                    [
                        self.branches.loc[b, "geometry"].length
                        for b, n in zip(all_branches_sorted, all_nodes_sorted)
                    ][: i + 1]
                )
            # Finally interpolate
            nodes_dict[nodes[0]]["up"].append(
                np.interp(up_node_chainage, chainage, bedlevel)
            )
            nodes_dict[nodes[1]]["down"].append(
                np.interp(down_node_chainage, chainage, bedlevel)
            )

    # Summarize everything and save
    nodes = list(nodes_dict.keys())
    node_geom = [
        Point(x, y)
        for x, y in zip(
            self.mesh1d.get_values("nnodex"), self.mesh1d.get_values("nnodey")
        )
    ]
    if resolve_at_bifurcation_method == "min":
        upstream_bedlevel = [
            np.min(v["up"]) if len(v["up"]) > 0 else np.nan
            for v in nodes_dict.values()
        ]
        downstream_bedlevel = [
            np.min(v["down"]) if len(v["down"]) > 0 else np.nan
            for v in nodes_dict.values()
        ]
    elif resolve_at_bifurcation_method == "max":
        upstream_bedlevel = [
            np.max(v["up"]) if len(v["up"]) > 0 else np.nan
            for v in nodes_dict.values()
        ]
        downstream_bedlevel = [
            np.max(v["down"]) if len(v["down"]) > 0 else np.nan
            for v in nodes_dict.values()
        ]
    elif resolve_at_bifurcation_method == "mean":
        upstream_bedlevel = [
            np.average(["up"]) if len(v["up"]) > 0 else np.nan
            for v in nodes_dict.values()
        ]
        downstream_bedlevel = [
            np.average(v["down"]) if len(v["down"]) > 0 else np.nan
            for v in nodes_dict.values()
        ]
    else:
        raise NotImplementedError

    self.nodes = gpd.GeoDataFrame(
        index=nodes_dict.keys(),
        data={
            "code": nodes_dict.keys(),
            "upstream_bedlevel": upstream_bedlevel,
            "downstream_bedlevel": downstream_bedlevel,
        },
        geometry=node_geom,
    )

    if return_reversed_branches:
        return list(np.unique(reserved_branches))
get_grouped_branches() -> None

Get grouped branch ids to use in set_branch_order function.

Source code in hydrolib/dhydamo/core/hydamo.py
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
@no_type_check
def get_grouped_branches(self) -> None:
    """Get grouped branch ids to use in set_branch_order function."""
    # Get all network data
    branch_ids = self.mesh1d.description1d["network_branch_ids"]
    # node_ids = self.mesh1d.description1d["network_node_ids"]
    # branch_edge_nodes_idx = self.mesh1d.get_values("nedge_nodes", as_array=True)
    # Collect all node ids per branch and all branches per node id
    self.make_nodes_to_branch_map()
    self.make_branches_to_node_map()

    branch_ids_checked = []
    groups = {0: []}
    for branch_id in branch_ids:
        if branch_id in branch_ids_checked:
            continue

        connected_nodes = self.nodes_to_branch_map[branch_id]  # get connected nodes
        for n in connected_nodes:
            b = self.branches_to_node_map[n]  # get connected branches
            if len(b) > 2:
                continue  # in this case there's a bifurcation so skip
            elif len(b) == 1:
                groups[list(groups.keys())[-1] + 1] = b  # b is already a list
                branch_ids_checked.extend(b)
                continue  # in this case the branch is not connected to other branches. make separate group
            else:
                # remove branch from connected_branches because we are not interested in it
                b = next(_b for _b in b if _b != branch_id)
                if b in branch_ids_checked:
                    # connected branch is already added to a group, so this means that branch should be added to
                    # that group
                    groups[next(k for k, v in groups.items() if b in v)].append(
                        branch_id
                    )
                    branch_ids_checked.extend([branch_id])
                else:
                    groups[list(groups.keys())[-1] + 1] = [
                        branch_id
                    ]  # otherwise add to group
                    branch_ids_checked.extend([branch_id])
            branch_ids_checked = list(np.unique(branch_ids_checked))
    groups.pop(0)  # remove the 0th group because empty

    # The branches are grouped but not fully connected (although routine above should do the trick in theory).
    # Try merging groups if a branch is in multiple groups.
    # In that case we know that branch groups are connected to eachother and is in fact a bigger group
    for b in branch_ids:
        _groups = groups.copy()  # make copy to apply changes on
        _k = -1  # default index
        # Loop over groups
        for k, v in groups.items():
            if b in v:  # if branch in grouped branches
                if _k == -1:
                    _k = k  # set index to first group found
                else:
                    _groups[_k].extend(
                        v
                    )  # otherwise add group to first found group
                    _groups[_k] = list(
                        np.unique(_groups[_k])
                    )  # remove duplicates due to add
                    _groups.pop(k)  # and remove group from groups
        groups = _groups.copy()  # copy changed dict over original
    # One pass over all branches should be sufficient to group everything together. Otherwise raise error
    if (
        max(
            [
                sum([1 if b in v else 0 for k, v in groups.items()])
                for b in branch_ids
            ]
        )
        > 1
    ):
        raise ValueError(
            f"Still branches contained in multiple groups. Maximum number of groups where this "
            f"happens: {max([sum([1 if b in v else 0 for k, v in groups.items()]) for b in branch_ids])}"
        )

    # save
    self.branch_groups = groups.copy()
get_node_idx_offset(branch_id: str, pt: shapely.geometry.Point, nnodes: int = 1) -> tuple

Get the index and offset of the nearest node on a 1d branch.

Source code in hydrolib/dhydamo/core/hydamo.py
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
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def get_node_idx_offset(
    self, branch_id: str, pt: shapely.geometry.Point, nnodes: int = 1
) -> tuple:
    """Get the index and offset of the nearest node on a 1d branch."""
    # Project the point on the branch
    dist = self.schematised[branch_id].project(pt)

    # Get the branch data from the networkdata
    branchidx = (
        self.mesh1d.description1d["network_branch_ids"].index(
            self.str2chars(branch_id, self.idstrlength)
        )
        + 1
    )
    pt_branch_id = self.mesh1d.get_values("branchidx", as_array=True)
    idx = np.nonzero(pt_branch_id == branchidx)

    # Find nearest offset
    offsets = self.mesh1d.get_values("branchoffset", as_array=True)[idx]
    isorted = np.argsort(np.absolute(offsets - dist))
    isorted = isorted[: min(nnodes, len(isorted))]

    # Get the offset
    offset = [offsets[imin] for imin in isorted]
    # Get the id of the node
    node_id = [idx[0][imin] + 1 for imin in isorted]

    return node_id, offset
make_branches_to_node_map() -> None

Map branches connected to each node.

Source code in hydrolib/dhydamo/core/hydamo.py
662
663
664
665
666
667
668
669
@no_type_check
def make_branches_to_node_map(self) -> None:
    """Map branches connected to each node."""
    self.make_nodes_to_branch_map()
    self.branches_to_node_map = {
        n: [k for k, v in self.nodes_to_branch_map.items() if n in v]
        for n in self.mesh1d.description1d["network_node_ids"]
    }
make_nodes_to_branch_map() -> None

Map nodes connected to each branch.

Source code in hydrolib/dhydamo/core/hydamo.py
650
651
652
653
654
655
656
657
658
659
660
@no_type_check
def make_nodes_to_branch_map(self) -> None:
    """Map nodes connected to each branch."""
    # Note: first node is upstream, second node is downstream
    self.nodes_to_branch_map = {
        b: [self.mesh1d.description1d["network_node_ids"][_idx - 1] for _idx in idx]
        for b, idx in zip(
            self.mesh1d.description1d["network_branch_ids"],
            self.mesh1d.get_values("nedge_nodes", as_array=True),
        )
    }
set_branch_interpolation_modelwide() -> None

Set cross-section interpolation over nodes on all branches model-wide.

Note
  • Interpolation will be set using branchorder property.
  • Branches are grouped between bifurcations where multiple branches meet.
  • No interpolation is applied over these type of bifurcations.
  • No branch order is set on branch groups consisting of 1 branch.
Source code in hydrolib/dhydamo/core/hydamo.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
@no_type_check
def set_branch_interpolation_modelwide(self) -> None:
    """Set cross-section interpolation over nodes on all branches model-wide.

    Note:
        - Interpolation will be set using branchorder property.
        - Branches are grouped between bifurcations where multiple branches meet.
        - No interpolation is applied over these type of bifurcations.
        - No branch order is set on branch groups consisting of 1 branch.
    """
    self.get_grouped_branches()
    for group in self.branch_groups.values():
        if len(group) > 1:
            self.set_branch_order(group)
set_branch_order(branchids: list, idx: int | None = None) -> None

Group branch ids so that the cross sections are interpolated along the branch.

Parameters

branchids : list List of branches to group idx : int Order number with which to update a branch

Source code in hydrolib/dhydamo/core/hydamo.py
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
@no_type_check
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def set_branch_order(self, branchids: list, idx: int | None = None) -> None:
    """Group branch ids so that the cross sections are interpolated along the branch.

    Parameters
    ----------
    branchids : list
        List of branches to group
    idx : int
        Order number with which to update a branch
    """
    # Get the ids (integers) of the branch names given by the user
    branchidx = np.isin(self.mesh1d.description1d["network_branch_ids"], branchids)
    # Get current order
    branchorder = self.mesh1d.get_values("nbranchorder", as_array=True)
    # Update
    if idx is None:
        branchorder[branchidx] = branchorder.max() + 1
    else:
        if not isinstance(idx, int):
            raise TypeError("Expected integer.")
        branchorder[branchidx] = idx
    # Save
    self.mesh1d.set_values("nbranchorder", branchorder)

ObservationPoints

Observation points of the model.

Parameters

hydamo : HyDAMO The HyDAMO object they belong to.

Source code in hydrolib/dhydamo/core/hydamo.py
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
class ObservationPoints:
    """Observation points of the model.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO object they belong to.
    """

    def __init__(self, hydamo: HyDAMO) -> None:
        self.hydamo = hydamo
        self.observation_points = gpd.GeoDataFrame().set_geometry([])

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_points(
        self,
        crds: list,
        names: list,
        locationTypes: str | list[str] | None = None,
        snap_distance: float = 5.0,
    ) -> None:
        """Add observation points, of type '1d' or '2d'; 1d points are snapped to a branch.

        Parameters
        ----------
        crds : Nx2 list or array
            x and y coordinates of observation points
        names : str or list
            names of the observation points
        locationTypes:  str or list
            type of the observationpoints: 1d or 2d
        snap_distance : float (default is 5 m)
            1d observation poinst within this distance to a branch will be snapped to it. Otherwise they are discarded.
        """
        if isinstance(names, str):
            names = [names]
            crds = [crds]

        if locationTypes is not None:
            if isinstance(locationTypes, str):
                locationTypes = [locationTypes]

            # split 1d and 2d points, as the first ones need to be snapped to branches
            obs2d = gpd.GeoDataFrame()
            obs2d["name"] = [
                n for nn, n in enumerate(names) if locationTypes[nn] == "2d"
            ]
            obs2d["locationtype"] = "2d"
            obs2d = obs2d.set_geometry(
                [
                    Point(*pt) if not isinstance(pt, Point) else pt
                    for ipt, pt in enumerate(crds)
                    if (locationTypes[ipt] == "2d")
                ]
            )
            obs2d["x"] = [pt.coords[0][0] for pt in obs2d["geometry"]]
            obs2d["y"] = [pt.coords[0][1] for pt in obs2d["geometry"]]
            names1d = [n for n_i, n in enumerate(names) if locationTypes[n_i] == "1d"]
            crds1d = [c for c_i, c in enumerate(crds) if locationTypes[c_i] == "1d"]
        else:
            names1d = names
            crds1d = crds

        obs1d = gpd.GeoDataFrame()
        obs1d["name"] = names1d
        obs1d = obs1d.set_geometry(
            [Point(*pt) if not isinstance(pt, Point) else pt for pt in crds1d]
        )
        obs1d["locationtype"] = "1d"
        find_nearest_branch(
            self.hydamo.branches, obs1d, method="overal", maxdist=snap_distance
        )
        obs1d = obs1d.rename(
            columns={"branch_id": "branchid", "branch_offset": "chainage"}
        )

        obs = (
            pd.concat([obs1d, obs2d], sort=True) if locationTypes is not None else obs1d
        )

        obs = obs.dropna(how="all", axis=1)

        # Add to dataframe
        if self.observation_points.empty:
            self.observation_points = gpd.GeoDataFrame(obs)
        else:
            self.observation_points = gpd.GeoDataFrame(
                pd.concat([self.observation_points, obs], ignore_index=True)
            )
add_points(crds: list, names: list, locationTypes: str | list[str] | None = None, snap_distance: float = 5.0) -> None

Add observation points, of type '1d' or '2d'; 1d points are snapped to a branch.

Parameters

crds : Nx2 list or array x and y coordinates of observation points names : str or list names of the observation points locationTypes: str or list type of the observationpoints: 1d or 2d snap_distance : float (default is 5 m) 1d observation poinst within this distance to a branch will be snapped to it. Otherwise they are discarded.

Source code in hydrolib/dhydamo/core/hydamo.py
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_points(
    self,
    crds: list,
    names: list,
    locationTypes: str | list[str] | None = None,
    snap_distance: float = 5.0,
) -> None:
    """Add observation points, of type '1d' or '2d'; 1d points are snapped to a branch.

    Parameters
    ----------
    crds : Nx2 list or array
        x and y coordinates of observation points
    names : str or list
        names of the observation points
    locationTypes:  str or list
        type of the observationpoints: 1d or 2d
    snap_distance : float (default is 5 m)
        1d observation poinst within this distance to a branch will be snapped to it. Otherwise they are discarded.
    """
    if isinstance(names, str):
        names = [names]
        crds = [crds]

    if locationTypes is not None:
        if isinstance(locationTypes, str):
            locationTypes = [locationTypes]

        # split 1d and 2d points, as the first ones need to be snapped to branches
        obs2d = gpd.GeoDataFrame()
        obs2d["name"] = [
            n for nn, n in enumerate(names) if locationTypes[nn] == "2d"
        ]
        obs2d["locationtype"] = "2d"
        obs2d = obs2d.set_geometry(
            [
                Point(*pt) if not isinstance(pt, Point) else pt
                for ipt, pt in enumerate(crds)
                if (locationTypes[ipt] == "2d")
            ]
        )
        obs2d["x"] = [pt.coords[0][0] for pt in obs2d["geometry"]]
        obs2d["y"] = [pt.coords[0][1] for pt in obs2d["geometry"]]
        names1d = [n for n_i, n in enumerate(names) if locationTypes[n_i] == "1d"]
        crds1d = [c for c_i, c in enumerate(crds) if locationTypes[c_i] == "1d"]
    else:
        names1d = names
        crds1d = crds

    obs1d = gpd.GeoDataFrame()
    obs1d["name"] = names1d
    obs1d = obs1d.set_geometry(
        [Point(*pt) if not isinstance(pt, Point) else pt for pt in crds1d]
    )
    obs1d["locationtype"] = "1d"
    find_nearest_branch(
        self.hydamo.branches, obs1d, method="overal", maxdist=snap_distance
    )
    obs1d = obs1d.rename(
        columns={"branch_id": "branchid", "branch_offset": "chainage"}
    )

    obs = (
        pd.concat([obs1d, obs2d], sort=True) if locationTypes is not None else obs1d
    )

    obs = obs.dropna(how="all", axis=1)

    # Add to dataframe
    if self.observation_points.empty:
        self.observation_points = gpd.GeoDataFrame(obs)
    else:
        self.observation_points = gpd.GeoDataFrame(
            pd.concat([self.observation_points, obs], ignore_index=True)
        )

StorageNodes

Storage nodes of the model.

Parameters

hydamo : HyDAMO The HyDAMO object they belong to.

Source code in hydrolib/dhydamo/core/hydamo.py
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
class StorageNodes:
    """Storage nodes of the model.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO object they belong to.
    """

    def __init__(self, hydamo: HyDAMO) -> None:
        self.storagenodes: dict[str, dict[str, object]] = {}

        self.hydamo = hydamo

        self.convert = StorageNodesIO(self)

    def add_storagenode(
        self,
        id: str,
        xy: tuple[float, float] | Point | None = None,
        branchid: str | None = None,
        chainage: float | None = None,
        nodeid: str | None = None,
        usestreetstorage: str | bool = "true",
        nodetype: str = "unspecified",
        manholeid: str | None = None,
        name: str | float = np.nan,
        usetable: str = "false",
        bedlevel: float = np.nan,
        area: float = np.nan,
        streetlevel: float = np.nan,
        streetstoragearea: float = np.nan,
        storagetype: str = "reservoir",
        levels: str | float = np.nan,
        storagearea: str | float = np.nan,
        interpolate: str = "linear",
        network: netmodels.Network | None = None,
    ) -> None:
        """Add a storage node, at a 1D node.

        The node is ``nodeid``, or the 1D node nearest to ``xy`` or to ``branchid`` and
        ``chainage``. The other arguments correspond to the D-Flow FM keywords of a
        storage node; with ``usetable="true"``, ``levels`` and ``storagearea`` are space
        separated numbers.

        Raises
        ------
        ValueError
            Without a ``nodeid``, a network or a location; or with a table but without
            ``levels`` and ``storagearea``.
        """
        if isinstance(xy, tuple):
            xy = Point(*xy)
        if xy is None and branchid is not None and chainage is not None:
            xy = self.hydamo.branches.geometry[branchid].interpolate(chainage)

        # Find the nearest node
        if nodeid is not None and not isinstance(nodeid, str):
            raise ValueError("If a nodeid is provided, it should be of type string.")
        if nodeid is None:
            if network is None or xy is None:
                raise ValueError(
                    "Without a nodeid, provide the network and a location: xy, or branchid and chainage."
                )
            if len(network._mesh1d.network1d_node_id) == 0:
                raise KeyError(
                    "To find the closest node a 1d mesh should be created first."
                )
            nodes1d = np.asarray(
                [
                    n
                    for n in zip(
                        network._mesh1d.network1d_node_x,
                        network._mesh1d.network1d_node_y,
                        network._mesh1d.network1d_node_id,
                    )
                ]
            )
            get_nearest = KDTree(nodes1d[:, 0:2])
            _, idx_nearest = get_nearest.query(xy.coords[:])
            nodeid = f"{float(nodes1d[idx_nearest[0], 0]):12.6f}_{float(nodes1d[idx_nearest[0], 1]):12.6f}"

        if manholeid is None:
            manholeid = nodeid

        base = {
            "type": "storageNode",
            "id": id,
            "name": id if name is None else name,
            "useStreetStorage": usestreetstorage,
            "nodeType": nodetype,
            "useTable": usetable,
            "manholeId": manholeid,
        }
        if nodeid is None:
            cds = {"branchid": branchid, "chainage": chainage}
        else:
            cds = {"nodeid": nodeid}

        if usetable == "false":
            out = {
                **base,
                **cds,
                "bedLevel": bedlevel,
                "area": area,
                "streetLevel": streetlevel,
                "streetStorageArea": streetstoragearea,
                "storageType": storagetype,
            }
        elif usetable == "true":
            if not isinstance(levels, str) or not isinstance(storagearea, str):
                raise ValueError(
                    "With usetable='true', provide levels and storagearea as strings of numbers."
                )
            assert len(levels.split()) == len(storagearea.split()), (
                "Number of levels does not equal number of storagearea"
            )
            out = {
                **base,
                **cds,
                "numLevels": len(levels.split()),
                "levels": levels,
                "storageArea": storagearea,
                "interpolate": interpolate,
                "bedLevel": -999.0,
                "area": -999.0,
                "streetLevel": -999.0,
                "streetStorageArea": -999.0,
                "storageType": storagetype,
            }
        else:
            raise ValueError(
                "Value of key 'usetable' is not supported. Either use 'true' or 'false"
            )
        self.storagenodes[id] = remove_nan_values(out)
add_storagenode(id: str, xy: tuple[float, float] | Point | None = None, branchid: str | None = None, chainage: float | None = None, nodeid: str | None = None, usestreetstorage: str | bool = 'true', nodetype: str = 'unspecified', manholeid: str | None = None, name: str | float = np.nan, usetable: str = 'false', bedlevel: float = np.nan, area: float = np.nan, streetlevel: float = np.nan, streetstoragearea: float = np.nan, storagetype: str = 'reservoir', levels: str | float = np.nan, storagearea: str | float = np.nan, interpolate: str = 'linear', network: netmodels.Network | None = None) -> None

Add a storage node, at a 1D node.

The node is nodeid, or the 1D node nearest to xy or to branchid and chainage. The other arguments correspond to the D-Flow FM keywords of a storage node; with usetable="true", levels and storagearea are space separated numbers.

Raises

ValueError Without a nodeid, a network or a location; or with a table but without levels and storagearea.

Source code in hydrolib/dhydamo/core/hydamo.py
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
def add_storagenode(
    self,
    id: str,
    xy: tuple[float, float] | Point | None = None,
    branchid: str | None = None,
    chainage: float | None = None,
    nodeid: str | None = None,
    usestreetstorage: str | bool = "true",
    nodetype: str = "unspecified",
    manholeid: str | None = None,
    name: str | float = np.nan,
    usetable: str = "false",
    bedlevel: float = np.nan,
    area: float = np.nan,
    streetlevel: float = np.nan,
    streetstoragearea: float = np.nan,
    storagetype: str = "reservoir",
    levels: str | float = np.nan,
    storagearea: str | float = np.nan,
    interpolate: str = "linear",
    network: netmodels.Network | None = None,
) -> None:
    """Add a storage node, at a 1D node.

    The node is ``nodeid``, or the 1D node nearest to ``xy`` or to ``branchid`` and
    ``chainage``. The other arguments correspond to the D-Flow FM keywords of a
    storage node; with ``usetable="true"``, ``levels`` and ``storagearea`` are space
    separated numbers.

    Raises
    ------
    ValueError
        Without a ``nodeid``, a network or a location; or with a table but without
        ``levels`` and ``storagearea``.
    """
    if isinstance(xy, tuple):
        xy = Point(*xy)
    if xy is None and branchid is not None and chainage is not None:
        xy = self.hydamo.branches.geometry[branchid].interpolate(chainage)

    # Find the nearest node
    if nodeid is not None and not isinstance(nodeid, str):
        raise ValueError("If a nodeid is provided, it should be of type string.")
    if nodeid is None:
        if network is None or xy is None:
            raise ValueError(
                "Without a nodeid, provide the network and a location: xy, or branchid and chainage."
            )
        if len(network._mesh1d.network1d_node_id) == 0:
            raise KeyError(
                "To find the closest node a 1d mesh should be created first."
            )
        nodes1d = np.asarray(
            [
                n
                for n in zip(
                    network._mesh1d.network1d_node_x,
                    network._mesh1d.network1d_node_y,
                    network._mesh1d.network1d_node_id,
                )
            ]
        )
        get_nearest = KDTree(nodes1d[:, 0:2])
        _, idx_nearest = get_nearest.query(xy.coords[:])
        nodeid = f"{float(nodes1d[idx_nearest[0], 0]):12.6f}_{float(nodes1d[idx_nearest[0], 1]):12.6f}"

    if manholeid is None:
        manholeid = nodeid

    base = {
        "type": "storageNode",
        "id": id,
        "name": id if name is None else name,
        "useStreetStorage": usestreetstorage,
        "nodeType": nodetype,
        "useTable": usetable,
        "manholeId": manholeid,
    }
    if nodeid is None:
        cds = {"branchid": branchid, "chainage": chainage}
    else:
        cds = {"nodeid": nodeid}

    if usetable == "false":
        out = {
            **base,
            **cds,
            "bedLevel": bedlevel,
            "area": area,
            "streetLevel": streetlevel,
            "streetStorageArea": streetstoragearea,
            "storageType": storagetype,
        }
    elif usetable == "true":
        if not isinstance(levels, str) or not isinstance(storagearea, str):
            raise ValueError(
                "With usetable='true', provide levels and storagearea as strings of numbers."
            )
        assert len(levels.split()) == len(storagearea.split()), (
            "Number of levels does not equal number of storagearea"
        )
        out = {
            **base,
            **cds,
            "numLevels": len(levels.split()),
            "levels": levels,
            "storageArea": storagearea,
            "interpolate": interpolate,
            "bedLevel": -999.0,
            "area": -999.0,
            "streetLevel": -999.0,
            "streetStorageArea": -999.0,
            "storageType": storagetype,
        }
    else:
        raise ValueError(
            "Value of key 'usetable' is not supported. Either use 'true' or 'false"
        )
    self.storagenodes[id] = remove_nan_values(out)

Structures

Structures of the model, one DataFrame per type.

The add_* methods take keyword arguments only; they correspond to the keywords of the D-Flow FM structure file.

Parameters

hydamo : HyDAMO The HyDAMO object they belong to.

Source code in hydrolib/dhydamo/core/hydamo.py
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
class Structures:
    """Structures of the model, one DataFrame per type.

    The ``add_*`` methods take keyword arguments only; they correspond to the keywords
    of the D-Flow FM structure file.

    Parameters
    ----------
    hydamo : HyDAMO
        The HyDAMO object they belong to.
    """

    def __init__(self, hydamo: HyDAMO) -> None:
        self.hydamo = hydamo
        self.generalstructures_df = pd.DataFrame()
        self.rweirs_df = pd.DataFrame()
        self.orifices_df = pd.DataFrame()
        self.uweirs_df = pd.DataFrame()
        self.culverts_df = pd.DataFrame()
        self.bridges_df = pd.DataFrame()
        self.pumps_df = pd.DataFrame()
        self.compounds_df = pd.DataFrame()

        # Maps management_device.globalid -> generated D-FlowFM structure id,
        # for weirs/orifices that have more than one Kunstwerkopening.
        #
        # Background: a weir's structure id is normally just its HyDAMO code,
        # and is therefore derivable from the static FK chain
        # management_device.kunstwerkopeningid -> opening.globalid ->
        # opening.stuwid -> weirs.globalid (see DRTCModel._resolve_weir_via_opening
        # in core/drtc.py). But when a weir has multiple openings, StructuresIO
        # builds one compound structure per opening and invents the id as
        # f"{weir.code}_{opening_index+1}" - that id only exists once this
        # enumeration has run, so it cannot be derived from HyDAMO data alone.
        # StructuresIO.weirs() populates this dict as it assigns those ids, and
        # DRTCModel falls back to it when the static chain finds no match.
        # Consequently, DRTCModel.from_hydamo()/check_timeseries() only resolve
        # multi-opening weirs correctly if structure conversion (StructuresIO)
        # has already run on this `hydamo` instance.
        self.compound_weir_structure_ids: dict[str, str] = {}

        self.convert = StructuresIO(self)

    def check_branchid_chainage(self, branchid: str, chainage: float) -> None:
        """Raise a ValueError if the branch does not exist or the chainage is outside it.

        Parameters
        ----------
        branchid : str
            Branch id.
        chainage : float
            Chainage on the branch.
        """
        # Check if the ID exists
        if branchid not in self.hydamo.branches["code"]:
            raise ValueError(
                f"branchid {branchid} not present. Give an existing branch."
            )

        # Get the branch
        branch = self.hydamo.branches.geometry[branchid]

        # Check the limits
        if chainage < 0.0:
            raise ValueError(
                f"Chainage {chainage} is outside the branch range (0.0 - {branch.length})."
            )
        if chainage > branch.length:
            raise ValueError(
                f"Chainage {chainage} is outside the branch length (0.0 - {branch.length})."
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_rweir(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        id: str,
        name: str | None = None,
        branchid: str,
        chainage: float,
        crestlevel: float | None = None,
        crestwidth: float | None = None,
        corrcoeff: float | None = None,
        usevelocityheight: bool = True,
        allowedflowdir: str = "both",
    ) -> None:
        """Add a regular weir.

        ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
        to the D-Flow FM keywords of a weir.
        """
        # Check branchid chainage
        self.check_branchid_chainage(branchid, chainage)

        dct = pd.DataFrame(
            {
                "id": id,
                "name": name,
                "branchid": branchid,
                "chainage": chainage,
                "crestlevel": crestlevel,
                "crestwidth": crestwidth,
                "corrcoeff": corrcoeff,
                "usevelocityheight": usevelocityheight,
                "allowedflowdir": allowedflowdir,
            },
            index=[id],
        )
        self.rweirs_df = pd.concat([self.rweirs_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_orifice(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        id: str,
        name: str | None = None,
        branchid: str,
        chainage: float,
        crestlevel: float | None = None,
        crestwidth: float | None = None,
        corrcoeff: float | None = None,
        usevelocityheight: bool = True,
        allowedflowdir: str = "both",
        gateloweredgelevel: float | None = None,
        uselimitflowpos: bool | None = None,
        limitflowpos: float | None = None,
        uselimitflowneg: bool | None = None,
        limitflowneg: float | None = None,
    ) -> None:
        """Add an orifice.

        ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
        to the D-Flow FM keywords of an orifice.
        """
        # Check branchid chainage
        self.check_branchid_chainage(branchid, chainage)

        dct = pd.DataFrame(
            {
                "id": id,
                "name": name,
                "branchid": branchid,
                "chainage": chainage,
                "crestlevel": crestlevel,
                "crestwidth": crestwidth,
                "corrcoeff": corrcoeff,
                "usevelocityheight": usevelocityheight,
                "allowedflowdir": allowedflowdir,
                "gateloweredgelevel": gateloweredgelevel,
                "uselimitflowpos": uselimitflowpos,
                "limitflowpos": limitflowpos,
                "uselimitflowneg": uselimitflowneg,
                "limitflowneg": limitflowneg,
            },
            index=[id],
        )
        self.orifices_df = pd.concat([self.orifices_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_uweir(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        id: str,
        name: str | None = None,
        branchid: str,
        chainage: float,
        crestlevel: float | None = None,
        crestwidth: float | None = None,
        dischargecoeff: float | None = None,
        usevelocityheight: bool = True,
        allowedflowdir: str = "both",
        numlevels: float | None = None,
        yvalues: str | None = None,
        zvalues: str | None = None,
    ) -> None:
        """Add a universal weir.

        ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
        to the D-Flow FM keywords of a universal weir.
        """
        # Check branchid chainage
        self.check_branchid_chainage(branchid, chainage)

        dct = pd.DataFrame(
            {
                "id": id,
                "name": name,
                "branchid": branchid,
                "chainage": chainage,
                "crestlevel": crestlevel,
                "dischargecoeff": dischargecoeff,
                "numlevels": numlevels,
                "allowedflowdir": allowedflowdir,
                "yvalues": yvalues,
                "zvalues": zvalues,
            },
            index=[id],
        )
        self.uweirs_df = pd.concat([self.uweirs_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_bridge(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        id: str,
        name: str | None = None,
        branchid: str,
        chainage: float,
        length: float | None = None,
        inletlosscoeff: float | None = None,
        outletlosscoeff: float | None = None,
        csdefid: str | None = None,
        shift: float | None = None,
        allowedflowdir: str = "both",
        frictiontype: str,
        friction: float | None = None,
    ) -> None:
        """Add a bridge.

        ``id``, ``branchid``, ``chainage`` and ``frictiontype`` (HyDAMO roughness type)
        are required; the other arguments correspond to the D-Flow FM keywords of a
        bridge. ``csdefid`` is the id of its cross section definition.
        """
        # Check branchid chainage
        self.check_branchid_chainage(branchid, chainage)

        # map HyDAMO definition to D-Hydro definition
        frictiontype = self.hydamo.roughness_mapping[frictiontype]

        dct = pd.DataFrame(
            {
                "id": id,
                "name": name,
                "branchid": branchid,
                "chainage": chainage,
                "length": length,
                "inletlosscoeff": inletlosscoeff,
                "outletlosscoeff": outletlosscoeff,
                "csdefid": csdefid,
                "shift": shift,
                "allowedflowdir": allowedflowdir,
                "frictiontype": frictiontype,
                "friction": friction,
            },
            index=[id],
        )
        self.bridges_df = pd.concat([self.bridges_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_culvert(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        id: str,
        name: str | None = None,
        branchid: str,
        chainage: float,
        leftlevel: float | None = None,
        rightlevel: float | None = None,
        length: float | None = None,
        inletlosscoeff: float | None = None,
        outletlosscoeff: float | None = None,
        crosssection: dict,
        allowedflowdir: str = "both",
        valveonoff: int = 0,
        numlosscoeff: int | None = None,
        valveopeningheight: float = 0,
        relopening: list | None = None,
        losscoeff: list | None = None,
        bedfrictiontype: str,
        bedfriction: float,
    ) -> None:
        """Add a culvert, and a cross section definition named after it.

        ``id``, ``branchid``, ``chainage``, ``crosssection``, ``bedfrictiontype``
        (HyDAMO roughness type) and ``bedfriction`` are required; the other arguments
        correspond to the D-Flow FM keywords of a culvert. ``crosssection`` is
        ``{"shape": "circle", "diameter": ...}`` or
        ``{"shape": "rectangle", "height": ..., "width": ..., "closed": ...}``.

        Raises
        ------
        NotImplementedError
            For another cross section shape.
        """
        # Check branchid chainage
        self.check_branchid_chainage(branchid, chainage)

        if crosssection["shape"] == "circle":
            definition = self.hydamo.crosssections.add_circle_definition(
                crosssection["diameter"], bedfrictiontype, bedfriction, name=id
            )
        elif crosssection["shape"] == "rectangle":
            definition = self.hydamo.crosssections.add_rectangle_definition(
                crosssection["height"],
                crosssection["width"],
                crosssection["closed"],
                bedfrictiontype,
                bedfriction,
                name=id,
            )
        else:
            raise NotImplementedError(
                f'Cross section with shape "{crosssection["shape"]}" not implemented.'
            )

        bedfrictiontype = self.hydamo.roughness_mapping[bedfrictiontype]

        dct = pd.DataFrame(
            {
                "id": id,
                "name": name,
                "branchid": branchid,
                "chainage": chainage,
                "rightlevel": rightlevel,
                "leftlevel": leftlevel,
                "length": length,
                "inletlosscoeff": inletlosscoeff,
                "outletlosscoeff": outletlosscoeff,
                "csdefid": definition,
                "bedfrictiontype": bedfrictiontype,
                "bedfriction": bedfriction,
                "allowedflowdir": allowedflowdir,
                "valveonoff": valveonoff,
                "numlosscoeff": numlosscoeff,
                "valveopeningheight": valveopeningheight,
                "relopening": [relopening],
                "losscoeff": [losscoeff],
            },
            index=[id],
        )

        self.culverts_df = pd.concat([self.culverts_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_pump(
        self,
        *,  # keyword-only, so required arguments can follow optional ones in the original order
        id: str,
        name: str | None = None,
        branchid: str,
        chainage: float,
        orientation: str = "positive",
        numstages: int = 1,
        controlside: str = "suctionSide",
        capacity: float | None = None,
        startlevelsuctionside: list | None = None,
        stoplevelsuctionside: list | None = None,
        startleveldeliveryside: list | None = None,
        stopleveldeliveryside: list | None = None,
    ) -> None:
        """Add a pump.

        ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
        to the D-Flow FM keywords of a pump.
        """
        # Check branchid chainage
        self.check_branchid_chainage(branchid, chainage)

        dct = pd.DataFrame(
            {
                "id": id,
                "name": name,
                "branchid": branchid,
                "chainage": chainage,
                "orientation": orientation,
                "numstages": numstages,
                "controlside": controlside,
                "capacity": capacity,
                "startlevelsuctionside": [startlevelsuctionside],
                "stoplevelsuctionside": [stoplevelsuctionside],
                "startleveldeliveryside": [startleveldeliveryside],
                "stopleveldeliveryside": [stopleveldeliveryside],
            },
            index=[id],
        )
        self.pumps_df = pd.concat([self.pumps_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_compound(self, *, id: str, structureids: list) -> None:
        """Add a compound structure of existing structures.

        Parameters
        ----------
        id : str
            Id of the compound structure.
        structureids : list
            Ids of its structures.
        """
        structurestring = ";".join([f"{s}" for s in structureids])
        numstructures = len(structureids)
        dct = pd.DataFrame(
            {
                "id": id,
                "name": id,
                "numstructures": numstructures,
                "structureids": structurestring,
            },
            index=[id],
        )
        self.compounds_df = pd.concat([self.compounds_df, dct], ignore_index=True)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def as_dataframe(
        self,
        generalstructures: bool = False,
        pumps: bool = False,
        rweirs: bool = False,
        bridges: bool = False,
        culverts: bool = False,
        uweirs: bool = False,
        orifices: bool = False,
        compounds: bool = False,
    ) -> pd.DataFrame | None:
        """Return the structures of the given types in one DataFrame, with a column ``structype``.

        Returns None if there are no such structures.
        """
        dfs = []
        for df, descr, add in zip(
            [
                self.generalstructures_df,
                self.culverts_df,
                self.rweirs_df,
                self.bridges_df,
                self.pumps_df,
                self.uweirs_df,
                self.orifices_df,
                self.compounds_df,
            ],
            [
                "generalstructures",
                "culvert",
                "weir",
                "bridge",
                "pump",
                "uweir",
                "orifice",
                "compound",
            ],
            [
                generalstructures,
                culverts,
                rweirs,
                bridges,
                pumps,
                uweirs,
                orifices,
                compounds,
            ],
        ):
            if any(df) and add:
                # Skip columns that are empty for this structure type, so they don't
                # affect the dtype of the combined column (pandas FutureWarning).
                df = df.dropna(axis=1, how="all").copy()
                df.insert(loc=0, column="structype", value=descr, allow_duplicates=True)
                dfs.append(df)

        if len(dfs) > 0:
            return pd.concat(dfs, sort=False, ignore_index=True)
        return None
add_bridge(*, id: str, name: str | None = None, branchid: str, chainage: float, length: float | None = None, inletlosscoeff: float | None = None, outletlosscoeff: float | None = None, csdefid: str | None = None, shift: float | None = None, allowedflowdir: str = 'both', frictiontype: str, friction: float | None = None) -> None

Add a bridge.

id, branchid, chainage and frictiontype (HyDAMO roughness type) are required; the other arguments correspond to the D-Flow FM keywords of a bridge. csdefid is the id of its cross section definition.

Source code in hydrolib/dhydamo/core/hydamo.py
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_bridge(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    id: str,
    name: str | None = None,
    branchid: str,
    chainage: float,
    length: float | None = None,
    inletlosscoeff: float | None = None,
    outletlosscoeff: float | None = None,
    csdefid: str | None = None,
    shift: float | None = None,
    allowedflowdir: str = "both",
    frictiontype: str,
    friction: float | None = None,
) -> None:
    """Add a bridge.

    ``id``, ``branchid``, ``chainage`` and ``frictiontype`` (HyDAMO roughness type)
    are required; the other arguments correspond to the D-Flow FM keywords of a
    bridge. ``csdefid`` is the id of its cross section definition.
    """
    # Check branchid chainage
    self.check_branchid_chainage(branchid, chainage)

    # map HyDAMO definition to D-Hydro definition
    frictiontype = self.hydamo.roughness_mapping[frictiontype]

    dct = pd.DataFrame(
        {
            "id": id,
            "name": name,
            "branchid": branchid,
            "chainage": chainage,
            "length": length,
            "inletlosscoeff": inletlosscoeff,
            "outletlosscoeff": outletlosscoeff,
            "csdefid": csdefid,
            "shift": shift,
            "allowedflowdir": allowedflowdir,
            "frictiontype": frictiontype,
            "friction": friction,
        },
        index=[id],
    )
    self.bridges_df = pd.concat([self.bridges_df, dct], ignore_index=True)
add_compound(*, id: str, structureids: list) -> None

Add a compound structure of existing structures.

Parameters

id : str Id of the compound structure. structureids : list Ids of its structures.

Source code in hydrolib/dhydamo/core/hydamo.py
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_compound(self, *, id: str, structureids: list) -> None:
    """Add a compound structure of existing structures.

    Parameters
    ----------
    id : str
        Id of the compound structure.
    structureids : list
        Ids of its structures.
    """
    structurestring = ";".join([f"{s}" for s in structureids])
    numstructures = len(structureids)
    dct = pd.DataFrame(
        {
            "id": id,
            "name": id,
            "numstructures": numstructures,
            "structureids": structurestring,
        },
        index=[id],
    )
    self.compounds_df = pd.concat([self.compounds_df, dct], ignore_index=True)
add_culvert(*, id: str, name: str | None = None, branchid: str, chainage: float, leftlevel: float | None = None, rightlevel: float | None = None, length: float | None = None, inletlosscoeff: float | None = None, outletlosscoeff: float | None = None, crosssection: dict, allowedflowdir: str = 'both', valveonoff: int = 0, numlosscoeff: int | None = None, valveopeningheight: float = 0, relopening: list | None = None, losscoeff: list | None = None, bedfrictiontype: str, bedfriction: float) -> None

Add a culvert, and a cross section definition named after it.

id, branchid, chainage, crosssection, bedfrictiontype (HyDAMO roughness type) and bedfriction are required; the other arguments correspond to the D-Flow FM keywords of a culvert. crosssection is {"shape": "circle", "diameter": ...} or {"shape": "rectangle", "height": ..., "width": ..., "closed": ...}.

Raises

NotImplementedError For another cross section shape.

Source code in hydrolib/dhydamo/core/hydamo.py
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_culvert(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    id: str,
    name: str | None = None,
    branchid: str,
    chainage: float,
    leftlevel: float | None = None,
    rightlevel: float | None = None,
    length: float | None = None,
    inletlosscoeff: float | None = None,
    outletlosscoeff: float | None = None,
    crosssection: dict,
    allowedflowdir: str = "both",
    valveonoff: int = 0,
    numlosscoeff: int | None = None,
    valveopeningheight: float = 0,
    relopening: list | None = None,
    losscoeff: list | None = None,
    bedfrictiontype: str,
    bedfriction: float,
) -> None:
    """Add a culvert, and a cross section definition named after it.

    ``id``, ``branchid``, ``chainage``, ``crosssection``, ``bedfrictiontype``
    (HyDAMO roughness type) and ``bedfriction`` are required; the other arguments
    correspond to the D-Flow FM keywords of a culvert. ``crosssection`` is
    ``{"shape": "circle", "diameter": ...}`` or
    ``{"shape": "rectangle", "height": ..., "width": ..., "closed": ...}``.

    Raises
    ------
    NotImplementedError
        For another cross section shape.
    """
    # Check branchid chainage
    self.check_branchid_chainage(branchid, chainage)

    if crosssection["shape"] == "circle":
        definition = self.hydamo.crosssections.add_circle_definition(
            crosssection["diameter"], bedfrictiontype, bedfriction, name=id
        )
    elif crosssection["shape"] == "rectangle":
        definition = self.hydamo.crosssections.add_rectangle_definition(
            crosssection["height"],
            crosssection["width"],
            crosssection["closed"],
            bedfrictiontype,
            bedfriction,
            name=id,
        )
    else:
        raise NotImplementedError(
            f'Cross section with shape "{crosssection["shape"]}" not implemented.'
        )

    bedfrictiontype = self.hydamo.roughness_mapping[bedfrictiontype]

    dct = pd.DataFrame(
        {
            "id": id,
            "name": name,
            "branchid": branchid,
            "chainage": chainage,
            "rightlevel": rightlevel,
            "leftlevel": leftlevel,
            "length": length,
            "inletlosscoeff": inletlosscoeff,
            "outletlosscoeff": outletlosscoeff,
            "csdefid": definition,
            "bedfrictiontype": bedfrictiontype,
            "bedfriction": bedfriction,
            "allowedflowdir": allowedflowdir,
            "valveonoff": valveonoff,
            "numlosscoeff": numlosscoeff,
            "valveopeningheight": valveopeningheight,
            "relopening": [relopening],
            "losscoeff": [losscoeff],
        },
        index=[id],
    )

    self.culverts_df = pd.concat([self.culverts_df, dct], ignore_index=True)
add_orifice(*, id: str, name: str | None = None, branchid: str, chainage: float, crestlevel: float | None = None, crestwidth: float | None = None, corrcoeff: float | None = None, usevelocityheight: bool = True, allowedflowdir: str = 'both', gateloweredgelevel: float | None = None, uselimitflowpos: bool | None = None, limitflowpos: float | None = None, uselimitflowneg: bool | None = None, limitflowneg: float | None = None) -> None

Add an orifice.

id, branchid and chainage are required; the other arguments correspond to the D-Flow FM keywords of an orifice.

Source code in hydrolib/dhydamo/core/hydamo.py
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_orifice(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    id: str,
    name: str | None = None,
    branchid: str,
    chainage: float,
    crestlevel: float | None = None,
    crestwidth: float | None = None,
    corrcoeff: float | None = None,
    usevelocityheight: bool = True,
    allowedflowdir: str = "both",
    gateloweredgelevel: float | None = None,
    uselimitflowpos: bool | None = None,
    limitflowpos: float | None = None,
    uselimitflowneg: bool | None = None,
    limitflowneg: float | None = None,
) -> None:
    """Add an orifice.

    ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
    to the D-Flow FM keywords of an orifice.
    """
    # Check branchid chainage
    self.check_branchid_chainage(branchid, chainage)

    dct = pd.DataFrame(
        {
            "id": id,
            "name": name,
            "branchid": branchid,
            "chainage": chainage,
            "crestlevel": crestlevel,
            "crestwidth": crestwidth,
            "corrcoeff": corrcoeff,
            "usevelocityheight": usevelocityheight,
            "allowedflowdir": allowedflowdir,
            "gateloweredgelevel": gateloweredgelevel,
            "uselimitflowpos": uselimitflowpos,
            "limitflowpos": limitflowpos,
            "uselimitflowneg": uselimitflowneg,
            "limitflowneg": limitflowneg,
        },
        index=[id],
    )
    self.orifices_df = pd.concat([self.orifices_df, dct], ignore_index=True)
add_pump(*, id: str, name: str | None = None, branchid: str, chainage: float, orientation: str = 'positive', numstages: int = 1, controlside: str = 'suctionSide', capacity: float | None = None, startlevelsuctionside: list | None = None, stoplevelsuctionside: list | None = None, startleveldeliveryside: list | None = None, stopleveldeliveryside: list | None = None) -> None

Add a pump.

id, branchid and chainage are required; the other arguments correspond to the D-Flow FM keywords of a pump.

Source code in hydrolib/dhydamo/core/hydamo.py
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_pump(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    id: str,
    name: str | None = None,
    branchid: str,
    chainage: float,
    orientation: str = "positive",
    numstages: int = 1,
    controlside: str = "suctionSide",
    capacity: float | None = None,
    startlevelsuctionside: list | None = None,
    stoplevelsuctionside: list | None = None,
    startleveldeliveryside: list | None = None,
    stopleveldeliveryside: list | None = None,
) -> None:
    """Add a pump.

    ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
    to the D-Flow FM keywords of a pump.
    """
    # Check branchid chainage
    self.check_branchid_chainage(branchid, chainage)

    dct = pd.DataFrame(
        {
            "id": id,
            "name": name,
            "branchid": branchid,
            "chainage": chainage,
            "orientation": orientation,
            "numstages": numstages,
            "controlside": controlside,
            "capacity": capacity,
            "startlevelsuctionside": [startlevelsuctionside],
            "stoplevelsuctionside": [stoplevelsuctionside],
            "startleveldeliveryside": [startleveldeliveryside],
            "stopleveldeliveryside": [stopleveldeliveryside],
        },
        index=[id],
    )
    self.pumps_df = pd.concat([self.pumps_df, dct], ignore_index=True)
add_rweir(*, id: str, name: str | None = None, branchid: str, chainage: float, crestlevel: float | None = None, crestwidth: float | None = None, corrcoeff: float | None = None, usevelocityheight: bool = True, allowedflowdir: str = 'both') -> None

Add a regular weir.

id, branchid and chainage are required; the other arguments correspond to the D-Flow FM keywords of a weir.

Source code in hydrolib/dhydamo/core/hydamo.py
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_rweir(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    id: str,
    name: str | None = None,
    branchid: str,
    chainage: float,
    crestlevel: float | None = None,
    crestwidth: float | None = None,
    corrcoeff: float | None = None,
    usevelocityheight: bool = True,
    allowedflowdir: str = "both",
) -> None:
    """Add a regular weir.

    ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
    to the D-Flow FM keywords of a weir.
    """
    # Check branchid chainage
    self.check_branchid_chainage(branchid, chainage)

    dct = pd.DataFrame(
        {
            "id": id,
            "name": name,
            "branchid": branchid,
            "chainage": chainage,
            "crestlevel": crestlevel,
            "crestwidth": crestwidth,
            "corrcoeff": corrcoeff,
            "usevelocityheight": usevelocityheight,
            "allowedflowdir": allowedflowdir,
        },
        index=[id],
    )
    self.rweirs_df = pd.concat([self.rweirs_df, dct], ignore_index=True)
add_uweir(*, id: str, name: str | None = None, branchid: str, chainage: float, crestlevel: float | None = None, crestwidth: float | None = None, dischargecoeff: float | None = None, usevelocityheight: bool = True, allowedflowdir: str = 'both', numlevels: float | None = None, yvalues: str | None = None, zvalues: str | None = None) -> None

Add a universal weir.

id, branchid and chainage are required; the other arguments correspond to the D-Flow FM keywords of a universal weir.

Source code in hydrolib/dhydamo/core/hydamo.py
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_uweir(
    self,
    *,  # keyword-only, so required arguments can follow optional ones in the original order
    id: str,
    name: str | None = None,
    branchid: str,
    chainage: float,
    crestlevel: float | None = None,
    crestwidth: float | None = None,
    dischargecoeff: float | None = None,
    usevelocityheight: bool = True,
    allowedflowdir: str = "both",
    numlevels: float | None = None,
    yvalues: str | None = None,
    zvalues: str | None = None,
) -> None:
    """Add a universal weir.

    ``id``, ``branchid`` and ``chainage`` are required; the other arguments correspond
    to the D-Flow FM keywords of a universal weir.
    """
    # Check branchid chainage
    self.check_branchid_chainage(branchid, chainage)

    dct = pd.DataFrame(
        {
            "id": id,
            "name": name,
            "branchid": branchid,
            "chainage": chainage,
            "crestlevel": crestlevel,
            "dischargecoeff": dischargecoeff,
            "numlevels": numlevels,
            "allowedflowdir": allowedflowdir,
            "yvalues": yvalues,
            "zvalues": zvalues,
        },
        index=[id],
    )
    self.uweirs_df = pd.concat([self.uweirs_df, dct], ignore_index=True)
as_dataframe(generalstructures: bool = False, pumps: bool = False, rweirs: bool = False, bridges: bool = False, culverts: bool = False, uweirs: bool = False, orifices: bool = False, compounds: bool = False) -> pd.DataFrame | None

Return the structures of the given types in one DataFrame, with a column structype.

Returns None if there are no such structures.

Source code in hydrolib/dhydamo/core/hydamo.py
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def as_dataframe(
    self,
    generalstructures: bool = False,
    pumps: bool = False,
    rweirs: bool = False,
    bridges: bool = False,
    culverts: bool = False,
    uweirs: bool = False,
    orifices: bool = False,
    compounds: bool = False,
) -> pd.DataFrame | None:
    """Return the structures of the given types in one DataFrame, with a column ``structype``.

    Returns None if there are no such structures.
    """
    dfs = []
    for df, descr, add in zip(
        [
            self.generalstructures_df,
            self.culverts_df,
            self.rweirs_df,
            self.bridges_df,
            self.pumps_df,
            self.uweirs_df,
            self.orifices_df,
            self.compounds_df,
        ],
        [
            "generalstructures",
            "culvert",
            "weir",
            "bridge",
            "pump",
            "uweir",
            "orifice",
            "compound",
        ],
        [
            generalstructures,
            culverts,
            rweirs,
            bridges,
            pumps,
            uweirs,
            orifices,
            compounds,
        ],
    ):
        if any(df) and add:
            # Skip columns that are empty for this structure type, so they don't
            # affect the dtype of the combined column (pandas FutureWarning).
            df = df.dropna(axis=1, how="all").copy()
            df.insert(loc=0, column="structype", value=descr, allow_duplicates=True)
            dfs.append(df)

    if len(dfs) > 0:
        return pd.concat(dfs, sort=False, ignore_index=True)
    return None
check_branchid_chainage(branchid: str, chainage: float) -> None

Raise a ValueError if the branch does not exist or the chainage is outside it.

Parameters

branchid : str Branch id. chainage : float Chainage on the branch.

Source code in hydrolib/dhydamo/core/hydamo.py
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
def check_branchid_chainage(self, branchid: str, chainage: float) -> None:
    """Raise a ValueError if the branch does not exist or the chainage is outside it.

    Parameters
    ----------
    branchid : str
        Branch id.
    chainage : float
        Chainage on the branch.
    """
    # Check if the ID exists
    if branchid not in self.hydamo.branches["code"]:
        raise ValueError(
            f"branchid {branchid} not present. Give an existing branch."
        )

    # Get the branch
    branch = self.hydamo.branches.geometry[branchid]

    # Check the limits
    if chainage < 0.0:
        raise ValueError(
            f"Chainage {chainage} is outside the branch range (0.0 - {branch.length})."
        )
    if chainage > branch.length:
        raise ValueError(
            f"Chainage {chainage} is outside the branch length (0.0 - {branch.length})."
        )

remove_nan_values(base: Mapping[str, object]) -> dict[str, object]

Return a copy of a mapping without the NaN values.

Parameters

base : Mapping[str, object] Input data, with NaN values.

Returns

dict[str, object] Copy without the float NaN values.

Source code in hydrolib/dhydamo/core/hydamo.py
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
def remove_nan_values(base: Mapping[str, object]) -> dict[str, object]:
    """Return a copy of a mapping without the NaN values.

    Parameters
    ----------
    base : Mapping[str, object]
        Input data, with NaN values.

    Returns
    -------
    dict[str, object]
        Copy without the float NaN values.
    """
    base_copy = dict(base)
    for k, v in base.items():
        if isinstance(v, float) and np.isnan(v):
            base_copy.pop(k)
    return base_copy

relations

Follow the relations between the HyDAMO tables, and plan cascading drops.

The relations themselves, and the cascade paths, are in the data model (hydrolib.dhydamo.core.data_model).

build_cascade_plan(hydamo: HyDAMO, source_table: str, source_index: pd.Index) -> dict[str, pd.Index]

Return the configured, bounded cascade plan for selected rows.

This helper exists to separate deciding what may be deleted from the subsequent dataframe mutation. Cascade policy is expressed as explicit paths in the data model's CASCADE_PATHS. Each configured path starts from the original source_index and is followed independently. Rows reached through the same table are merged by index, and this function never mutates a dataframe.

Parameters

hydamo : HyDAMO Object containing the source and related table dataframes. source_table : str Name of the source dataframe, such as "profile" or "pumpstations". Its cascade paths are looked up in CASCADE_PATHS. source_index : pandas.Index Index labels identifying the source rows from which to build the plan.

Returns

dict[str, pandas.Index] Mapping from each related table name to the unique index labels that would be affected. The source table itself is not included. A table without cascade paths returns an empty dictionary.

Raises

ValueError If source_table is not a HyDAMO table (TABLES or OWN_TABLES), e.g. a typo: read as a table without cascade paths, it would let the caller drop the source rows and leave their related rows behind.

Source code in hydrolib/dhydamo/core/relations.py
 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
def build_cascade_plan(
    hydamo: HyDAMO,
    source_table: str,
    source_index: pd.Index,
) -> dict[str, pd.Index]:
    """Return the configured, bounded cascade plan for selected rows.

    This helper exists to separate deciding *what may be deleted* from the
    subsequent dataframe mutation.  Cascade policy is expressed as explicit
    paths in the data model's ``CASCADE_PATHS``. Each configured path starts from the
    original ``source_index`` and is followed independently. Rows reached
    through the same table are merged by index, and this function never mutates
    a dataframe.

    Parameters
    ----------
    hydamo : HyDAMO
        Object containing the source and related table dataframes.
    source_table : str
        Name of the source dataframe, such as ``"profile"`` or
        ``"pumpstations"``.  Its cascade paths are looked up in
        ``CASCADE_PATHS``.
    source_index : pandas.Index
        Index labels identifying the source rows from which to build the
        plan.

    Returns
    -------
    dict[str, pandas.Index]
        Mapping from each related table name to the unique index labels that
        would be affected.  The source table itself is not included.  A
        table without cascade paths returns an empty dictionary.

    Raises
    ------
    ValueError
        If ``source_table`` is not a HyDAMO table (``TABLES`` or ``OWN_TABLES``),
        e.g. a typo: read as a table without cascade paths, it would let the
        caller drop the source rows and leave their related rows behind.
    """
    if source_table not in TABLES and source_table not in OWN_TABLES:
        raise ValueError(
            f"{source_table!r} is not a HyDAMO table, so its cascade paths are "
            "unknown. Use the table's attribute name, e.g. 'weirs'."
        )
    paths = CASCADE_PATHS.get(source_table, ())
    if not paths:
        return {}

    source = getattr(hydamo, source_table)
    current_source = source.loc[source_index]
    planned: dict[str, pd.Index] = {}

    for path in paths:
        current_table = source_table
        current_rows = current_source

        for relation in path:
            current_table, current_rows = follow_relation(
                hydamo, relation, current_table, current_rows
            )
            if current_table in planned:
                planned[current_table] = planned[current_table].union(
                    current_rows.index
                )
            else:
                planned[current_table] = current_rows.index.copy()

    return planned

follow_relation(hydamo: HyDAMO, relation: Relation, from_table: str, rows: pd.DataFrame) -> tuple[str, pd.DataFrame]

Return rows related to rows through a direct relation.

This helper exists because a relation is defined once in foreign-key direction (child to parent), but callers may start from either endpoint. It selects the correct source and target columns for that direction, so callers do not need duplicate forward and reverse relation definitions.

Matching is performed on relation key columns, not on dataframe indices. For example, following profile_line from profile matches profile.profiellijnid to profile_line.globalid; following it in reverse matches profile_line.globalid to profile.profiellijnid.

Parameters

hydamo : HyDAMO Object containing the dataframe for the other relation endpoint. relation : Relation Direct relation to follow. Its foreign_key belongs to child_table and its parent_key belongs to parent_table. from_table : str Name of the endpoint represented by rows. It must equal either relation.child_table or relation.parent_table. rows : pandas.DataFrame Selected rows from from_table. The relevant relation key must be present as a column. An empty dataframe with that column returns an empty dataframe for the other endpoint.

Returns

tuple[str, pandas.DataFrame] The name of the other endpoint table and the rows whose relation key matches a key value in rows. The target dataframe's index and columns are preserved.

Raises

ValueError If from_table is not an endpoint of relation. KeyError If the required source or target relation key is missing.

Source code in hydrolib/dhydamo/core/relations.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def follow_relation(
    hydamo: HyDAMO,
    relation: Relation,
    from_table: str,
    rows: pd.DataFrame,
) -> tuple[str, pd.DataFrame]:
    """Return rows related to ``rows`` through a direct relation.

    This helper exists because a relation is defined once in foreign-key
    direction (child to parent), but callers may start from either endpoint.
    It selects the correct source and target columns for that direction, so
    callers do not need duplicate forward and reverse relation definitions.

    Matching is performed on relation key columns, not on dataframe indices.
    For example, following ``profile_line`` from ``profile`` matches
    ``profile.profiellijnid`` to ``profile_line.globalid``; following it in
    reverse matches ``profile_line.globalid`` to ``profile.profiellijnid``.

    Parameters
    ----------
    hydamo : HyDAMO
        Object containing the dataframe for the other relation endpoint.
    relation : Relation
        Direct relation to follow.  Its ``foreign_key`` belongs to
        ``child_table`` and its ``parent_key`` belongs to ``parent_table``.
    from_table : str
        Name of the endpoint represented by ``rows``.  It must equal either
        ``relation.child_table`` or ``relation.parent_table``.
    rows : pandas.DataFrame
        Selected rows from ``from_table``.  The relevant relation key must be
        present as a column.  An empty dataframe with that column returns an
        empty dataframe for the other endpoint.

    Returns
    -------
    tuple[str, pandas.DataFrame]
        The name of the other endpoint table and the rows whose relation key
        matches a key value in ``rows``.  The target dataframe's index and
        columns are preserved.

    Raises
    ------
    ValueError
        If ``from_table`` is not an endpoint of ``relation``.
    KeyError
        If the required source or target relation key is missing.
    """
    if from_table == relation.child_table:
        target_table = relation.parent_table
        target_rows = relation.parents_of(rows, getattr(hydamo, target_table))
    elif from_table == relation.parent_table:
        target_table = relation.child_table
        target_rows = relation.children_of(rows, getattr(hydamo, target_table))
    else:
        raise ValueError(
            f"Table {from_table!r} is not an endpoint of relation "
            f"{relation.name!r}; expected {relation.child_table!r} or "
            f"{relation.parent_table!r}"
        )

    return target_table, target_rows