Skip to content

IO

DHyDAMO IO API

Read input data and write D-HYDRO model files.

common

DataFrames and GeoDataFrames with required columns and a geometry type check.

ExtendedDataFrame

Bases: DataFrame

DataFrame with required columns.

The data is replaced in place (see set_data), so references to the object, e.g. from a HyDAMO object, stay valid.

Parameters

required_columns : str or list[str], optional Columns the data must have. Defaults to None: no required columns. *args, **kwargs Passed on to pd.DataFrame.

Source code in hydrolib/dhydamo/io/common.py
 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
class ExtendedDataFrame(pd.DataFrame):
    """DataFrame with required columns.

    The data is replaced in place (see `set_data`), so references to the object, e.g.
    from a HyDAMO object, stay valid.

    Parameters
    ----------
    required_columns : str or list[str], optional
        Columns the data must have. Defaults to None: no required columns.
    *args, **kwargs
        Passed on to ``pd.DataFrame``.
    """

    # _metadata exists at runtime, but pandas-stubs does not declare it
    _metadata = ["required_columns"] + pd.DataFrame._metadata  # type: ignore[attr-defined]

    # args and kwargs are passed on to DataFrame, which pandas also calls with its own arguments
    def __init__(
        self, required_columns: str | list[str] | None = None, *args: Any, **kwargs: Any
    ) -> None:
        super().__init__(*args, **kwargs)

        if required_columns is None:
            required_columns = []

        self.required_columns = (
            required_columns[:]
            if isinstance(required_columns, list)
            else [required_columns]
        )

    def delete_all(self) -> None:
        """Remove all rows, in place."""
        if not self.empty:
            self.iloc[:, 0] = np.nan
            # inplace: returning a copy of an ExtendedDataFrame gives a plain DataFrame
            self.dropna(inplace=True)  # noqa: PD002

    def _drop_columns_not_in(self, data: pd.DataFrame) -> None:
        """Remove the columns that *data* doesn't have, in place."""
        stale = [column for column in self.columns if column not in data.columns]
        if stale:
            # inplace: returning a copy loses the Extended class
            self.drop(columns=stale, inplace=True)  # noqa: PD002

    def set_data(self, df: pd.DataFrame, index_col: Hashable | None) -> None:
        """Replace the data with that of a DataFrame, in place.

        Rows and columns that *df* doesn't have are removed.

        Parameters
        ----------
        df : pd.DataFrame
            New data.
        index_col : Hashable or None
            Column to use as index; None keeps the index of ``df``.

        Raises
        ------
        KeyError
            If a required column is missing.
        """
        if not self.empty:
            self.delete_all()
        self._drop_columns_not_in(df)

        # Copy content
        for col, values in df.items():
            self[col] = values.to_numpy()

        if index_col is None:
            self.index = df.index
            self.index.name = df.index.name

        else:
            self.index = df[index_col]
            self.index.name = index_col

        # Check columns and types
        self._check_columns()

    def add_data(self, df: pd.DataFrame) -> None:
        """Append the rows of a DataFrame, in place.

        Parameters
        ----------
        df : pd.DataFrame
            Rows to add.

        Raises
        ------
        KeyError
            If ``df`` has columns that this DataFrame does not have.
        """
        if not np.isin(df.columns, self.columns).all():
            raise KeyError(
                "The new df contains columns that are not present in the current df."
            )

        # Concatenate data
        current = pd.DataFrame(self.values, index=self.index, columns=self.columns)
        newdf = pd.concat([current, df], ignore_index=False, sort=False)

        # Empty current df
        self.delete_all()

        # Add values again
        self.set_data(newdf, index_col=self.index.name)

    def _check_columns(self) -> None:
        """Raise a KeyError if a required column is missing."""
        present_columns = self.columns.tolist()
        for i, column in enumerate(self.required_columns):
            if column not in present_columns:
                raise KeyError(
                    'Column "{}" not found. Got {}, Expected at least {}'.format(
                        column,
                        ", ".join(present_columns),
                        ", ".join(self.required_columns),
                    )
                )

    def read_gpkg_layer(
        self,
        gpkg_path: str | Path,
        layer_name: str,
        column_mapping: dict | None = None,
        index_col: str | None = None,
    ) -> None:
        """Read a GeoPackage table into this object (deprecated).

        Use ``HyDAMO.load_from_gpkg()`` to load DAMO data.
        """
        warnings.warn(
            "read_gpkg_layer() is deprecated and will be removed in a future release. "
            "Use HyDAMO.load_from_gpkg() to load DAMO-formatted GeoPackages.",
            DeprecationWarning,
            stacklevel=2,
        )
        self._read_gpkg_layer(
            gpkg_path=gpkg_path,
            layer_name=layer_name,
            column_mapping=column_mapping,
            index_col=index_col,
        )

    def _read_gpkg_layer(
        self,
        gpkg_path: str | Path,
        layer_name: str,
        column_mapping: dict | None = None,
        index_col: str | None = None,
        fill_from_globalid: str | None = None,
        identity_column: str | None = None,
        # the arguments for geometry layers, which a table ignores
        **kwargs: object,
    ) -> None:
        """Read a GeoPackage layer as a table, without its geometry.

        The column names are made lowercase; the layer name is matched case-insensitively.
        """
        if not Path(gpkg_path).exists():
            raise OSError(f'File not found: "{gpkg_path}"')

        if isinstance(gpkg_path, Path):
            gpkg_path = str(gpkg_path)

        if layer_name.lower() not in map(
            str.lower, gpd.list_layers(gpkg_path).name.tolist()
        ):
            raise ValueError(f'Layer "{layer_name}" does not exist in: "{gpkg_path}"')

        layer = gpd.read_file(gpkg_path, layer=layer_name, engine="pyogrio")
        columns = [col.lower() for col in layer.columns]
        layer.columns = columns
        if "geometry" in layer.columns:
            layer = layer.drop("geometry", axis=1)

        df = layer
        if column_mapping is not None:
            df = _rename_columns(df, column_mapping, layer_name)

        if fill_from_globalid is not None:
            _fill_from_globalid(df, fill_from_globalid, layer_name)

        if identity_column is not None:
            _check_identity(df, identity_column)

        if index_col is not None:
            _make_index_unique(df, index_col)

        # Add data to class GeoDataFrame
        self.set_data(df, index_col=index_col)
add_data(df: pd.DataFrame) -> None

Append the rows of a DataFrame, in place.

Parameters

df : pd.DataFrame Rows to add.

Raises

KeyError If df has columns that this DataFrame does not have.

Source code in hydrolib/dhydamo/io/common.py
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
def add_data(self, df: pd.DataFrame) -> None:
    """Append the rows of a DataFrame, in place.

    Parameters
    ----------
    df : pd.DataFrame
        Rows to add.

    Raises
    ------
    KeyError
        If ``df`` has columns that this DataFrame does not have.
    """
    if not np.isin(df.columns, self.columns).all():
        raise KeyError(
            "The new df contains columns that are not present in the current df."
        )

    # Concatenate data
    current = pd.DataFrame(self.values, index=self.index, columns=self.columns)
    newdf = pd.concat([current, df], ignore_index=False, sort=False)

    # Empty current df
    self.delete_all()

    # Add values again
    self.set_data(newdf, index_col=self.index.name)
delete_all() -> None

Remove all rows, in place.

Source code in hydrolib/dhydamo/io/common.py
852
853
854
855
856
857
def delete_all(self) -> None:
    """Remove all rows, in place."""
    if not self.empty:
        self.iloc[:, 0] = np.nan
        # inplace: returning a copy of an ExtendedDataFrame gives a plain DataFrame
        self.dropna(inplace=True)  # noqa: PD002
read_gpkg_layer(gpkg_path: str | Path, layer_name: str, column_mapping: dict | None = None, index_col: str | None = None) -> None

Read a GeoPackage table into this object (deprecated).

Use HyDAMO.load_from_gpkg() to load DAMO data.

Source code in hydrolib/dhydamo/io/common.py
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
def read_gpkg_layer(
    self,
    gpkg_path: str | Path,
    layer_name: str,
    column_mapping: dict | None = None,
    index_col: str | None = None,
) -> None:
    """Read a GeoPackage table into this object (deprecated).

    Use ``HyDAMO.load_from_gpkg()`` to load DAMO data.
    """
    warnings.warn(
        "read_gpkg_layer() is deprecated and will be removed in a future release. "
        "Use HyDAMO.load_from_gpkg() to load DAMO-formatted GeoPackages.",
        DeprecationWarning,
        stacklevel=2,
    )
    self._read_gpkg_layer(
        gpkg_path=gpkg_path,
        layer_name=layer_name,
        column_mapping=column_mapping,
        index_col=index_col,
    )
set_data(df: pd.DataFrame, index_col: Hashable | None) -> None

Replace the data with that of a DataFrame, in place.

Rows and columns that df doesn't have are removed.

Parameters

df : pd.DataFrame New data. index_col : Hashable or None Column to use as index; None keeps the index of df.

Raises

KeyError If a required column is missing.

Source code in hydrolib/dhydamo/io/common.py
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
def set_data(self, df: pd.DataFrame, index_col: Hashable | None) -> None:
    """Replace the data with that of a DataFrame, in place.

    Rows and columns that *df* doesn't have are removed.

    Parameters
    ----------
    df : pd.DataFrame
        New data.
    index_col : Hashable or None
        Column to use as index; None keeps the index of ``df``.

    Raises
    ------
    KeyError
        If a required column is missing.
    """
    if not self.empty:
        self.delete_all()
    self._drop_columns_not_in(df)

    # Copy content
    for col, values in df.items():
        self[col] = values.to_numpy()

    if index_col is None:
        self.index = df.index
        self.index.name = df.index.name

    else:
        self.index = df[index_col]
        self.index.name = index_col

    # Check columns and types
    self._check_columns()

ExtendedGeoDataFrame

Bases: GeoDataFrame

GeoDataFrame with required columns and a required geometry type.

The data is replaced in place (see set_data), so references to the object, e.g. from a HyDAMO object, stay valid.

Parameters

geotype : type[BaseGeometry] or UnionType Required geometry class, or a union of classes such as Polygon | MultiPolygon. required_columns : str or list[str], optional Columns the data must have. Defaults to None: no required columns. logger : ModuleType or logging.Logger, optional Not used. Defaults to the logging module. *args, **kwargs Passed on to gpd.GeoDataFrame.

Source code in hydrolib/dhydamo/io/common.py
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
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
class ExtendedGeoDataFrame(gpd.GeoDataFrame):
    """GeoDataFrame with required columns and a required geometry type.

    The data is replaced in place (see `set_data`), so references to the object, e.g.
    from a HyDAMO object, stay valid.

    Parameters
    ----------
    geotype : type[BaseGeometry] or UnionType
        Required geometry class, or a union of classes such as ``Polygon | MultiPolygon``.
    required_columns : str or list[str], optional
        Columns the data must have. Defaults to None: no required columns.
    logger : ModuleType or logging.Logger, optional
        Not used. Defaults to the ``logging`` module.
    *args, **kwargs
        Passed on to ``gpd.GeoDataFrame``.
    """

    # normal properties
    # _metadata exists at runtime, but types-geopandas does not declare it
    _metadata = ["required_columns", "geotype"] + gpd.GeoDataFrame._metadata  # type: ignore[attr-defined]

    # args and kwargs are passed on to GeoDataFrame, which pandas also calls with its own arguments
    def __init__(
        self,
        # a geometry class, or a union of them such as Polygon | MultiPolygon
        geotype: type[BaseGeometry] | UnionType,
        required_columns: str | list[str] | None = None,
        logger: ModuleType | logging.Logger = logging,
        *args: Any,
        **kwargs: Any,
    ) -> None:
        # Check type
        if required_columns is None:
            required_columns = []
        elif not isinstance(required_columns, list):
            required_columns = [required_columns]

        # Add required columns to column list
        if "columns" in kwargs:
            kwargs["columns"] += required_columns
        else:
            kwargs["columns"] = required_columns

        super().__init__(*args, **kwargs)

        self.required_columns = required_columns[:]
        self.geotype = geotype

    # pandas-stubs marks DataFrame.copy as final; this override keeps the geotype and required columns
    def copy(self, deep: bool = True) -> ExtendedGeoDataFrame:  # type: ignore[misc]
        """Return a copy that keeps the geometry type and the required columns."""
        index = self.index.tolist() if not deep else deepcopy(self.index.tolist())
        columns = self.columns.tolist() if not deep else deepcopy(self.columns.tolist())

        edf = ExtendedGeoDataFrame(
            geotype=self.geotype,
            required_columns=[],
            index=index,
            columns=columns,
        )
        edf.required_columns.extend(self.required_columns[:])
        edf.loc[:, :] = self.values if not deep else deepcopy(self.values)

        return edf

    def delete_all(self) -> None:
        """Remove all rows, in place."""
        if not self.empty:
            # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
            self.drop(self.index, inplace=True)  # noqa: PD002

    def read_shp(
        self,
        path: str | Path,
        index_col: str | None = None,
        column_mapping: dict | None = None,
        check_columns: bool = True,
        proj_crs: CRS | str | None = None,
        clip: Polygon | MultiPolygon | None = None,
        check_geotype: bool = True,
        id_col: str = "code",
        filter_cols: bool = False,
        filter_rows: dict[str, object] | None = None,
    ) -> None:
        """Read a shapefile (or another file geopandas can read) into this object, in place.

        Features without a geometry are dropped.

        Parameters
        ----------
        path : str or Path
            File to read.
        index_col : str, optional
            Column to use as index. Defaults to None: keep the index of the file.
        column_mapping : dict, optional
            Renames columns, from old to new name. Defaults to None.
        check_columns : bool, optional
            Check that the required columns are present. Defaults to True.
        proj_crs : CRS or str, optional
            Reproject to this CRS. Defaults to None: keep the CRS of the file.
        clip : Polygon or MultiPolygon, optional
            Keep only the features that intersect this geometry. Defaults to None.
        check_geotype : bool, optional
            Check the geometry type. Defaults to True.
        id_col : str, optional
            Not used. Defaults to ``"code"``.
        filter_cols : bool, optional
            Keep only the required columns. Defaults to False.
        filter_rows : dict[str, object], optional
            Keep only the rows with these values, as ``{column: value}``. Defaults to None.

        Raises
        ------
        OSError
            If the file has no features with a geometry.
        """
        # Read GeoDataFrame
        gdf = gpd.read_file(path)

        # Only keep required columns
        if filter_cols:
            logger.info("Filtering required column keys")
            gdf = gdf.drop(
                columns=gdf.columns[~gdf.columns.isin(self.required_columns)]
            )

        # filter out rows on key/value pairs if required
        if filter_rows is not None:
            logger.info("Filter rows using key value pairs")
            filtered = (gdf[list(filter_rows)] == pd.Series(filter_rows)).all(axis=1)
            gdf = gdf[filtered]

        # Drop features without geometry
        total_features = len(gdf)
        gdf = gdf.drop(gdf.index[gdf.geometry.isna()])  # temporary fix
        missing_features = len(gdf.index[gdf.geometry.isna()])
        logger.debug(
            f"{missing_features} out of {total_features} do not have a geometry"
        )

        # Rename columns:
        if column_mapping is not None:
            gdf = gdf.rename(columns=column_mapping)

        # Check number of entries
        if gdf.empty:
            raise OSError("Imported shapefile contains no rows.")

        # Add data to class GeoDataFrame
        self.set_data(
            gdf,
            index_col=index_col,
            check_columns=check_columns,
            check_geotype=check_geotype,
        )

        # Clip if extent is provided
        if clip is not None:
            self.clip(clip)

        # To re-project CRS system to projected CRS, first all empty geometries should be dropped
        if proj_crs is not None:
            self.check_projection(proj_crs)
        else:
            logger.debug("No projected CRS is given in ini-file")

    def _drop_columns_not_in(self, data: pd.DataFrame) -> None:
        """Remove the columns that *data* doesn't have, in place."""
        stale = [column for column in self.columns if column not in data.columns]
        if stale:
            # inplace: returning a copy loses the Extended class
            self.drop(columns=stale, inplace=True)  # noqa: PD002

    def set_data(
        self,
        gdf: gpd.GeoDataFrame,
        index_col: str | None = None,
        check_columns: bool = True,
        check_geotype: bool = True,
    ) -> None:
        """Replace the data with that of a GeoDataFrame, in place.

        Rows and columns that *gdf* doesn't have are removed.

        Parameters
        ----------
        gdf : gpd.GeoDataFrame
            New data.
        index_col : str, optional
            Column to use as index. Defaults to None: keep the index of ``gdf``.
        check_columns : bool, optional
            Check that the required columns are present. Defaults to True.
        check_geotype : bool, optional
            Check the geometry type. Defaults to True.

        Raises
        ------
        KeyError
            If a required column is missing.
        TypeError
            If a geometry is not of the required type.
        """
        if not self.empty:
            self.delete_all()
        self._drop_columns_not_in(gdf)

        # Check columns
        if check_columns:
            self._check_columns(gdf)

        # Copy content
        for col, values in gdf.items():
            if str(values.dtype) == "geometry":
                # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
                self.set_geometry(values.to_numpy(), inplace=True)
            else:
                self[col] = values.to_numpy()

        if index_col is None:
            self.index = gdf.index
            self.index.name = gdf.index.name

        else:
            self.index = gdf[index_col]
            self.index.name = index_col

        # Check geometry types
        if check_geotype:
            self._check_geotype()

    def _check_columns(self, gdf: pd.DataFrame) -> None:
        """Raise a KeyError if a required column is missing from ``gdf``."""
        present_columns = gdf.columns.tolist()
        for column in self.required_columns:
            # TODO: geopackages don't support very long names. Only give an error if the first 25
            # characters don't occur, otherwise lengthen the column name (not implemented yet).
            if column not in present_columns:
                raise KeyError(
                    'Column "{}" not found. Got {}, Expected at least {}'.format(
                        column,
                        ", ".join(present_columns),
                        ", ".join(self.required_columns),
                    )
                )

    def _check_geotype(self) -> None:
        """Raise a TypeError if a geometry is not of the required type."""
        if not all(isinstance(geo, self.geotype) for geo in self.geometry):
            # a union like Polygon | MultiPolygon has no usable __name__ (Python 3.14 gives "Union")
            if isinstance(self.geotype, type):
                geotype_name = self.geotype.__name__
            else:
                geotype_name = str(self.geotype)
            found_types = self.geometry.type.unique().tolist()
            raise TypeError(
                f'Geometrytype "{geotype_name}" required. The input shapefile has geometry type(s) {found_types}.'
            )

    def show_gpkg(self, gpkg_path: str | Path) -> None:
        """Log the layers of a GeoPackage, with their geometry type and size.

        Parameters
        ----------
        gpkg_path : str or Path
            GeoPackage to show.

        Raises
        ------
        OSError
            If the file does not exist.
        """
        if not Path(gpkg_path).exists():
            raise OSError(f'File not found: "{gpkg_path}"')

        if isinstance(gpkg_path, Path):
            gpkg_path = str(gpkg_path)

        layerlist = gpd.list_layers(gpkg_path).name.tolist()
        logger.info(
            "Content of gpkg-file %s, containing %d layers:",
            gpkg_path,
            len(layerlist),
        )
        logger.info(
            "\tINDEX\t|\tNAME                        \t|\tGEOM_TYPE      \t|\t NFEATURES\t|\t   NFIELDS"
        )
        for laynum, layer_name in enumerate(layerlist):
            layer = gpd.read_file(gpkg_path, layer=layer_name)
            if layer.empty:
                logger.warning('Layer "%s" is empty.', layer_name)
                continue

            nfields = len(layer.columns)
            nfeatures = layer.shape[0]

            if isinstance(layer, gpd.GeoDataFrame):
                geom_type = layer.geom_type.iloc[0]
                if geom_type is None:
                    geom_type = "None"
            else:
                geom_type = "None"

            logger.info(
                "\t%5d\t|\t%30s\t|\t%s\t|\t%10d\t|\t%10d",
                laynum,
                layer_name,
                geom_type,
                nfeatures,
                nfields,
            )

    def read_gpkg_layer(
        self,
        gpkg_path: str | Path,
        layer_name: str,
        index_col: str | None = None,
        groupby_column: str | None = None,
        order_column: str | None = None,
        id_col: str = "code",
        column_mapping: dict | None = None,
        check_columns: bool = True,
        check_geotype: bool = True,
        clip: Polygon | MultiPolygon | None = None,
        cliptype: str = "select",
        check_3d: bool = True,
    ) -> None:
        """Read a GeoPackage layer into this object (deprecated).

        Use ``HyDAMO.load_from_gpkg()`` to load DAMO data.
        """
        warnings.warn(
            "read_gpkg_layer() is deprecated and will be removed in a future release. "
            "Use HyDAMO.load_from_gpkg() to load DAMO-formatted GeoPackages.",
            DeprecationWarning,
            stacklevel=2,
        )
        self._read_gpkg_layer(
            gpkg_path=gpkg_path,
            layer_name=layer_name,
            index_col=index_col,
            groupby_column=groupby_column,
            order_column=order_column,
            id_col=id_col,
            column_mapping=column_mapping,
            check_columns=check_columns,
            check_geotype=check_geotype,
            clip=clip,
            cliptype=cliptype,
            check_3d=check_3d,
        )

    def _read_gpkg_layer(
        self,
        gpkg_path: str | Path,
        layer_name: str,
        index_col: str | None = None,
        groupby_column: str | None = None,
        order_column: str | None = None,
        id_col: str = "code",
        column_mapping: dict | None = None,
        fill_from_globalid: str | None = None,
        identity_column: str | None = None,
        check_columns: bool = True,
        check_geotype: bool = True,
        clip: Polygon | MultiPolygon | None = None,
        cliptype: str = "select",
        check_3d: bool = True,
    ) -> None:
        if not Path(gpkg_path).exists():
            raise OSError(f'File not found: "{gpkg_path}"')

        if isinstance(gpkg_path, Path):
            gpkg_path = str(gpkg_path)

        if layer_name.lower() not in map(
            str.lower, gpd.list_layers(gpkg_path).name.tolist()
        ):
            raise ValueError(f'Layer "{layer_name}" does not exist in: "{gpkg_path}"')

        layer = gpd.read_file(gpkg_path, layer=layer_name, engine="pyogrio")
        layer.columns = [col.lower() for col in layer.columns]
        # Rename first, so that the renames also apply to the columns that group
        # and order points into lines.
        if column_mapping is not None:
            layer = _rename_columns(layer, column_mapping, layer_name)
        columns = list(layer.columns)

        # Create geodataframe
        if groupby_column is not None:
            fields, geometries = _points_to_lines(
                layer, groupby_column, order_column, check_3d
            )
            gdf = gpd.GeoDataFrame(fields, columns=columns, geometry=geometries)
        else:
            gdf = gpd.GeoDataFrame(layer, columns=columns, geometry=layer.geometry)

        if fill_from_globalid is not None:
            _fill_from_globalid(gdf, fill_from_globalid, layer_name)

        if identity_column is not None:
            _check_identity(gdf, identity_column)

        if index_col is not None:
            _make_index_unique(gdf, index_col)

        # Add data to class GeoDataFrame
        self.set_data(
            gdf,
            index_col=index_col,
            check_columns=check_columns,
            check_geotype=check_geotype,
        )

        if clip is not None:
            self.clip(geometry=clip, cliptype=cliptype)

    # replaces GeoDataFrame.clip with an in-place clip or selection, with its own arguments;
    # mypy reports the override on the def line and on each incompatible argument
    def clip(  # type: ignore[override]
        self,
        geometry: Polygon | MultiPolygon,  # type: ignore[override]
        cliptype: str = "select",  # type: ignore[override]
        clip_and_drop: bool = True,
    ) -> None:
        """Keep only the features within a geometry, in place.

        Parameters
        ----------
        geometry : Polygon or MultiPolygon
            Area to keep.
        cliptype : str, optional
            ``"select"`` keeps the features that intersect the area, unchanged;
            ``"clip"`` cuts them off at its boundary. Defaults to ``"select"``.
        clip_and_drop : bool, optional
            With ``"clip"``: keep only parts of the original geometry types (e.g. no
            points where a line touches the boundary), and merge the parts of one
            feature into one multi-geometry. Defaults to True.

        Raises
        ------
        TypeError
            If the geometry is not a Polygon or MultiPolygon.
        ValueError
            If the cliptype is unknown, or no features are left.
        """
        if not isinstance(geometry, (Polygon, MultiPolygon)):
            raise TypeError("Expected geometry of type Polygon or MultiPolygon")

        # Clip if needed
        if cliptype == "clip":
            pre_geomtypes = self.geom_type.unique().tolist()
            if "Polygon" in pre_geomtypes and "MultiPolygon" not in pre_geomtypes:
                pre_geomtypes.append("MultiPolygon")
            if "MultiPolygon" in pre_geomtypes and "Polygon" not in pre_geomtypes:
                pre_geomtypes.append("Polygon")
            gdf = gpd.clip(self, gpd.GeoDataFrame(geometry=[geometry], crs=self.crs))
            if clip_and_drop:
                # Reduce to allowed
                gdf = gpd.GeoDataFrame(gdf, crs=gdf.crs)
                rem = gdf[~gdf.geom_type.isin(pre_geomtypes)]
                # Explode to deal with geometry collections
                rem = rem.explode(ignore_index=False, index_parts=False)
                rem = rem[rem.geom_type.isin(pre_geomtypes)]
                gdf = gpd.GeoDataFrame(
                    pd.concat(
                        [gdf[gdf.geom_type.isin(pre_geomtypes)], rem],
                        ignore_index=False,
                    ),
                    crs=gdf.crs,
                )
                # Merge duplicate indices to single multigeometry
                keep = []
                for idx, group in gdf.groupby(level=0, sort=False):
                    if len(group) == 1:
                        keep.append(group.iloc[0].copy())
                    elif len(group) > 1:
                        row = group.iloc[0].copy()
                        geoms = group.geometry.tolist()
                        geom = shapely.union_all(geoms)
                        if geom.geom_type not in pre_geomtypes:
                            logger.warning(
                                "Cannot deduplicate index '%s': clipping resulted in split geometries, using the first geometry.",
                                idx,
                            )
                            geom = geoms[0]
                        row["geometry"] = geom
                        keep.append(row)
                gdf = gpd.GeoDataFrame(keep, crs=gdf.crs)
        elif cliptype == "select":
            gdf = self.loc[self.intersects(geometry).to_numpy()]
        else:
            raise ValueError(
                f"Cliptype {cliptype} not recognized. Use 'clip' or 'select'."
            )
        if gdf.empty:
            raise ValueError("Found no features within extent geometry.")

        self.set_data(gdf)

    def check_projection(self, crs_out: CRS | str) -> None:
        """Reproject to a CRS, in place, if the data has another CRS."""
        if crs_out != self.crs:
            # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
            self.to_crs(crs_out, inplace=True)
        else:
            logger.info("OSM data has same projection as projected crs in ini-file")

    def branch_to_prof(
        self,
        offset: float = 0.0,
        vertex_end: bool = False,
        rename_col: str | None = None,
        prefix: str = "",
        suffix: str = "",
    ) -> ExtendedGeoDataFrame:
        """Return a point on each branch, e.g. to place a profile.

        Parameters
        ----------
        offset : float, optional
            Distance of the point from the start of the branch, or from its end with
            ``vertex_end``. Stored in the column ``offset``. Defaults to 0.0.
        vertex_end : bool, optional
            Measure ``offset`` from the end of the branch. Defaults to False.
        rename_col : str, optional
            Column with the branch id. It is copied to ``branch_id``, and the column gets
            ``prefix`` and ``suffix`` around the id. Defaults to None.
        prefix, suffix : str, optional
            Added around the id in ``rename_col``. Default to ``""``.

        Returns
        -------
        ExtendedGeoDataFrame
            Copy of the branches, with the points as geometry.

        Raises
        ------
        ValueError
            If ``rename_col`` does not exist.
        """
        gdf_out = self.copy()

        # interpolate over feature geometries
        # the offset from the end of each branch, or from its start
        chainage: pd.Series | float = offset
        if vertex_end:
            chainage = self.length - offset
        p = self.interpolate(chainage)
        gdf_out.geometry = p
        gdf_out["offset"] = chainage

        if rename_col is not None:
            try:
                gdf_out["branch_id"] = gdf_out[rename_col]
                gdf_out[rename_col] = [
                    f"{prefix}{g[1][rename_col]}{suffix}" for g in self.iterrows()
                ]
            except KeyError as err:
                raise ValueError(
                    f"Column rename with '{rename_col}' did not succeed."
                ) from err

        return gdf_out

    def merge_columns(self, col1: str, col2: str, rename_col: str) -> None:
        """Add two columns and store the result in a column, in place.

        Strings are concatenated, numbers are added.

        Parameters
        ----------
        col1, col2 : str
            Names of the columns to add.
        rename_col : str
            Name of the column for the result; an existing column is overwritten.

        Raises
        ------
        ValueError
            If a column does not exist, or the columns cannot be added.
        """
        missing = [col for col in (col1, col2) if col not in self.columns]
        if missing:
            raise ValueError(
                f"Cannot merge columns '{col1}' and '{col2}': {', '.join(repr(col) for col in missing)} not found."
            )
        try:
            self[rename_col] = self[col1] + self[col2]
        except TypeError as err:
            raise ValueError(
                f"Merge of columns '{col1}' and '{col2}' did not succeed."
            ) from err

    def snap_to_branch(
        self, branches: gpd.GeoDataFrame, snap_method: str, maxdist: float = 5
    ) -> None:
        """Find the nearest branch for each geometry, see `spatial.find_nearest_branch`.

        Fills the columns ``branch_id`` and ``branch_offset``, in place.

        Parameters
        ----------
        branches : gpd.GeoDataFrame
            Branches, with the branch id as index.
        snap_method : str
            ``"overal"``, ``"centroid"``, ``"ends"`` or ``"intersecting"``.
        maxdist : float, optional
            Maximum distance to a branch. Defaults to 5.
        """
        spatial.find_nearest_branch(
            branches=branches, geometries=self, method=snap_method, maxdist=maxdist
        )
branch_to_prof(offset: float = 0.0, vertex_end: bool = False, rename_col: str | None = None, prefix: str = '', suffix: str = '') -> ExtendedGeoDataFrame

Return a point on each branch, e.g. to place a profile.

Parameters

offset : float, optional Distance of the point from the start of the branch, or from its end with vertex_end. Stored in the column offset. Defaults to 0.0. vertex_end : bool, optional Measure offset from the end of the branch. Defaults to False. rename_col : str, optional Column with the branch id. It is copied to branch_id, and the column gets prefix and suffix around the id. Defaults to None. prefix, suffix : str, optional Added around the id in rename_col. Default to "".

Returns

ExtendedGeoDataFrame Copy of the branches, with the points as geometry.

Raises

ValueError If rename_col does not exist.

Source code in hydrolib/dhydamo/io/common.py
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
def branch_to_prof(
    self,
    offset: float = 0.0,
    vertex_end: bool = False,
    rename_col: str | None = None,
    prefix: str = "",
    suffix: str = "",
) -> ExtendedGeoDataFrame:
    """Return a point on each branch, e.g. to place a profile.

    Parameters
    ----------
    offset : float, optional
        Distance of the point from the start of the branch, or from its end with
        ``vertex_end``. Stored in the column ``offset``. Defaults to 0.0.
    vertex_end : bool, optional
        Measure ``offset`` from the end of the branch. Defaults to False.
    rename_col : str, optional
        Column with the branch id. It is copied to ``branch_id``, and the column gets
        ``prefix`` and ``suffix`` around the id. Defaults to None.
    prefix, suffix : str, optional
        Added around the id in ``rename_col``. Default to ``""``.

    Returns
    -------
    ExtendedGeoDataFrame
        Copy of the branches, with the points as geometry.

    Raises
    ------
    ValueError
        If ``rename_col`` does not exist.
    """
    gdf_out = self.copy()

    # interpolate over feature geometries
    # the offset from the end of each branch, or from its start
    chainage: pd.Series | float = offset
    if vertex_end:
        chainage = self.length - offset
    p = self.interpolate(chainage)
    gdf_out.geometry = p
    gdf_out["offset"] = chainage

    if rename_col is not None:
        try:
            gdf_out["branch_id"] = gdf_out[rename_col]
            gdf_out[rename_col] = [
                f"{prefix}{g[1][rename_col]}{suffix}" for g in self.iterrows()
            ]
        except KeyError as err:
            raise ValueError(
                f"Column rename with '{rename_col}' did not succeed."
            ) from err

    return gdf_out
check_projection(crs_out: CRS | str) -> None

Reproject to a CRS, in place, if the data has another CRS.

Source code in hydrolib/dhydamo/io/common.py
705
706
707
708
709
710
711
def check_projection(self, crs_out: CRS | str) -> None:
    """Reproject to a CRS, in place, if the data has another CRS."""
    if crs_out != self.crs:
        # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
        self.to_crs(crs_out, inplace=True)
    else:
        logger.info("OSM data has same projection as projected crs in ini-file")
clip(geometry: Polygon | MultiPolygon, cliptype: str = 'select', clip_and_drop: bool = True) -> None

Keep only the features within a geometry, in place.

Parameters

geometry : Polygon or MultiPolygon Area to keep. cliptype : str, optional "select" keeps the features that intersect the area, unchanged; "clip" cuts them off at its boundary. Defaults to "select". clip_and_drop : bool, optional With "clip": keep only parts of the original geometry types (e.g. no points where a line touches the boundary), and merge the parts of one feature into one multi-geometry. Defaults to True.

Raises

TypeError If the geometry is not a Polygon or MultiPolygon. ValueError If the cliptype is unknown, or no features are left.

Source code in hydrolib/dhydamo/io/common.py
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
def clip(  # type: ignore[override]
    self,
    geometry: Polygon | MultiPolygon,  # type: ignore[override]
    cliptype: str = "select",  # type: ignore[override]
    clip_and_drop: bool = True,
) -> None:
    """Keep only the features within a geometry, in place.

    Parameters
    ----------
    geometry : Polygon or MultiPolygon
        Area to keep.
    cliptype : str, optional
        ``"select"`` keeps the features that intersect the area, unchanged;
        ``"clip"`` cuts them off at its boundary. Defaults to ``"select"``.
    clip_and_drop : bool, optional
        With ``"clip"``: keep only parts of the original geometry types (e.g. no
        points where a line touches the boundary), and merge the parts of one
        feature into one multi-geometry. Defaults to True.

    Raises
    ------
    TypeError
        If the geometry is not a Polygon or MultiPolygon.
    ValueError
        If the cliptype is unknown, or no features are left.
    """
    if not isinstance(geometry, (Polygon, MultiPolygon)):
        raise TypeError("Expected geometry of type Polygon or MultiPolygon")

    # Clip if needed
    if cliptype == "clip":
        pre_geomtypes = self.geom_type.unique().tolist()
        if "Polygon" in pre_geomtypes and "MultiPolygon" not in pre_geomtypes:
            pre_geomtypes.append("MultiPolygon")
        if "MultiPolygon" in pre_geomtypes and "Polygon" not in pre_geomtypes:
            pre_geomtypes.append("Polygon")
        gdf = gpd.clip(self, gpd.GeoDataFrame(geometry=[geometry], crs=self.crs))
        if clip_and_drop:
            # Reduce to allowed
            gdf = gpd.GeoDataFrame(gdf, crs=gdf.crs)
            rem = gdf[~gdf.geom_type.isin(pre_geomtypes)]
            # Explode to deal with geometry collections
            rem = rem.explode(ignore_index=False, index_parts=False)
            rem = rem[rem.geom_type.isin(pre_geomtypes)]
            gdf = gpd.GeoDataFrame(
                pd.concat(
                    [gdf[gdf.geom_type.isin(pre_geomtypes)], rem],
                    ignore_index=False,
                ),
                crs=gdf.crs,
            )
            # Merge duplicate indices to single multigeometry
            keep = []
            for idx, group in gdf.groupby(level=0, sort=False):
                if len(group) == 1:
                    keep.append(group.iloc[0].copy())
                elif len(group) > 1:
                    row = group.iloc[0].copy()
                    geoms = group.geometry.tolist()
                    geom = shapely.union_all(geoms)
                    if geom.geom_type not in pre_geomtypes:
                        logger.warning(
                            "Cannot deduplicate index '%s': clipping resulted in split geometries, using the first geometry.",
                            idx,
                        )
                        geom = geoms[0]
                    row["geometry"] = geom
                    keep.append(row)
            gdf = gpd.GeoDataFrame(keep, crs=gdf.crs)
    elif cliptype == "select":
        gdf = self.loc[self.intersects(geometry).to_numpy()]
    else:
        raise ValueError(
            f"Cliptype {cliptype} not recognized. Use 'clip' or 'select'."
        )
    if gdf.empty:
        raise ValueError("Found no features within extent geometry.")

    self.set_data(gdf)
copy(deep: bool = True) -> ExtendedGeoDataFrame

Return a copy that keeps the geometry type and the required columns.

Source code in hydrolib/dhydamo/io/common.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def copy(self, deep: bool = True) -> ExtendedGeoDataFrame:  # type: ignore[misc]
    """Return a copy that keeps the geometry type and the required columns."""
    index = self.index.tolist() if not deep else deepcopy(self.index.tolist())
    columns = self.columns.tolist() if not deep else deepcopy(self.columns.tolist())

    edf = ExtendedGeoDataFrame(
        geotype=self.geotype,
        required_columns=[],
        index=index,
        columns=columns,
    )
    edf.required_columns.extend(self.required_columns[:])
    edf.loc[:, :] = self.values if not deep else deepcopy(self.values)

    return edf
delete_all() -> None

Remove all rows, in place.

Source code in hydrolib/dhydamo/io/common.py
271
272
273
274
275
def delete_all(self) -> None:
    """Remove all rows, in place."""
    if not self.empty:
        # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
        self.drop(self.index, inplace=True)  # noqa: PD002
merge_columns(col1: str, col2: str, rename_col: str) -> None

Add two columns and store the result in a column, in place.

Strings are concatenated, numbers are added.

Parameters

col1, col2 : str Names of the columns to add. rename_col : str Name of the column for the result; an existing column is overwritten.

Raises

ValueError If a column does not exist, or the columns cannot be added.

Source code in hydrolib/dhydamo/io/common.py
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
def merge_columns(self, col1: str, col2: str, rename_col: str) -> None:
    """Add two columns and store the result in a column, in place.

    Strings are concatenated, numbers are added.

    Parameters
    ----------
    col1, col2 : str
        Names of the columns to add.
    rename_col : str
        Name of the column for the result; an existing column is overwritten.

    Raises
    ------
    ValueError
        If a column does not exist, or the columns cannot be added.
    """
    missing = [col for col in (col1, col2) if col not in self.columns]
    if missing:
        raise ValueError(
            f"Cannot merge columns '{col1}' and '{col2}': {', '.join(repr(col) for col in missing)} not found."
        )
    try:
        self[rename_col] = self[col1] + self[col2]
    except TypeError as err:
        raise ValueError(
            f"Merge of columns '{col1}' and '{col2}' did not succeed."
        ) from err
read_gpkg_layer(gpkg_path: str | Path, layer_name: str, index_col: str | None = None, groupby_column: str | None = None, order_column: str | None = None, id_col: str = 'code', column_mapping: dict | None = None, check_columns: bool = True, check_geotype: bool = True, clip: Polygon | MultiPolygon | None = None, cliptype: str = 'select', check_3d: bool = True) -> None

Read a GeoPackage layer into this object (deprecated).

Use HyDAMO.load_from_gpkg() to load DAMO data.

Source code in hydrolib/dhydamo/io/common.py
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
def read_gpkg_layer(
    self,
    gpkg_path: str | Path,
    layer_name: str,
    index_col: str | None = None,
    groupby_column: str | None = None,
    order_column: str | None = None,
    id_col: str = "code",
    column_mapping: dict | None = None,
    check_columns: bool = True,
    check_geotype: bool = True,
    clip: Polygon | MultiPolygon | None = None,
    cliptype: str = "select",
    check_3d: bool = True,
) -> None:
    """Read a GeoPackage layer into this object (deprecated).

    Use ``HyDAMO.load_from_gpkg()`` to load DAMO data.
    """
    warnings.warn(
        "read_gpkg_layer() is deprecated and will be removed in a future release. "
        "Use HyDAMO.load_from_gpkg() to load DAMO-formatted GeoPackages.",
        DeprecationWarning,
        stacklevel=2,
    )
    self._read_gpkg_layer(
        gpkg_path=gpkg_path,
        layer_name=layer_name,
        index_col=index_col,
        groupby_column=groupby_column,
        order_column=order_column,
        id_col=id_col,
        column_mapping=column_mapping,
        check_columns=check_columns,
        check_geotype=check_geotype,
        clip=clip,
        cliptype=cliptype,
        check_3d=check_3d,
    )
read_shp(path: str | Path, index_col: str | None = None, column_mapping: dict | None = None, check_columns: bool = True, proj_crs: CRS | str | None = None, clip: Polygon | MultiPolygon | None = None, check_geotype: bool = True, id_col: str = 'code', filter_cols: bool = False, filter_rows: dict[str, object] | None = None) -> None

Read a shapefile (or another file geopandas can read) into this object, in place.

Features without a geometry are dropped.

Parameters

path : str or Path File to read. index_col : str, optional Column to use as index. Defaults to None: keep the index of the file. column_mapping : dict, optional Renames columns, from old to new name. Defaults to None. check_columns : bool, optional Check that the required columns are present. Defaults to True. proj_crs : CRS or str, optional Reproject to this CRS. Defaults to None: keep the CRS of the file. clip : Polygon or MultiPolygon, optional Keep only the features that intersect this geometry. Defaults to None. check_geotype : bool, optional Check the geometry type. Defaults to True. id_col : str, optional Not used. Defaults to "code". filter_cols : bool, optional Keep only the required columns. Defaults to False. filter_rows : dict[str, object], optional Keep only the rows with these values, as {column: value}. Defaults to None.

Raises

OSError If the file has no features with a geometry.

Source code in hydrolib/dhydamo/io/common.py
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
def read_shp(
    self,
    path: str | Path,
    index_col: str | None = None,
    column_mapping: dict | None = None,
    check_columns: bool = True,
    proj_crs: CRS | str | None = None,
    clip: Polygon | MultiPolygon | None = None,
    check_geotype: bool = True,
    id_col: str = "code",
    filter_cols: bool = False,
    filter_rows: dict[str, object] | None = None,
) -> None:
    """Read a shapefile (or another file geopandas can read) into this object, in place.

    Features without a geometry are dropped.

    Parameters
    ----------
    path : str or Path
        File to read.
    index_col : str, optional
        Column to use as index. Defaults to None: keep the index of the file.
    column_mapping : dict, optional
        Renames columns, from old to new name. Defaults to None.
    check_columns : bool, optional
        Check that the required columns are present. Defaults to True.
    proj_crs : CRS or str, optional
        Reproject to this CRS. Defaults to None: keep the CRS of the file.
    clip : Polygon or MultiPolygon, optional
        Keep only the features that intersect this geometry. Defaults to None.
    check_geotype : bool, optional
        Check the geometry type. Defaults to True.
    id_col : str, optional
        Not used. Defaults to ``"code"``.
    filter_cols : bool, optional
        Keep only the required columns. Defaults to False.
    filter_rows : dict[str, object], optional
        Keep only the rows with these values, as ``{column: value}``. Defaults to None.

    Raises
    ------
    OSError
        If the file has no features with a geometry.
    """
    # Read GeoDataFrame
    gdf = gpd.read_file(path)

    # Only keep required columns
    if filter_cols:
        logger.info("Filtering required column keys")
        gdf = gdf.drop(
            columns=gdf.columns[~gdf.columns.isin(self.required_columns)]
        )

    # filter out rows on key/value pairs if required
    if filter_rows is not None:
        logger.info("Filter rows using key value pairs")
        filtered = (gdf[list(filter_rows)] == pd.Series(filter_rows)).all(axis=1)
        gdf = gdf[filtered]

    # Drop features without geometry
    total_features = len(gdf)
    gdf = gdf.drop(gdf.index[gdf.geometry.isna()])  # temporary fix
    missing_features = len(gdf.index[gdf.geometry.isna()])
    logger.debug(
        f"{missing_features} out of {total_features} do not have a geometry"
    )

    # Rename columns:
    if column_mapping is not None:
        gdf = gdf.rename(columns=column_mapping)

    # Check number of entries
    if gdf.empty:
        raise OSError("Imported shapefile contains no rows.")

    # Add data to class GeoDataFrame
    self.set_data(
        gdf,
        index_col=index_col,
        check_columns=check_columns,
        check_geotype=check_geotype,
    )

    # Clip if extent is provided
    if clip is not None:
        self.clip(clip)

    # To re-project CRS system to projected CRS, first all empty geometries should be dropped
    if proj_crs is not None:
        self.check_projection(proj_crs)
    else:
        logger.debug("No projected CRS is given in ini-file")
set_data(gdf: gpd.GeoDataFrame, index_col: str | None = None, check_columns: bool = True, check_geotype: bool = True) -> None

Replace the data with that of a GeoDataFrame, in place.

Rows and columns that gdf doesn't have are removed.

Parameters

gdf : gpd.GeoDataFrame New data. index_col : str, optional Column to use as index. Defaults to None: keep the index of gdf. check_columns : bool, optional Check that the required columns are present. Defaults to True. check_geotype : bool, optional Check the geometry type. Defaults to True.

Raises

KeyError If a required column is missing. TypeError If a geometry is not of the required type.

Source code in hydrolib/dhydamo/io/common.py
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
def set_data(
    self,
    gdf: gpd.GeoDataFrame,
    index_col: str | None = None,
    check_columns: bool = True,
    check_geotype: bool = True,
) -> None:
    """Replace the data with that of a GeoDataFrame, in place.

    Rows and columns that *gdf* doesn't have are removed.

    Parameters
    ----------
    gdf : gpd.GeoDataFrame
        New data.
    index_col : str, optional
        Column to use as index. Defaults to None: keep the index of ``gdf``.
    check_columns : bool, optional
        Check that the required columns are present. Defaults to True.
    check_geotype : bool, optional
        Check the geometry type. Defaults to True.

    Raises
    ------
    KeyError
        If a required column is missing.
    TypeError
        If a geometry is not of the required type.
    """
    if not self.empty:
        self.delete_all()
    self._drop_columns_not_in(gdf)

    # Check columns
    if check_columns:
        self._check_columns(gdf)

    # Copy content
    for col, values in gdf.items():
        if str(values.dtype) == "geometry":
            # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
            self.set_geometry(values.to_numpy(), inplace=True)
        else:
            self[col] = values.to_numpy()

    if index_col is None:
        self.index = gdf.index
        self.index.name = gdf.index.name

    else:
        self.index = gdf[index_col]
        self.index.name = index_col

    # Check geometry types
    if check_geotype:
        self._check_geotype()
show_gpkg(gpkg_path: str | Path) -> None

Log the layers of a GeoPackage, with their geometry type and size.

Parameters

gpkg_path : str or Path GeoPackage to show.

Raises

OSError If the file does not exist.

Source code in hydrolib/dhydamo/io/common.py
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
def show_gpkg(self, gpkg_path: str | Path) -> None:
    """Log the layers of a GeoPackage, with their geometry type and size.

    Parameters
    ----------
    gpkg_path : str or Path
        GeoPackage to show.

    Raises
    ------
    OSError
        If the file does not exist.
    """
    if not Path(gpkg_path).exists():
        raise OSError(f'File not found: "{gpkg_path}"')

    if isinstance(gpkg_path, Path):
        gpkg_path = str(gpkg_path)

    layerlist = gpd.list_layers(gpkg_path).name.tolist()
    logger.info(
        "Content of gpkg-file %s, containing %d layers:",
        gpkg_path,
        len(layerlist),
    )
    logger.info(
        "\tINDEX\t|\tNAME                        \t|\tGEOM_TYPE      \t|\t NFEATURES\t|\t   NFIELDS"
    )
    for laynum, layer_name in enumerate(layerlist):
        layer = gpd.read_file(gpkg_path, layer=layer_name)
        if layer.empty:
            logger.warning('Layer "%s" is empty.', layer_name)
            continue

        nfields = len(layer.columns)
        nfeatures = layer.shape[0]

        if isinstance(layer, gpd.GeoDataFrame):
            geom_type = layer.geom_type.iloc[0]
            if geom_type is None:
                geom_type = "None"
        else:
            geom_type = "None"

        logger.info(
            "\t%5d\t|\t%30s\t|\t%s\t|\t%10d\t|\t%10d",
            laynum,
            layer_name,
            geom_type,
            nfeatures,
            nfields,
        )
snap_to_branch(branches: gpd.GeoDataFrame, snap_method: str, maxdist: float = 5) -> None

Find the nearest branch for each geometry, see spatial.find_nearest_branch.

Fills the columns branch_id and branch_offset, in place.

Parameters

branches : gpd.GeoDataFrame Branches, with the branch id as index. snap_method : str "overal", "centroid", "ends" or "intersecting". maxdist : float, optional Maximum distance to a branch. Defaults to 5.

Source code in hydrolib/dhydamo/io/common.py
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
def snap_to_branch(
    self, branches: gpd.GeoDataFrame, snap_method: str, maxdist: float = 5
) -> None:
    """Find the nearest branch for each geometry, see `spatial.find_nearest_branch`.

    Fills the columns ``branch_id`` and ``branch_offset``, in place.

    Parameters
    ----------
    branches : gpd.GeoDataFrame
        Branches, with the branch id as index.
    snap_method : str
        ``"overal"``, ``"centroid"``, ``"ends"`` or ``"intersecting"``.
    maxdist : float, optional
        Maximum distance to a branch. Defaults to 5.
    """
    spatial.find_nearest_branch(
        branches=branches, geometries=self, method=snap_method, maxdist=maxdist
    )

damo_versions

Load a DAMO GeoPackage of a supported version into HYDROLIB's data model.

steps holds the renames of each DAMO version, and loader reads a GeoPackage into HYDROLIB's data model (hydrolib.dhydamo.core.data_model): the HyDAMO tables under their DAMO 2.2 names and HYDROLIB's extensions. explain reports how a layer becomes a HyDAMO table, from the same data.

SourceLayer dataclass

Where a HyDAMO table comes from in a file of one DAMO version.

Parameters

layer : str The layer in that version. renames : dict[str, str] {column in that version: DAMO 2.2 name}, for the renamed columns.

Source code in hydrolib/dhydamo/io/damo_versions/steps.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass(frozen=True)
class SourceLayer:
    """Where a HyDAMO table comes from in a file of one DAMO version.

    Parameters
    ----------
    layer : str
        The layer in that version.
    renames : dict[str, str]
        ``{column in that version: DAMO 2.2 name}``, for the renamed columns.
    """

    layer: str
    renames: dict[str, str]

explain

Report how a layer of a DAMO GeoPackage becomes a HyDAMO table.

The report is built from the data model (hydrolib.dhydamo.core.data_model) and the version steps (steps) only, the same data loading uses, so it can't drift from the loading code: the layers and column names come from steps.source_layers, as loading gets them. It explains the contract, not one file: it doesn't open a GeoPackage, so it can't say which columns a version's schema has.

explain_table(table: str, version: str) -> str

Return a text report of how HyDAMO table is loaded from a DAMO version file.

The report gives the layer the table is read from and the steps that moved it; per declared column, whether the loaded table requires it, its name in version, the steps that renamed it, and whether the loader fills or derives it; HYDROLIB's extensions with their reasons; the values the code compares against; and the relations the table takes part in.

Parameters

table : str HyDAMO attribute of the table, e.g. "management_device". version : str DAMO version, one of SUPPORTED_HYDAMO_VERSIONS, e.g. "2.5".

Returns

str The report, one table, several lines.

Raises

ValueError If version is not supported, or table isn't a HyDAMO table.

Examples

print(explain_table("management_device", "2.5")) # doctest: +SKIP

Source code in hydrolib/dhydamo/io/damo_versions/explain.py
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
def explain_table(table: str, version: str) -> str:
    """Return a text report of how HyDAMO *table* is loaded from a DAMO *version* file.

    The report gives the layer the table is read from and the steps that moved it;
    per declared column, whether the loaded table requires it, its name in *version*,
    the steps that renamed it, and whether the loader fills or derives it; HYDROLIB's
    extensions with their reasons; the values the code compares against; and the
    relations the table takes part in.

    Parameters
    ----------
    table : str
        HyDAMO attribute of the table, e.g. ``"management_device"``.
    version : str
        DAMO version, one of `SUPPORTED_HYDAMO_VERSIONS`, e.g. ``"2.5"``.

    Returns
    -------
    str
        The report, one table, several lines.

    Raises
    ------
    ValueError
        If *version* is not supported, or *table* isn't a HyDAMO table.

    Examples
    --------
    >>> print(explain_table("management_device", "2.5"))  # doctest: +SKIP
    """
    source = source_layers(version)
    if table not in TABLES:
        raise ValueError(
            f'"{table}" is not a HyDAMO table; the tables are {", ".join(TABLES)}.'
        )
    definition = TABLES[table]
    # The table's layer and renames in each version from 2.2 up to *version*
    versions = SUPPORTED_HYDAMO_VERSIONS[: SUPPORTED_HYDAMO_VERSIONS.index(version) + 1]
    history = {v: source_layers(v)[table] for v in versions}
    lines = [f'{table} <- layer "{source[table].layer}" (DAMO {version})']
    lines.append(_INDENT + _layer_history(history))
    if definition.group_by is not None:
        lines.append(
            _INDENT + f"Points grouped into lines by {definition.group_by}, ordered "
            f"by {definition.order_by}."
        )
    lines.append("")
    lines.extend(_column_lines(definition, history, version))
    lines.extend(_extension_lines(table))
    lines.extend(_value_lines(definition))
    lines.extend(_relation_lines(table))
    return "\n".join(lines)
explain_tables(version: str) -> str

Return the report of explain_table for every HyDAMO table, for DAMO version.

Parameters

version : str DAMO version, one of SUPPORTED_HYDAMO_VERSIONS, e.g. "2.6".

Returns

str The reports, in the order of data_model.TABLES, separated by a blank line.

Raises

ValueError If version is not supported.

Source code in hydrolib/dhydamo/io/damo_versions/explain.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def explain_tables(version: str) -> str:
    """Return the report of `explain_table` for every HyDAMO table, for DAMO *version*.

    Parameters
    ----------
    version : str
        DAMO version, one of `SUPPORTED_HYDAMO_VERSIONS`, e.g. ``"2.6"``.

    Returns
    -------
    str
        The reports, in the order of `data_model.TABLES`, separated by a blank line.

    Raises
    ------
    ValueError
        If *version* is not supported.
    """
    return "\n\n".join(explain_table(table, version) for table in TABLES)

explain_table(table: str, version: str) -> str

Return a text report of how HyDAMO table is loaded from a DAMO version file.

The report gives the layer the table is read from and the steps that moved it; per declared column, whether the loaded table requires it, its name in version, the steps that renamed it, and whether the loader fills or derives it; HYDROLIB's extensions with their reasons; the values the code compares against; and the relations the table takes part in.

Parameters

table : str HyDAMO attribute of the table, e.g. "management_device". version : str DAMO version, one of SUPPORTED_HYDAMO_VERSIONS, e.g. "2.5".

Returns

str The report, one table, several lines.

Raises

ValueError If version is not supported, or table isn't a HyDAMO table.

Examples

print(explain_table("management_device", "2.5")) # doctest: +SKIP

Source code in hydrolib/dhydamo/io/damo_versions/explain.py
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
def explain_table(table: str, version: str) -> str:
    """Return a text report of how HyDAMO *table* is loaded from a DAMO *version* file.

    The report gives the layer the table is read from and the steps that moved it;
    per declared column, whether the loaded table requires it, its name in *version*,
    the steps that renamed it, and whether the loader fills or derives it; HYDROLIB's
    extensions with their reasons; the values the code compares against; and the
    relations the table takes part in.

    Parameters
    ----------
    table : str
        HyDAMO attribute of the table, e.g. ``"management_device"``.
    version : str
        DAMO version, one of `SUPPORTED_HYDAMO_VERSIONS`, e.g. ``"2.5"``.

    Returns
    -------
    str
        The report, one table, several lines.

    Raises
    ------
    ValueError
        If *version* is not supported, or *table* isn't a HyDAMO table.

    Examples
    --------
    >>> print(explain_table("management_device", "2.5"))  # doctest: +SKIP
    """
    source = source_layers(version)
    if table not in TABLES:
        raise ValueError(
            f'"{table}" is not a HyDAMO table; the tables are {", ".join(TABLES)}.'
        )
    definition = TABLES[table]
    # The table's layer and renames in each version from 2.2 up to *version*
    versions = SUPPORTED_HYDAMO_VERSIONS[: SUPPORTED_HYDAMO_VERSIONS.index(version) + 1]
    history = {v: source_layers(v)[table] for v in versions}
    lines = [f'{table} <- layer "{source[table].layer}" (DAMO {version})']
    lines.append(_INDENT + _layer_history(history))
    if definition.group_by is not None:
        lines.append(
            _INDENT + f"Points grouped into lines by {definition.group_by}, ordered "
            f"by {definition.order_by}."
        )
    lines.append("")
    lines.extend(_column_lines(definition, history, version))
    lines.extend(_extension_lines(table))
    lines.extend(_value_lines(definition))
    lines.extend(_relation_lines(table))
    return "\n".join(lines)

explain_tables(version: str) -> str

Return the report of explain_table for every HyDAMO table, for DAMO version.

Parameters

version : str DAMO version, one of SUPPORTED_HYDAMO_VERSIONS, e.g. "2.6".

Returns

str The reports, in the order of data_model.TABLES, separated by a blank line.

Raises

ValueError If version is not supported.

Source code in hydrolib/dhydamo/io/damo_versions/explain.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def explain_tables(version: str) -> str:
    """Return the report of `explain_table` for every HyDAMO table, for DAMO *version*.

    Parameters
    ----------
    version : str
        DAMO version, one of `SUPPORTED_HYDAMO_VERSIONS`, e.g. ``"2.6"``.

    Returns
    -------
    str
        The reports, in the order of `data_model.TABLES`, separated by a blank line.

    Raises
    ------
    ValueError
        If *version* is not supported.
    """
    return "\n\n".join(explain_table(table, version) for table in TABLES)

load_layers(hydamo: HyDAMO, gpkg_path: str | Path, sources: dict[str, SourceLayer], hydamo_version: str, clip_layers: dict | None = None, check_3d: bool = True) -> None

Read the layers of a DAMO GeoPackage into hydamo, under their DAMO 2.2 names.

Then rewrites values and computes the derived columns, as declared on the tables (Column.rewrite, Table.derived_columns).

Parameters

hydamo : HyDAMO The HyDAMO instance whose tables are filled. gpkg_path : str or Path Path to the GeoPackage. sources : dict[str, SourceLayer] The layers and renames of the GeoPackage's DAMO version, from source_layers. hydamo_version : str DAMO version of the GeoPackage, for the messages. clip_layers : dict, optional Per-table spatial clip: maps a HyDAMO attribute to a (geometry, cliptype) tuple. Tables absent from the dict are loaded without clipping. check_3d : bool Whether to require Z coordinates on profile points when grouping them into lines. Default is True.

Raises

KeyError If a loaded layer lacks a required column (data_model.TABLES); the message names the layer and the column. Raised at once. ValueError If a layer that is not optional is missing, or a layer of points lacks the column that groups or orders them into lines; the message names the layer. Also if a table's identity, or the column that groups points into lines, is empty in some rows; the message names the layer and the first rows. These errors are collected over all layers and raised together, one line each.

Source code in hydrolib/dhydamo/io/damo_versions/loader.py
 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
 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
def load_layers(
    hydamo: HyDAMO,
    gpkg_path: str | Path,
    sources: dict[str, SourceLayer],
    hydamo_version: str,
    clip_layers: dict | None = None,
    check_3d: bool = True,
) -> None:
    """Read the layers of a DAMO GeoPackage into *hydamo*, under their DAMO 2.2 names.

    Then rewrites values and computes the derived columns, as declared on the tables
    (`Column.rewrite`, `Table.derived_columns`).

    Parameters
    ----------
    hydamo : HyDAMO
        The ``HyDAMO`` instance whose tables are filled.
    gpkg_path : str or Path
        Path to the GeoPackage.
    sources : dict[str, SourceLayer]
        The layers and renames of the GeoPackage's DAMO version, from
        `source_layers`.
    hydamo_version : str
        DAMO version of the GeoPackage, for the messages.
    clip_layers : dict, optional
        Per-table spatial clip: maps a HyDAMO attribute to a ``(geometry, cliptype)``
        tuple. Tables absent from the dict are loaded without clipping.
    check_3d : bool
        Whether to require Z coordinates on profile points when grouping them into
        lines. Default is ``True``.

    Raises
    ------
    KeyError
        If a loaded layer lacks a required column (`data_model.TABLES`); the message
        names the layer and the column. Raised at once.
    ValueError
        If a layer that is not optional is missing, or a layer of points lacks the
        column that groups or orders them into lines; the message names the layer.
        Also if a table's identity, or the column that groups points into lines, is
        empty in some rows; the message names the layer and the first rows. These
        errors are collected over all layers and raised together, one line each.
    """
    gpkg_path = Path(gpkg_path)
    available_layers = {
        layer_name.lower(): layer_name
        for layer_name in gpd.list_layers(gpkg_path).name.tolist()
    }
    errors: list[str] = []
    for name, source in sources.items():
        table = TABLES[name]
        actual_layer = available_layers.get(source.layer.lower())
        if actual_layer is None:
            if table.optional_layer:
                logger.info(
                    'Skipping optional HyDAMO layer "%s" for DAMO %s.',
                    source.layer,
                    hydamo_version,
                )
                continue
            errors.append(
                f'Missing required HyDAMO layer "{source.layer}" for DAMO {hydamo_version}.'
            )
            continue

        kwargs: dict = {
            "gpkg_path": gpkg_path,
            "layer_name": actual_layer,
            "index_col": table.identity_column,
            "column_mapping": source.renames or None,
            "fill_from_globalid": table.column_filled_from_globalid,
            "identity_column": table.identity_column,
            "check_geotype": table.check_geotype,
            "check_3d": check_3d,
        }
        if table.group_by is not None:
            kwargs["groupby_column"] = table.group_by
        if table.order_by is not None:
            kwargs["order_column"] = table.order_by
        if clip_layers and name in clip_layers:
            kwargs["clip"], kwargs["cliptype"] = clip_layers[name]

        # The table's own messages don't name the layer.
        prefix = f'HyDAMO layer "{actual_layer}" (DAMO {hydamo_version}): '
        try:
            getattr(hydamo, name)._read_gpkg_layer(**kwargs)
        except KeyError as exc:
            # A missing column raises at once, as a KeyError, so callers that catch
            # it still do.
            raise KeyError(prefix + str(exc.args[0])) from exc
        except ValueError as exc:
            # e.g. empty codes: collected, so all layers are reported at once
            errors.append(prefix + str(exc))
            continue
        if not _KEEP_UNDECLARED_COLUMNS:
            _drop_undeclared_columns(hydamo, name, table)
    if errors:
        raise ValueError("\n".join(errors))

    _rewrite_values(hydamo)
    # The derived columns of the tables (Table.derived_columns)
    _derive_profile_code(hydamo)
    _derive_boundary_node(hydamo)
    _derive_weir_crest(hydamo)
    _derive_gate_height(hydamo)

loader

Load a DAMO GeoPackage of any supported version into HYDROLIB's data model.

load_layers(hydamo: HyDAMO, gpkg_path: str | Path, sources: dict[str, SourceLayer], hydamo_version: str, clip_layers: dict | None = None, check_3d: bool = True) -> None

Read the layers of a DAMO GeoPackage into hydamo, under their DAMO 2.2 names.

Then rewrites values and computes the derived columns, as declared on the tables (Column.rewrite, Table.derived_columns).

Parameters

hydamo : HyDAMO The HyDAMO instance whose tables are filled. gpkg_path : str or Path Path to the GeoPackage. sources : dict[str, SourceLayer] The layers and renames of the GeoPackage's DAMO version, from source_layers. hydamo_version : str DAMO version of the GeoPackage, for the messages. clip_layers : dict, optional Per-table spatial clip: maps a HyDAMO attribute to a (geometry, cliptype) tuple. Tables absent from the dict are loaded without clipping. check_3d : bool Whether to require Z coordinates on profile points when grouping them into lines. Default is True.

Raises

KeyError If a loaded layer lacks a required column (data_model.TABLES); the message names the layer and the column. Raised at once. ValueError If a layer that is not optional is missing, or a layer of points lacks the column that groups or orders them into lines; the message names the layer. Also if a table's identity, or the column that groups points into lines, is empty in some rows; the message names the layer and the first rows. These errors are collected over all layers and raised together, one line each.

Source code in hydrolib/dhydamo/io/damo_versions/loader.py
 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
 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
def load_layers(
    hydamo: HyDAMO,
    gpkg_path: str | Path,
    sources: dict[str, SourceLayer],
    hydamo_version: str,
    clip_layers: dict | None = None,
    check_3d: bool = True,
) -> None:
    """Read the layers of a DAMO GeoPackage into *hydamo*, under their DAMO 2.2 names.

    Then rewrites values and computes the derived columns, as declared on the tables
    (`Column.rewrite`, `Table.derived_columns`).

    Parameters
    ----------
    hydamo : HyDAMO
        The ``HyDAMO`` instance whose tables are filled.
    gpkg_path : str or Path
        Path to the GeoPackage.
    sources : dict[str, SourceLayer]
        The layers and renames of the GeoPackage's DAMO version, from
        `source_layers`.
    hydamo_version : str
        DAMO version of the GeoPackage, for the messages.
    clip_layers : dict, optional
        Per-table spatial clip: maps a HyDAMO attribute to a ``(geometry, cliptype)``
        tuple. Tables absent from the dict are loaded without clipping.
    check_3d : bool
        Whether to require Z coordinates on profile points when grouping them into
        lines. Default is ``True``.

    Raises
    ------
    KeyError
        If a loaded layer lacks a required column (`data_model.TABLES`); the message
        names the layer and the column. Raised at once.
    ValueError
        If a layer that is not optional is missing, or a layer of points lacks the
        column that groups or orders them into lines; the message names the layer.
        Also if a table's identity, or the column that groups points into lines, is
        empty in some rows; the message names the layer and the first rows. These
        errors are collected over all layers and raised together, one line each.
    """
    gpkg_path = Path(gpkg_path)
    available_layers = {
        layer_name.lower(): layer_name
        for layer_name in gpd.list_layers(gpkg_path).name.tolist()
    }
    errors: list[str] = []
    for name, source in sources.items():
        table = TABLES[name]
        actual_layer = available_layers.get(source.layer.lower())
        if actual_layer is None:
            if table.optional_layer:
                logger.info(
                    'Skipping optional HyDAMO layer "%s" for DAMO %s.',
                    source.layer,
                    hydamo_version,
                )
                continue
            errors.append(
                f'Missing required HyDAMO layer "{source.layer}" for DAMO {hydamo_version}.'
            )
            continue

        kwargs: dict = {
            "gpkg_path": gpkg_path,
            "layer_name": actual_layer,
            "index_col": table.identity_column,
            "column_mapping": source.renames or None,
            "fill_from_globalid": table.column_filled_from_globalid,
            "identity_column": table.identity_column,
            "check_geotype": table.check_geotype,
            "check_3d": check_3d,
        }
        if table.group_by is not None:
            kwargs["groupby_column"] = table.group_by
        if table.order_by is not None:
            kwargs["order_column"] = table.order_by
        if clip_layers and name in clip_layers:
            kwargs["clip"], kwargs["cliptype"] = clip_layers[name]

        # The table's own messages don't name the layer.
        prefix = f'HyDAMO layer "{actual_layer}" (DAMO {hydamo_version}): '
        try:
            getattr(hydamo, name)._read_gpkg_layer(**kwargs)
        except KeyError as exc:
            # A missing column raises at once, as a KeyError, so callers that catch
            # it still do.
            raise KeyError(prefix + str(exc.args[0])) from exc
        except ValueError as exc:
            # e.g. empty codes: collected, so all layers are reported at once
            errors.append(prefix + str(exc))
            continue
        if not _KEEP_UNDECLARED_COLUMNS:
            _drop_undeclared_columns(hydamo, name, table)
    if errors:
        raise ValueError("\n".join(errors))

    _rewrite_values(hydamo)
    # The derived columns of the tables (Table.derived_columns)
    _derive_profile_code(hydamo)
    _derive_boundary_node(hydamo)
    _derive_weir_crest(hydamo)
    _derive_gate_height(hydamo)

source_layers(version: str) -> dict[str, SourceLayer]

Return, per HyDAMO table, its layer and column renames in a DAMO version.

Chains the steps between DAMO 2.2 and version.

Parameters

version : str DAMO version, one of SUPPORTED_HYDAMO_VERSIONS, e.g. "2.4".

Returns

dict[str, SourceLayer] By HyDAMO attribute, in the order of data_model.TABLES.

Raises

ValueError If the version is not supported, a step names a table that isn't a HyDAMO table, or two tables read the same layer: the steps are keyed by table, so each table needs its own layer.

Source code in hydrolib/dhydamo/io/damo_versions/steps.py
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
def source_layers(version: str) -> dict[str, SourceLayer]:
    """Return, per HyDAMO table, its layer and column renames in a DAMO *version*.

    Chains the steps between DAMO 2.2 and *version*.

    Parameters
    ----------
    version : str
        DAMO version, one of `SUPPORTED_HYDAMO_VERSIONS`, e.g. ``"2.4"``.

    Returns
    -------
    dict[str, SourceLayer]
        By HyDAMO attribute, in the order of `data_model.TABLES`.

    Raises
    ------
    ValueError
        If the version is not supported, a step names a table that isn't a HyDAMO
        table, or two tables read the same layer: the steps are keyed by table, so
        each table needs its own layer.
    """
    if version not in SUPPORTED_HYDAMO_VERSIONS:
        supported = ", ".join(SUPPORTED_HYDAMO_VERSIONS)
        raise ValueError(
            f'Unsupported HyDAMO DAMO version "{version}". Supported versions: {supported}.'
        )
    layers = {name: table.layer for name, table in TABLES.items()}
    # {column in the current version: DAMO 2.2 name}, per table
    renames: dict[str, dict[str, str]] = {name: {} for name in TABLES}
    for step in STEPS[: SUPPORTED_HYDAMO_VERSIONS.index(version)]:
        _check_tables_exist(step)
        layers.update(step.layers)
        for name, columns in step.columns.items():
            # All renames of the step at once, from the names before it: a rename
            # may take the name another column had before the step.
            before = renames[name]
            kept = {
                current: original
                for current, original in before.items()
                if current not in columns
            }
            renamed = {new: before.get(old, old) for old, new in columns.items()}
            renames[name] = {**kept, **renamed}
    _check_layers_are_unique(layers, version)
    return {name: SourceLayer(layers[name], renames[name]) for name in TABLES}

steps

The DAMO version steps: the renames DAMO made in each version, for what HYDROLIB reads.

A step is written forward, from the older version to the newer, like the DAMO release notes. Each rename is written once, in the step where DAMO made it.

Loading doesn't convert the data step by step. source_layers chains the steps into, per HyDAMO table, the layer to read in the file's version and the renames from that version's column names to DAMO 2.2, the version of HYDROLIB's data model (data_model). The layer is then read and renamed once.

SourceLayer dataclass

Where a HyDAMO table comes from in a file of one DAMO version.

Parameters

layer : str The layer in that version. renames : dict[str, str] {column in that version: DAMO 2.2 name}, for the renamed columns.

Source code in hydrolib/dhydamo/io/damo_versions/steps.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass(frozen=True)
class SourceLayer:
    """Where a HyDAMO table comes from in a file of one DAMO version.

    Parameters
    ----------
    layer : str
        The layer in that version.
    renames : dict[str, str]
        ``{column in that version: DAMO 2.2 name}``, for the renamed columns.
    """

    layer: str
    renames: dict[str, str]
Step dataclass

The layer and column renames from DAMO version old to new.

Parameters

old : str The older DAMO version, e.g. "2.4". new : str The newer DAMO version, e.g. "2.5". layers : dict[str, str] The tables whose layer changed: {HyDAMO attribute: layer in new}. columns : dict[str, dict[str, str]] The tables whose columns were renamed: {HyDAMO attribute: {column in old: column in new}}. For a table that moves to another layer (see layers), the old names are those of its old layer.

Source code in hydrolib/dhydamo/io/damo_versions/steps.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@dataclass(frozen=True)
class Step:
    """The layer and column renames from DAMO version *old* to *new*.

    Parameters
    ----------
    old : str
        The older DAMO version, e.g. ``"2.4"``.
    new : str
        The newer DAMO version, e.g. ``"2.5"``.
    layers : dict[str, str]
        The tables whose layer changed: ``{HyDAMO attribute: layer in new}``.
    columns : dict[str, dict[str, str]]
        The tables whose columns were renamed:
        ``{HyDAMO attribute: {column in old: column in new}}``. For a table that moves
        to another layer (see *layers*), the old names are those of its old layer.
    """

    old: str
    new: str
    layers: dict[str, str] = field(default_factory=dict)
    columns: dict[str, dict[str, str]] = field(default_factory=dict)
source_layers(version: str) -> dict[str, SourceLayer]

Return, per HyDAMO table, its layer and column renames in a DAMO version.

Chains the steps between DAMO 2.2 and version.

Parameters

version : str DAMO version, one of SUPPORTED_HYDAMO_VERSIONS, e.g. "2.4".

Returns

dict[str, SourceLayer] By HyDAMO attribute, in the order of data_model.TABLES.

Raises

ValueError If the version is not supported, a step names a table that isn't a HyDAMO table, or two tables read the same layer: the steps are keyed by table, so each table needs its own layer.

Source code in hydrolib/dhydamo/io/damo_versions/steps.py
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
def source_layers(version: str) -> dict[str, SourceLayer]:
    """Return, per HyDAMO table, its layer and column renames in a DAMO *version*.

    Chains the steps between DAMO 2.2 and *version*.

    Parameters
    ----------
    version : str
        DAMO version, one of `SUPPORTED_HYDAMO_VERSIONS`, e.g. ``"2.4"``.

    Returns
    -------
    dict[str, SourceLayer]
        By HyDAMO attribute, in the order of `data_model.TABLES`.

    Raises
    ------
    ValueError
        If the version is not supported, a step names a table that isn't a HyDAMO
        table, or two tables read the same layer: the steps are keyed by table, so
        each table needs its own layer.
    """
    if version not in SUPPORTED_HYDAMO_VERSIONS:
        supported = ", ".join(SUPPORTED_HYDAMO_VERSIONS)
        raise ValueError(
            f'Unsupported HyDAMO DAMO version "{version}". Supported versions: {supported}.'
        )
    layers = {name: table.layer for name, table in TABLES.items()}
    # {column in the current version: DAMO 2.2 name}, per table
    renames: dict[str, dict[str, str]] = {name: {} for name in TABLES}
    for step in STEPS[: SUPPORTED_HYDAMO_VERSIONS.index(version)]:
        _check_tables_exist(step)
        layers.update(step.layers)
        for name, columns in step.columns.items():
            # All renames of the step at once, from the names before it: a rename
            # may take the name another column had before the step.
            before = renames[name]
            kept = {
                current: original
                for current, original in before.items()
                if current not in columns
            }
            renamed = {new: before.get(old, old) for old, new in columns.items()}
            renames[name] = {**kept, **renamed}
    _check_layers_are_unique(layers, version)
    return {name: SourceLayer(layers[name], renames[name]) for name in TABLES}

dimrwriter

Write the DIMR configuration and a run.bat for a coupled FM, RR and RTC model.

DIMRWriter

Temporary files for DIMR-configuration - to be superseded by Hydrolib-core functionality.

Source code in hydrolib/dhydamo/io/dimrwriter.py
 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
 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
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
class DIMRWriter:
    """Temporary files for DIMR-configuration - to be superseded by Hydrolib-core functionality."""

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def __init__(
        self, dimr_path: str | None = None, output_path: str | Path | None = None
    ) -> None:
        """Create a DIMR writer.

        This is a temporary fix to include writers for RR and RTC, which are not yet
        fully included in HYDROLIB-core, or have bugs. Eventually this class should be
        redundant, when HYDROLIB-core includes this functionality.

        Parameters
        ----------
        dimr_path : str, optional
            The ``run_dimr.bat`` script that `write_runbat` calls. Defaults to None: the
            script of a D-HYDRO Suite 2022.04 installation.
        output_path : str or Path, optional
            Model folder in which the files are written. Defaults to None: the current
            working directory.
        """
        if dimr_path is None:
            self.run_dimr = r"C:\Program Files\Deltares\D-HYDRO Suite 2022.04 1D2D\plugins\DeltaShell.Dimr\kernels\x64\dimr\scripts\run_dimr.bat"
        else:
            self.run_dimr = dimr_path

        if output_path is None:
            self.output_path = Path(os.path.abspath("."))
        else:
            self.output_path = Path(output_path)

        self.template_dir = Path(os.path.abspath("."))

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def write_runbat(
        self, debuglevel: int = 6, runlog: str | Path | None = None
    ) -> None:
        """Write a run.bat that runs the model with DIMR.

        The script calls the ``run_dimr.bat`` given when creating the writer.

        Parameters
        ----------
        debuglevel : int, optional
            DIMR debug level (``-d``). Defaults to 6.
        runlog : str or Path, optional
            File to which the output of DIMR is redirected. Defaults to None: no
            redirection.
        """
        with open(os.path.join(self.output_path, "run.bat"), "w") as f:
            f.write("@ echo off\n")
            f.write("set OMP_NUM_THREADS=2\n")
            if runlog is None:
                f.write(
                    'call "' + str(self.run_dimr) + '" -d ' + str(debuglevel) + "\n"
                )
            else:
                f.write(
                    'call "'
                    + str(self.run_dimr)
                    + '" -d '
                    + str(debuglevel)
                    + " > "
                    + str(runlog)
                    + "\n"
                )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def add_crs(self, netcdf_path: str | Path | None = None) -> None:
        """Add the coordinate reference system EPSG:28992 (RD New) to the network file, in place.

        Parameters
        ----------
        netcdf_path : str or Path, optional
            Network file, or a folder with it (the first ``*.nc`` file is used). Defaults
            to None: the first ``*.nc`` file in the ``dflowfm`` folder of the output path.

        Raises
        ------
        FileNotFoundError
            If no netCDF file is found.
        """
        if netcdf_path is None:
            netfile = next((self.output_path / "dflowfm").glob("*.nc"), None)
            if netfile is None:
                raise FileNotFoundError(
                    f"Netcdf file not found in {self.output_path / 'dflowfm'}. Provide the correct path via the netcdf_path argument."
                )
        else:
            netcdf_path = Path(netcdf_path)
            if netcdf_path.is_dir():
                netfile = next(netcdf_path.glob("*.nc"), None)
                if netfile is None:
                    raise FileNotFoundError(f"Netcdf file not found in {netcdf_path}.")
            elif netcdf_path.is_file():
                netfile = netcdf_path
            else:
                raise FileNotFoundError(f"Netcdf file not found at {netcdf_path}.")
        netf = nc.Dataset(netfile, "r+")
        netf.Conventions = "CF-1.8 UGRID-1.0 Deltares-0.10"
        proj = netf.createVariable("projected_coordinate_system", "i4")
        proj.epsg = 28992
        proj.grid_mapping_name = "Amersfoort / RD New"  # "Rijksdriehoeksstelsel"
        proj.longitude_of_prime_meridian = 0.0  # ; // double
        proj.semi_major_axis = 6377397.155  # ; // double
        proj.semi_minor_axis = 6356078.962818189  # ; // double
        proj.inverse_flattening = 299.1528128  # ; // double
        proj.proj4_params = "+proj=sterea +lat_0=52.1561605555556 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs"
        proj.EPSG_code = "EPSG:28992"
        proj.value = "value is equal to EPSG code"
        proj.wkt = 'PROJCS["Amersfoort / RD New",\n    GEOGCS["Amersfoort",\n        DATUM["Amersfoort",\n            SPHEROID["Bessel 1841",6377397.155,299.1528128,\n'
        netf.close()

    @staticmethod
    def _add_unique_coupler_item(
        coupler: ET.Element,
        source_name: str | None,
        target_name: str | None,
        seen_pairs: set[tuple[str, str]],
        gn_brackets: str,
    ) -> bool:
        if source_name is None or target_name is None:
            return False

        pair = (source_name, target_name)
        if pair in seen_pairs:
            return False
        seen_pairs.add(pair)

        item = ET.SubElement(coupler, gn_brackets + "item")
        item.text = ""
        item.tail = "\n"

        source = ET.SubElement(item, gn_brackets + "sourceName")
        source.text = source_name
        source.tail = "\n"

        target = ET.SubElement(item, gn_brackets + "targetName")
        target.text = target_name
        target.tail = "\n"
        return True

    @staticmethod
    def _get_complex_coupler_blocks(
        rtc_model: DRTCModel, name_prefix: str
    ) -> list[ET.Element]:
        """Return the <coupler> blocks from the complex controllers' dimr_config whose name starts with name_prefix."""
        if rtc_model.complex_controllers is None:
            return []

        complex_config = rtc_model.complex_controllers["dimr_config"][0]
        blocks = []
        for block in complex_config:
            block_tag = (
                block.tag.split("}", 1)[-1] if block.tag.startswith("{") else block.tag
            )
            if block_tag == "coupler" and block.attrib["name"].lower().startswith(
                name_prefix
            ):
                blocks.append(block)
        return blocks

    # @validate_call(config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True))
    def write_dimrconfig(
        self,
        fm: FMModel,
        rr_model: DRRModel | None = None,
        rtc_model: DRTCModel | None = None,
    ) -> None:
        """Write ``dimr_config.xml`` for the FM model, coupled with RR and RTC if given.

        Parameters
        ----------
        fm : FMModel
            The D-Flow FM model. Without RR and RTC, only FM is run.
        rr_model : DRRModel, optional
            The RR model. Defaults to None.
        rtc_model : DRTCModel, optional
            The RTC model. Defaults to None.
        """
        generalname = "http://schemas.deltares.nl/dimr"  # Config
        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 / "dimr_config.xml")

        myroot = configfile.getroot()
        if fm.filepath is None:
            raise ValueError(
                "The FM model has no filepath: save it before writing the DIMR config."
            )
        myroot[1][1].text = fm.filepath.parts[-2]
        myroot[1][2].text = fm.filepath.name

        # control blocks
        control = ET.Element(gn_brackets + "control")
        control.text = ""
        control.tail = "\n"
        myroot.insert(1, control)

        if rr_model is not None or rtc_model is not None:
            parallel = ET.SubElement(control, gn_brackets + "parallel")
            parallel.tail = "\n"
            parallel.text = ""

        if rtc_model is not None:
            # a flow_to_rtc coupler is only needed for PID/interval controllers,
            # or complex controllers whose dimr_config defines one themselves
            complex_flow_to_rtc_blocks = self._get_complex_coupler_blocks(
                rtc_model, "flow_to_rtc"
            )
            needs_flow_to_rtc_coupler = (
                bool(rtc_model.pid_controllers)
                or bool(rtc_model.interval_controllers)
                or bool(complex_flow_to_rtc_blocks)
            )

            startgrouprtc = ET.SubElement(parallel, gn_brackets + "startGroup")
            startgrouprtc.text = ""
            startgrouprtc.tail = "\n"

            timertc = ET.SubElement(startgrouprtc, gn_brackets + "time")
            timertc.text = f"{0} {rtc_model.time_settings['step']} {fm.time.tstop}"
            timertc.tail = "\n"
            if needs_flow_to_rtc_coupler:
                couplerrtcrr = ET.SubElement(startgrouprtc, gn_brackets + "coupler")
                couplerrtcrr.attrib = {"name": "flow_to_rtc"}
                couplerrtcrr.tail = "\n"

            startrtc = ET.SubElement(startgrouprtc, gn_brackets + "start")
            startrtc.attrib = {"name": "Real_Time_Control"}
            startrtc.tail = "\n"
            couplerrtc = ET.SubElement(startgrouprtc, gn_brackets + "coupler")
            couplerrtc.attrib = {"name": "rtc_to_flow"}
            couplerrtc.tail = "\n"

        if rr_model is not None:
            startgrouprr = ET.SubElement(parallel, gn_brackets + "startGroup")
            startgrouprr.text = ""
            startgrouprr.tail = "\n"

            timerr = ET.SubElement(startgrouprr, gn_brackets + "time")
            timerr.text = (
                f"{0} {rr_model.d3b_parameters['Timestepsize']} {fm.time.tstop}"
            )
            timerr.tail = "\n"
            couplerrrf = ET.SubElement(startgrouprr, gn_brackets + "coupler")
            couplerrrf.attrib = {"name": "flow_to_rr"}
            couplerrrf.tail = "\n"
            startrr = ET.SubElement(startgrouprr, gn_brackets + "start")
            startrr.attrib = {"name": "RR"}
            startrr.tail = "\n"
            couplerfrr = ET.SubElement(startgrouprr, gn_brackets + "coupler")
            couplerfrr.attrib = {"name": "rr_to_flow"}
            couplerfrr.tail = "\n"
        if rr_model is not None or rtc_model is not None:
            startfm = ET.SubElement(parallel, gn_brackets + "start")
        else:
            startfm = ET.SubElement(control, gn_brackets + "start")
        startfm.attrib = {"name": "DFM"}
        startfm.tail = "\n"

        # component blocks
        if rtc_model is not None:
            comprtc = ET.Element(gn_brackets + "component")
            comprtc.attrib = {"name": "Real_Time_Control"}
            comprtc.tail = "\n"
            librtc = ET.SubElement(comprtc, gn_brackets + "library")
            librtc.text = "FBCTools_BMI"
            librtc.tail = "\n"
            wdrtc = ET.SubElement(comprtc, gn_brackets + "workingDir")
            wdrtc.text = "rtc"
            wdrtc.tail = "\n"
            frtc = ET.SubElement(comprtc, gn_brackets + "inputFile")
            frtc.text = "."
            frtc.tail = "\n"
            myroot.insert(2, comprtc)

        if rr_model is not None:
            comprr = ET.Element(gn_brackets + "component")
            comprr.attrib = {"name": "RR"}
            comprr.tail = "\n"
            librr = ET.SubElement(comprr, gn_brackets + "library")
            librr.text = "rr_dll"
            librr.tail = "\n"
            wdrr = ET.SubElement(comprr, gn_brackets + "workingDir")
            wdrr.text = "rr"
            wdrr.tail = "\n"
            frr = ET.SubElement(comprr, gn_brackets + "inputFile")
            frr.text = "Sobek_3b.fnm"
            frr.tail = "\n"
            myroot.insert(4, comprr)

            # FM to RR coupler
            couplerfmrr = ET.Element(gn_brackets + "coupler")
            couplerfmrr.attrib = {"name": "flow_to_rr"}
            couplerfmrr.tail = "\n"

            sourcefmrr = ET.SubElement(couplerfmrr, gn_brackets + "sourceComponent")
            sourcefmrr.text = "DFM"
            sourcefmrr.tail = "\n"

            targetfmrr = ET.SubElement(couplerfmrr, gn_brackets + "targetComponent")
            targetfmrr.text = "RR"
            targetfmrr.tail = "\n"

            for i in rr_model.external_forcings.boundary_nodes:
                item = ET.SubElement(couplerfmrr, gn_brackets + "item")
                item.text = ""
                item.tail = "\n"

                source = ET.SubElement(item, gn_brackets + "sourceName")
                source.text = f"laterals/{i}/water_level"
                source.tail = "\n"

                target = ET.SubElement(item, gn_brackets + "targetName")
                target.text = f"catchments/{i}/water_level"
                target.tail = "\n"

            logfmrr = ET.SubElement(couplerfmrr, gn_brackets + "logger")
            logfmrr.text = ""
            logfmrr.tail = "\n"

            wdlogfmrr = ET.SubElement(logfmrr, gn_brackets + "workingDir")
            wdlogfmrr.text = "."
            wdlogfmrr.tail = "\n"

            flogfmrr = ET.SubElement(logfmrr, gn_brackets + "outputFile")
            flogfmrr.text = "dflowfm_to_rr.nc"
            flogfmrr.tail = "\n"
            myroot.append(couplerfmrr)

        if rtc_model is not None:
            # RTC to FM coupler
            couplerrtcfm = ET.Element(gn_brackets + "coupler")
            couplerrtcfm.attrib = {"name": "rtc_to_flow"}
            couplerrtcfm.tail = "\n"

            sourcertcfm = ET.SubElement(couplerrtcfm, gn_brackets + "sourceComponent")
            sourcertcfm.text = "Real_Time_Control"
            sourcertcfm.tail = "\n"

            targetrtcfm = ET.SubElement(couplerrtcfm, gn_brackets + "targetComponent")
            targetrtcfm.text = "DFM"
            targetrtcfm.tail = "\n"

            rtcdict = {
                "Crest level (s)": ["weirs", "crestLevel"],
                "Gate lower edge level (s)": ["orifices", "gateLowerEdgeLevel"],
                "Capacity (p)": ["pumps", "capacity"],
                "Valve opening (s)": ["culverts", "valveOpeningHeight"],
            }

            rtc_to_flow_seen_pairs: set[tuple[str, str]] = set()
            rtc_to_flow_simple_count = 0
            rtc_to_flow_complex_count = 0

            for i in rtc_model.all_controllers:
                svar = rtc_model.all_controllers[i]["steering_variable"]
                if self._add_unique_coupler_item(
                    couplerrtcfm,
                    f"[Output]{i}/{svar}",
                    f"{rtcdict[svar][0]}/{i}/{rtcdict[svar][1]}",
                    rtc_to_flow_seen_pairs,
                    gn_brackets,
                ):
                    rtc_to_flow_simple_count += 1

            # check if there are user-specified controller that should be included
            if rtc_model.complex_controllers is not None:
                complex_config = rtc_model.complex_controllers["dimr_config"][0]
                for block in complex_config:
                    block_tag = (
                        block.tag.split("}", 1)[-1]
                        if block.tag.startswith("{")
                        else block.tag
                    )
                    if block_tag == "coupler" and block.attrib[
                        "name"
                    ].lower().startswith("rtc_to_flow"):
                        for iblock in block:
                            iblock_tag = (
                                iblock.tag.split("}", 1)[-1]
                                if iblock.tag.startswith("{")
                                else iblock.tag
                            )
                            if iblock_tag == "item":
                                found_source = iblock.find(".//{*}sourceName")
                                found_target = iblock.find(".//{*}targetName")
                                if self._add_unique_coupler_item(
                                    couplerrtcfm,
                                    found_source.text
                                    if found_source is not None
                                    else None,
                                    found_target.text
                                    if found_target is not None
                                    else None,
                                    rtc_to_flow_seen_pairs,
                                    gn_brackets,
                                ):
                                    rtc_to_flow_complex_count += 1

            logger.info(
                "dimr_config.xml: Wrote rtc_to_flow coupler with %d items (%d simple, %d complex).",
                len(rtc_to_flow_seen_pairs),
                rtc_to_flow_simple_count,
                rtc_to_flow_complex_count,
            )

            logrtcfm = ET.SubElement(couplerrtcfm, gn_brackets + "logger")
            logrtcfm.text = ""
            logrtcfm.tail = "\n"

            wdlogrtcfm = ET.SubElement(logrtcfm, gn_brackets + "workingDir")
            wdlogrtcfm.text = "."
            wdlogrtcfm.tail = "\n"

            flogrtcfm = ET.SubElement(logrtcfm, gn_brackets + "outputFile")
            flogrtcfm.text = "rtc_to_dflowfm.nc"
            flogrtcfm.tail = "\n"

            myroot.append(couplerrtcfm)

            # the Fm to RTC coupler is not always needed. It is for PID controllers.
            coupler_exists = False
            flow_to_rtc_seen_pairs: set[tuple[str, str]] = set()
            flow_to_rtc_simple_count = 0
            flow_to_rtc_complex_count = 0
            if bool(rtc_model.pid_controllers) or bool(rtc_model.interval_controllers):
                couplerfmrtc = ET.Element(gn_brackets + "coupler")
                couplerfmrtc.attrib = {"name": "flow_to_rtc"}
                couplerfmrtc.tail = "\n"

                sourcefmrtc = ET.SubElement(
                    couplerfmrtc, gn_brackets + "sourceComponent"
                )
                sourcefmrtc.text = "DFM"
                sourcefmrtc.tail = "\n"

                targetfmrtc = ET.SubElement(
                    couplerfmrtc, gn_brackets + "targetComponent"
                )
                targetfmrtc.text = "Real_Time_Control"
                targetfmrtc.tail = "\n"

                for i in rtc_model.pid_controllers:
                    if (
                        rtc_model.pid_controllers[i]["target_variable"]
                        == "Discharge (op)"
                    ):
                        source_name = f"observations/{rtc_model.pid_controllers[i]['observation_point']}/discharge"
                    elif (
                        rtc_model.pid_controllers[i]["target_variable"]
                        == "Water level (op)"
                    ):
                        source_name = f"observations/{rtc_model.pid_controllers[i]['observation_point']}/water_level"
                    else:
                        raise ValueError(
                            "Invalid target variable in controller: should bo discharge or water level."
                        )
                    target_name = f"[Input]{rtc_model.pid_controllers[i]['observation_point']}/{rtc_model.pid_controllers[i]['target_variable']}"
                    if self._add_unique_coupler_item(
                        couplerfmrtc,
                        source_name,
                        target_name,
                        flow_to_rtc_seen_pairs,
                        gn_brackets,
                    ):
                        flow_to_rtc_simple_count += 1

                # Loop through all interval controllers
                for i in rtc_model.interval_controllers:
                    if (
                        rtc_model.interval_controllers[i]["target_variable"]
                        == "Discharge (op)"
                    ):
                        source_name = f"observations/{rtc_model.interval_controllers[i]['observation_point']}/discharge"
                    elif (
                        rtc_model.interval_controllers[i]["target_variable"]
                        == "Water level (op)"
                    ):
                        source_name = f"observations/{rtc_model.interval_controllers[i]['observation_point']}/water_level"
                    else:
                        raise ValueError(
                            "Invalid target variable in controller: should be discharge or water level."
                        )
                    target_name = f"[Input]{rtc_model.interval_controllers[i]['observation_point']}/{rtc_model.interval_controllers[i]['target_variable']}"
                    if self._add_unique_coupler_item(
                        couplerfmrtc,
                        source_name,
                        target_name,
                        flow_to_rtc_seen_pairs,
                        gn_brackets,
                    ):
                        flow_to_rtc_simple_count += 1

                coupler_exists = True
            # it could be that there are no PID/interval controllers, but there are complex controllers
            for block in complex_flow_to_rtc_blocks:
                if not coupler_exists:
                    couplerfmrtc = ET.Element(gn_brackets + "coupler")
                    couplerfmrtc.attrib = {"name": "flow_to_rtc"}
                    couplerfmrtc.tail = "\n"

                    sourcefmrtc = ET.SubElement(
                        couplerfmrtc, gn_brackets + "sourceComponent"
                    )
                    sourcefmrtc.text = "DFM"
                    sourcefmrtc.tail = "\n"

                    targetfmrtc = ET.SubElement(
                        couplerfmrtc, gn_brackets + "targetComponent"
                    )
                    targetfmrtc.text = "Real_Time_Control"
                    targetfmrtc.tail = "\n"

                    coupler_exists = True
                for iblock in block:
                    iblock_tag = (
                        iblock.tag.split("}", 1)[-1]
                        if iblock.tag.startswith("{")
                        else iblock.tag
                    )
                    if iblock_tag == "item":
                        found_source = iblock.find(".//{*}sourceName")
                        found_target = iblock.find(".//{*}targetName")
                        if self._add_unique_coupler_item(
                            couplerfmrtc,
                            found_source.text if found_source is not None else None,
                            found_target.text if found_target is not None else None,
                            flow_to_rtc_seen_pairs,
                            gn_brackets,
                        ):
                            flow_to_rtc_complex_count += 1
            # in any of those two cases, add the controllers and the logger
            if coupler_exists:
                logger.info(
                    "dimr_config.xml: Wrote flow_to_rtc coupler with %d items (%d simple, %d complex).",
                    len(flow_to_rtc_seen_pairs),
                    flow_to_rtc_simple_count,
                    flow_to_rtc_complex_count,
                )

                logrtc = ET.SubElement(couplerfmrtc, gn_brackets + "logger")
                logrtc.text = ""
                logrtc.tail = "\n"

                wdlogrtc = ET.SubElement(logrtc, gn_brackets + "workingDir")
                wdlogrtc.text = "."
                wdlogrtc.tail = "\n"

                flogrtc = ET.SubElement(logrtc, gn_brackets + "outputFile")
                flogrtc.text = "dflowfm_to_rtc.nc"
                flogrtc.tail = "\n"

                myroot.append(couplerfmrtc)

        if rr_model is not None:
            # finally the RR to FM coupler
            couplerrrfm = ET.Element(gn_brackets + "coupler")
            couplerrrfm.attrib = {"name": "rr_to_flow"}
            couplerrrfm.tail = "\n"

            sourcerrfm = ET.SubElement(couplerrrfm, gn_brackets + "sourceComponent")
            sourcerrfm.text = "RR"
            sourcerrfm.tail = "\n"

            targetrrfm = ET.SubElement(couplerrrfm, gn_brackets + "targetComponent")
            targetrrfm.text = "DFM"
            targetrrfm.tail = "\n"

            for i in rr_model.external_forcings.boundary_nodes:
                item = ET.SubElement(couplerrrfm, gn_brackets + "item")
                item.text = ""
                item.tail = "\n"

                source = ET.SubElement(item, gn_brackets + "sourceName")
                source.text = f"catchments/{i}/water_discharge"
                source.tail = "\n"

                target = ET.SubElement(item, gn_brackets + "targetName")
                target.text = f"laterals/{i}/water_discharge"
                target.tail = "\n"

            logrrfm = ET.SubElement(couplerrrfm, gn_brackets + "logger")
            logrrfm.text = ""
            logrrfm.tail = "\n"

            wdlogrrfm = ET.SubElement(logrrfm, gn_brackets + "workingDir")
            wdlogrrfm.text = "."
            wdlogrrfm.tail = "\n"

            flogrrfm = ET.SubElement(logrrfm, gn_brackets + "outputFile")
            flogrrfm.text = "rr_to_dflowfm.nc"
            flogrrfm.tail = "\n"

            myroot.append(couplerrrfm)
        # use the function from DRTC to finish the file with the correct namespace
        DRTCModel.finish_file(myroot, self.output_path / "dimr_config.xml")
__init__(dimr_path: str | None = None, output_path: str | Path | None = None) -> None

Create a DIMR writer.

This is a temporary fix to include writers for RR and RTC, which are not yet fully included in HYDROLIB-core, or have bugs. Eventually this class should be redundant, when HYDROLIB-core includes this functionality.

Parameters

dimr_path : str, optional The run_dimr.bat script that write_runbat calls. Defaults to None: the script of a D-HYDRO Suite 2022.04 installation. output_path : str or Path, optional Model folder in which the files are written. Defaults to None: the current working directory.

Source code in hydrolib/dhydamo/io/dimrwriter.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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def __init__(
    self, dimr_path: str | None = None, output_path: str | Path | None = None
) -> None:
    """Create a DIMR writer.

    This is a temporary fix to include writers for RR and RTC, which are not yet
    fully included in HYDROLIB-core, or have bugs. Eventually this class should be
    redundant, when HYDROLIB-core includes this functionality.

    Parameters
    ----------
    dimr_path : str, optional
        The ``run_dimr.bat`` script that `write_runbat` calls. Defaults to None: the
        script of a D-HYDRO Suite 2022.04 installation.
    output_path : str or Path, optional
        Model folder in which the files are written. Defaults to None: the current
        working directory.
    """
    if dimr_path is None:
        self.run_dimr = r"C:\Program Files\Deltares\D-HYDRO Suite 2022.04 1D2D\plugins\DeltaShell.Dimr\kernels\x64\dimr\scripts\run_dimr.bat"
    else:
        self.run_dimr = dimr_path

    if output_path is None:
        self.output_path = Path(os.path.abspath("."))
    else:
        self.output_path = Path(output_path)

    self.template_dir = Path(os.path.abspath("."))
add_crs(netcdf_path: str | Path | None = None) -> None

Add the coordinate reference system EPSG:28992 (RD New) to the network file, in place.

Parameters

netcdf_path : str or Path, optional Network file, or a folder with it (the first *.nc file is used). Defaults to None: the first *.nc file in the dflowfm folder of the output path.

Raises

FileNotFoundError If no netCDF file is found.

Source code in hydrolib/dhydamo/io/dimrwriter.py
 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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def add_crs(self, netcdf_path: str | Path | None = None) -> None:
    """Add the coordinate reference system EPSG:28992 (RD New) to the network file, in place.

    Parameters
    ----------
    netcdf_path : str or Path, optional
        Network file, or a folder with it (the first ``*.nc`` file is used). Defaults
        to None: the first ``*.nc`` file in the ``dflowfm`` folder of the output path.

    Raises
    ------
    FileNotFoundError
        If no netCDF file is found.
    """
    if netcdf_path is None:
        netfile = next((self.output_path / "dflowfm").glob("*.nc"), None)
        if netfile is None:
            raise FileNotFoundError(
                f"Netcdf file not found in {self.output_path / 'dflowfm'}. Provide the correct path via the netcdf_path argument."
            )
    else:
        netcdf_path = Path(netcdf_path)
        if netcdf_path.is_dir():
            netfile = next(netcdf_path.glob("*.nc"), None)
            if netfile is None:
                raise FileNotFoundError(f"Netcdf file not found in {netcdf_path}.")
        elif netcdf_path.is_file():
            netfile = netcdf_path
        else:
            raise FileNotFoundError(f"Netcdf file not found at {netcdf_path}.")
    netf = nc.Dataset(netfile, "r+")
    netf.Conventions = "CF-1.8 UGRID-1.0 Deltares-0.10"
    proj = netf.createVariable("projected_coordinate_system", "i4")
    proj.epsg = 28992
    proj.grid_mapping_name = "Amersfoort / RD New"  # "Rijksdriehoeksstelsel"
    proj.longitude_of_prime_meridian = 0.0  # ; // double
    proj.semi_major_axis = 6377397.155  # ; // double
    proj.semi_minor_axis = 6356078.962818189  # ; // double
    proj.inverse_flattening = 299.1528128  # ; // double
    proj.proj4_params = "+proj=sterea +lat_0=52.1561605555556 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs"
    proj.EPSG_code = "EPSG:28992"
    proj.value = "value is equal to EPSG code"
    proj.wkt = 'PROJCS["Amersfoort / RD New",\n    GEOGCS["Amersfoort",\n        DATUM["Amersfoort",\n            SPHEROID["Bessel 1841",6377397.155,299.1528128,\n'
    netf.close()
write_dimrconfig(fm: FMModel, rr_model: DRRModel | None = None, rtc_model: DRTCModel | None = None) -> None

Write dimr_config.xml for the FM model, coupled with RR and RTC if given.

Parameters

fm : FMModel The D-Flow FM model. Without RR and RTC, only FM is run. rr_model : DRRModel, optional The RR model. Defaults to None. rtc_model : DRTCModel, optional The RTC model. Defaults to None.

Source code in hydrolib/dhydamo/io/dimrwriter.py
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
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
def write_dimrconfig(
    self,
    fm: FMModel,
    rr_model: DRRModel | None = None,
    rtc_model: DRTCModel | None = None,
) -> None:
    """Write ``dimr_config.xml`` for the FM model, coupled with RR and RTC if given.

    Parameters
    ----------
    fm : FMModel
        The D-Flow FM model. Without RR and RTC, only FM is run.
    rr_model : DRRModel, optional
        The RR model. Defaults to None.
    rtc_model : DRTCModel, optional
        The RTC model. Defaults to None.
    """
    generalname = "http://schemas.deltares.nl/dimr"  # Config
    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 / "dimr_config.xml")

    myroot = configfile.getroot()
    if fm.filepath is None:
        raise ValueError(
            "The FM model has no filepath: save it before writing the DIMR config."
        )
    myroot[1][1].text = fm.filepath.parts[-2]
    myroot[1][2].text = fm.filepath.name

    # control blocks
    control = ET.Element(gn_brackets + "control")
    control.text = ""
    control.tail = "\n"
    myroot.insert(1, control)

    if rr_model is not None or rtc_model is not None:
        parallel = ET.SubElement(control, gn_brackets + "parallel")
        parallel.tail = "\n"
        parallel.text = ""

    if rtc_model is not None:
        # a flow_to_rtc coupler is only needed for PID/interval controllers,
        # or complex controllers whose dimr_config defines one themselves
        complex_flow_to_rtc_blocks = self._get_complex_coupler_blocks(
            rtc_model, "flow_to_rtc"
        )
        needs_flow_to_rtc_coupler = (
            bool(rtc_model.pid_controllers)
            or bool(rtc_model.interval_controllers)
            or bool(complex_flow_to_rtc_blocks)
        )

        startgrouprtc = ET.SubElement(parallel, gn_brackets + "startGroup")
        startgrouprtc.text = ""
        startgrouprtc.tail = "\n"

        timertc = ET.SubElement(startgrouprtc, gn_brackets + "time")
        timertc.text = f"{0} {rtc_model.time_settings['step']} {fm.time.tstop}"
        timertc.tail = "\n"
        if needs_flow_to_rtc_coupler:
            couplerrtcrr = ET.SubElement(startgrouprtc, gn_brackets + "coupler")
            couplerrtcrr.attrib = {"name": "flow_to_rtc"}
            couplerrtcrr.tail = "\n"

        startrtc = ET.SubElement(startgrouprtc, gn_brackets + "start")
        startrtc.attrib = {"name": "Real_Time_Control"}
        startrtc.tail = "\n"
        couplerrtc = ET.SubElement(startgrouprtc, gn_brackets + "coupler")
        couplerrtc.attrib = {"name": "rtc_to_flow"}
        couplerrtc.tail = "\n"

    if rr_model is not None:
        startgrouprr = ET.SubElement(parallel, gn_brackets + "startGroup")
        startgrouprr.text = ""
        startgrouprr.tail = "\n"

        timerr = ET.SubElement(startgrouprr, gn_brackets + "time")
        timerr.text = (
            f"{0} {rr_model.d3b_parameters['Timestepsize']} {fm.time.tstop}"
        )
        timerr.tail = "\n"
        couplerrrf = ET.SubElement(startgrouprr, gn_brackets + "coupler")
        couplerrrf.attrib = {"name": "flow_to_rr"}
        couplerrrf.tail = "\n"
        startrr = ET.SubElement(startgrouprr, gn_brackets + "start")
        startrr.attrib = {"name": "RR"}
        startrr.tail = "\n"
        couplerfrr = ET.SubElement(startgrouprr, gn_brackets + "coupler")
        couplerfrr.attrib = {"name": "rr_to_flow"}
        couplerfrr.tail = "\n"
    if rr_model is not None or rtc_model is not None:
        startfm = ET.SubElement(parallel, gn_brackets + "start")
    else:
        startfm = ET.SubElement(control, gn_brackets + "start")
    startfm.attrib = {"name": "DFM"}
    startfm.tail = "\n"

    # component blocks
    if rtc_model is not None:
        comprtc = ET.Element(gn_brackets + "component")
        comprtc.attrib = {"name": "Real_Time_Control"}
        comprtc.tail = "\n"
        librtc = ET.SubElement(comprtc, gn_brackets + "library")
        librtc.text = "FBCTools_BMI"
        librtc.tail = "\n"
        wdrtc = ET.SubElement(comprtc, gn_brackets + "workingDir")
        wdrtc.text = "rtc"
        wdrtc.tail = "\n"
        frtc = ET.SubElement(comprtc, gn_brackets + "inputFile")
        frtc.text = "."
        frtc.tail = "\n"
        myroot.insert(2, comprtc)

    if rr_model is not None:
        comprr = ET.Element(gn_brackets + "component")
        comprr.attrib = {"name": "RR"}
        comprr.tail = "\n"
        librr = ET.SubElement(comprr, gn_brackets + "library")
        librr.text = "rr_dll"
        librr.tail = "\n"
        wdrr = ET.SubElement(comprr, gn_brackets + "workingDir")
        wdrr.text = "rr"
        wdrr.tail = "\n"
        frr = ET.SubElement(comprr, gn_brackets + "inputFile")
        frr.text = "Sobek_3b.fnm"
        frr.tail = "\n"
        myroot.insert(4, comprr)

        # FM to RR coupler
        couplerfmrr = ET.Element(gn_brackets + "coupler")
        couplerfmrr.attrib = {"name": "flow_to_rr"}
        couplerfmrr.tail = "\n"

        sourcefmrr = ET.SubElement(couplerfmrr, gn_brackets + "sourceComponent")
        sourcefmrr.text = "DFM"
        sourcefmrr.tail = "\n"

        targetfmrr = ET.SubElement(couplerfmrr, gn_brackets + "targetComponent")
        targetfmrr.text = "RR"
        targetfmrr.tail = "\n"

        for i in rr_model.external_forcings.boundary_nodes:
            item = ET.SubElement(couplerfmrr, gn_brackets + "item")
            item.text = ""
            item.tail = "\n"

            source = ET.SubElement(item, gn_brackets + "sourceName")
            source.text = f"laterals/{i}/water_level"
            source.tail = "\n"

            target = ET.SubElement(item, gn_brackets + "targetName")
            target.text = f"catchments/{i}/water_level"
            target.tail = "\n"

        logfmrr = ET.SubElement(couplerfmrr, gn_brackets + "logger")
        logfmrr.text = ""
        logfmrr.tail = "\n"

        wdlogfmrr = ET.SubElement(logfmrr, gn_brackets + "workingDir")
        wdlogfmrr.text = "."
        wdlogfmrr.tail = "\n"

        flogfmrr = ET.SubElement(logfmrr, gn_brackets + "outputFile")
        flogfmrr.text = "dflowfm_to_rr.nc"
        flogfmrr.tail = "\n"
        myroot.append(couplerfmrr)

    if rtc_model is not None:
        # RTC to FM coupler
        couplerrtcfm = ET.Element(gn_brackets + "coupler")
        couplerrtcfm.attrib = {"name": "rtc_to_flow"}
        couplerrtcfm.tail = "\n"

        sourcertcfm = ET.SubElement(couplerrtcfm, gn_brackets + "sourceComponent")
        sourcertcfm.text = "Real_Time_Control"
        sourcertcfm.tail = "\n"

        targetrtcfm = ET.SubElement(couplerrtcfm, gn_brackets + "targetComponent")
        targetrtcfm.text = "DFM"
        targetrtcfm.tail = "\n"

        rtcdict = {
            "Crest level (s)": ["weirs", "crestLevel"],
            "Gate lower edge level (s)": ["orifices", "gateLowerEdgeLevel"],
            "Capacity (p)": ["pumps", "capacity"],
            "Valve opening (s)": ["culverts", "valveOpeningHeight"],
        }

        rtc_to_flow_seen_pairs: set[tuple[str, str]] = set()
        rtc_to_flow_simple_count = 0
        rtc_to_flow_complex_count = 0

        for i in rtc_model.all_controllers:
            svar = rtc_model.all_controllers[i]["steering_variable"]
            if self._add_unique_coupler_item(
                couplerrtcfm,
                f"[Output]{i}/{svar}",
                f"{rtcdict[svar][0]}/{i}/{rtcdict[svar][1]}",
                rtc_to_flow_seen_pairs,
                gn_brackets,
            ):
                rtc_to_flow_simple_count += 1

        # check if there are user-specified controller that should be included
        if rtc_model.complex_controllers is not None:
            complex_config = rtc_model.complex_controllers["dimr_config"][0]
            for block in complex_config:
                block_tag = (
                    block.tag.split("}", 1)[-1]
                    if block.tag.startswith("{")
                    else block.tag
                )
                if block_tag == "coupler" and block.attrib[
                    "name"
                ].lower().startswith("rtc_to_flow"):
                    for iblock in block:
                        iblock_tag = (
                            iblock.tag.split("}", 1)[-1]
                            if iblock.tag.startswith("{")
                            else iblock.tag
                        )
                        if iblock_tag == "item":
                            found_source = iblock.find(".//{*}sourceName")
                            found_target = iblock.find(".//{*}targetName")
                            if self._add_unique_coupler_item(
                                couplerrtcfm,
                                found_source.text
                                if found_source is not None
                                else None,
                                found_target.text
                                if found_target is not None
                                else None,
                                rtc_to_flow_seen_pairs,
                                gn_brackets,
                            ):
                                rtc_to_flow_complex_count += 1

        logger.info(
            "dimr_config.xml: Wrote rtc_to_flow coupler with %d items (%d simple, %d complex).",
            len(rtc_to_flow_seen_pairs),
            rtc_to_flow_simple_count,
            rtc_to_flow_complex_count,
        )

        logrtcfm = ET.SubElement(couplerrtcfm, gn_brackets + "logger")
        logrtcfm.text = ""
        logrtcfm.tail = "\n"

        wdlogrtcfm = ET.SubElement(logrtcfm, gn_brackets + "workingDir")
        wdlogrtcfm.text = "."
        wdlogrtcfm.tail = "\n"

        flogrtcfm = ET.SubElement(logrtcfm, gn_brackets + "outputFile")
        flogrtcfm.text = "rtc_to_dflowfm.nc"
        flogrtcfm.tail = "\n"

        myroot.append(couplerrtcfm)

        # the Fm to RTC coupler is not always needed. It is for PID controllers.
        coupler_exists = False
        flow_to_rtc_seen_pairs: set[tuple[str, str]] = set()
        flow_to_rtc_simple_count = 0
        flow_to_rtc_complex_count = 0
        if bool(rtc_model.pid_controllers) or bool(rtc_model.interval_controllers):
            couplerfmrtc = ET.Element(gn_brackets + "coupler")
            couplerfmrtc.attrib = {"name": "flow_to_rtc"}
            couplerfmrtc.tail = "\n"

            sourcefmrtc = ET.SubElement(
                couplerfmrtc, gn_brackets + "sourceComponent"
            )
            sourcefmrtc.text = "DFM"
            sourcefmrtc.tail = "\n"

            targetfmrtc = ET.SubElement(
                couplerfmrtc, gn_brackets + "targetComponent"
            )
            targetfmrtc.text = "Real_Time_Control"
            targetfmrtc.tail = "\n"

            for i in rtc_model.pid_controllers:
                if (
                    rtc_model.pid_controllers[i]["target_variable"]
                    == "Discharge (op)"
                ):
                    source_name = f"observations/{rtc_model.pid_controllers[i]['observation_point']}/discharge"
                elif (
                    rtc_model.pid_controllers[i]["target_variable"]
                    == "Water level (op)"
                ):
                    source_name = f"observations/{rtc_model.pid_controllers[i]['observation_point']}/water_level"
                else:
                    raise ValueError(
                        "Invalid target variable in controller: should bo discharge or water level."
                    )
                target_name = f"[Input]{rtc_model.pid_controllers[i]['observation_point']}/{rtc_model.pid_controllers[i]['target_variable']}"
                if self._add_unique_coupler_item(
                    couplerfmrtc,
                    source_name,
                    target_name,
                    flow_to_rtc_seen_pairs,
                    gn_brackets,
                ):
                    flow_to_rtc_simple_count += 1

            # Loop through all interval controllers
            for i in rtc_model.interval_controllers:
                if (
                    rtc_model.interval_controllers[i]["target_variable"]
                    == "Discharge (op)"
                ):
                    source_name = f"observations/{rtc_model.interval_controllers[i]['observation_point']}/discharge"
                elif (
                    rtc_model.interval_controllers[i]["target_variable"]
                    == "Water level (op)"
                ):
                    source_name = f"observations/{rtc_model.interval_controllers[i]['observation_point']}/water_level"
                else:
                    raise ValueError(
                        "Invalid target variable in controller: should be discharge or water level."
                    )
                target_name = f"[Input]{rtc_model.interval_controllers[i]['observation_point']}/{rtc_model.interval_controllers[i]['target_variable']}"
                if self._add_unique_coupler_item(
                    couplerfmrtc,
                    source_name,
                    target_name,
                    flow_to_rtc_seen_pairs,
                    gn_brackets,
                ):
                    flow_to_rtc_simple_count += 1

            coupler_exists = True
        # it could be that there are no PID/interval controllers, but there are complex controllers
        for block in complex_flow_to_rtc_blocks:
            if not coupler_exists:
                couplerfmrtc = ET.Element(gn_brackets + "coupler")
                couplerfmrtc.attrib = {"name": "flow_to_rtc"}
                couplerfmrtc.tail = "\n"

                sourcefmrtc = ET.SubElement(
                    couplerfmrtc, gn_brackets + "sourceComponent"
                )
                sourcefmrtc.text = "DFM"
                sourcefmrtc.tail = "\n"

                targetfmrtc = ET.SubElement(
                    couplerfmrtc, gn_brackets + "targetComponent"
                )
                targetfmrtc.text = "Real_Time_Control"
                targetfmrtc.tail = "\n"

                coupler_exists = True
            for iblock in block:
                iblock_tag = (
                    iblock.tag.split("}", 1)[-1]
                    if iblock.tag.startswith("{")
                    else iblock.tag
                )
                if iblock_tag == "item":
                    found_source = iblock.find(".//{*}sourceName")
                    found_target = iblock.find(".//{*}targetName")
                    if self._add_unique_coupler_item(
                        couplerfmrtc,
                        found_source.text if found_source is not None else None,
                        found_target.text if found_target is not None else None,
                        flow_to_rtc_seen_pairs,
                        gn_brackets,
                    ):
                        flow_to_rtc_complex_count += 1
        # in any of those two cases, add the controllers and the logger
        if coupler_exists:
            logger.info(
                "dimr_config.xml: Wrote flow_to_rtc coupler with %d items (%d simple, %d complex).",
                len(flow_to_rtc_seen_pairs),
                flow_to_rtc_simple_count,
                flow_to_rtc_complex_count,
            )

            logrtc = ET.SubElement(couplerfmrtc, gn_brackets + "logger")
            logrtc.text = ""
            logrtc.tail = "\n"

            wdlogrtc = ET.SubElement(logrtc, gn_brackets + "workingDir")
            wdlogrtc.text = "."
            wdlogrtc.tail = "\n"

            flogrtc = ET.SubElement(logrtc, gn_brackets + "outputFile")
            flogrtc.text = "dflowfm_to_rtc.nc"
            flogrtc.tail = "\n"

            myroot.append(couplerfmrtc)

    if rr_model is not None:
        # finally the RR to FM coupler
        couplerrrfm = ET.Element(gn_brackets + "coupler")
        couplerrrfm.attrib = {"name": "rr_to_flow"}
        couplerrrfm.tail = "\n"

        sourcerrfm = ET.SubElement(couplerrrfm, gn_brackets + "sourceComponent")
        sourcerrfm.text = "RR"
        sourcerrfm.tail = "\n"

        targetrrfm = ET.SubElement(couplerrrfm, gn_brackets + "targetComponent")
        targetrrfm.text = "DFM"
        targetrrfm.tail = "\n"

        for i in rr_model.external_forcings.boundary_nodes:
            item = ET.SubElement(couplerrrfm, gn_brackets + "item")
            item.text = ""
            item.tail = "\n"

            source = ET.SubElement(item, gn_brackets + "sourceName")
            source.text = f"catchments/{i}/water_discharge"
            source.tail = "\n"

            target = ET.SubElement(item, gn_brackets + "targetName")
            target.text = f"laterals/{i}/water_discharge"
            target.tail = "\n"

        logrrfm = ET.SubElement(couplerrrfm, gn_brackets + "logger")
        logrrfm.text = ""
        logrrfm.tail = "\n"

        wdlogrrfm = ET.SubElement(logrrfm, gn_brackets + "workingDir")
        wdlogrrfm.text = "."
        wdlogrrfm.tail = "\n"

        flogrrfm = ET.SubElement(logrrfm, gn_brackets + "outputFile")
        flogrrfm.text = "rr_to_dflowfm.nc"
        flogrrfm.tail = "\n"

        myroot.append(couplerrrfm)
    # use the function from DRTC to finish the file with the correct namespace
    DRTCModel.finish_file(myroot, self.output_path / "dimr_config.xml")
write_runbat(debuglevel: int = 6, runlog: str | Path | None = None) -> None

Write a run.bat that runs the model with DIMR.

The script calls the run_dimr.bat given when creating the writer.

Parameters

debuglevel : int, optional DIMR debug level (-d). Defaults to 6. runlog : str or Path, optional File to which the output of DIMR is redirected. Defaults to None: no redirection.

Source code in hydrolib/dhydamo/io/dimrwriter.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def write_runbat(
    self, debuglevel: int = 6, runlog: str | Path | None = None
) -> None:
    """Write a run.bat that runs the model with DIMR.

    The script calls the ``run_dimr.bat`` given when creating the writer.

    Parameters
    ----------
    debuglevel : int, optional
        DIMR debug level (``-d``). Defaults to 6.
    runlog : str or Path, optional
        File to which the output of DIMR is redirected. Defaults to None: no
        redirection.
    """
    with open(os.path.join(self.output_path, "run.bat"), "w") as f:
        f.write("@ echo off\n")
        f.write("set OMP_NUM_THREADS=2\n")
        if runlog is None:
            f.write(
                'call "' + str(self.run_dimr) + '" -d ' + str(debuglevel) + "\n"
            )
        else:
            f.write(
                'call "'
                + str(self.run_dimr)
                + '" -d '
                + str(debuglevel)
                + " > "
                + str(runlog)
                + "\n"
            )

drrreader

Derive the RR nodes, meteo and boundaries of a D-RR model from catchments and rasters.

ExternalForcingsIO

Fill the meteo, seepage and boundary nodes of an RR model.

Parameters

external_forcings : drr.ExternalForcings The external forcings of the RR model, filled in place.

Source code in hydrolib/dhydamo/io/drrreader.py
 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
class ExternalForcingsIO:
    """Fill the meteo, seepage and boundary nodes of an RR model.

    Parameters
    ----------
    external_forcings : drr.ExternalForcings
        The external forcings of the RR model, filled in place.
    """

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

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def seepage_from_input(
        self,
        catchments: ExtendedGeoDataFrame,
        seepage_folder: Path | str,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add a seepage time series per catchment, the mean of each raster in a folder.

        The time of each step is read from the raster (IDF or netCDF).

        Parameters
        ----------
        catchments : ExtendedGeoDataFrame
            Catchment areas.
        seepage_folder : str or Path
            Folder with the seepage rasters, one per time step.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.
        """
        rasters: list[zonal.Raster] = []
        times: list[pd.Timestamp] = []
        affine = raster_crs = nodata = None
        # sorted: the time series follows the order of the files
        for path in sorted(Path(seepage_folder).iterdir()):
            if path.suffix == ".idf":
                # Lazy: zonal_stats_per_raster reads it when its turn comes.
                dataset = idfreader.open(path).squeeze()
                if affine is None:
                    affine = idfreader.affine_from_idf(dataset)
                    raster_crs = dataset.attrs.get("crs")
                    nodata = dataset.attrs.get("nodata", np.nan)
                elif idfreader.affine_from_idf(dataset) != affine:
                    raise ValueError(
                        f"IDF seepage file {path.name} differs in grid from the others."
                    )
                rasters.append(dataset)
                # the one time of the file
                times.append(pd.DatetimeIndex(dataset["time"].to_numpy().ravel())[0])
            else:
                rasters.append(path)
                times.append(self.external_forcings.drrmodel._time_from_filename(path))
        stats = zonal.zonal_stats_per_raster(
            gpd.GeoDataFrame(catchments),
            rasters,
            "mean",
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            affine=affine,
            raster_crs=raster_crs,
            nodata=nodata,
            progress=True,
        )
        result = pd.DataFrame(
            stats.to_numpy().T,
            index=times,
            columns=["sep_" + str(cat) for cat in catchments.code],
        )
        if affine is not None:
            # if an NHI model (IDF files) is used, convert units from m3 to mm/d
            result = (result / (1e-3 * (affine[0] * -affine[4]))) / (
                (times[2] - times[1]).total_seconds() / 86400.0
            )
        for column, series in result.items():
            self.external_forcings.add_seepage(str(column), series)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def precip_from_input(
        self,
        areas: ExtendedGeoDataFrame,
        precip_folder: Path | str | None = None,
        precip_file: Path | str | None = None,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add a precipitation time series per meteo area, or use an existing meteo file.

        Parameters
        ----------
        areas : ExtendedGeoDataFrame
            Meteo areas for which time series are created.
        precip_folder : str or Path, optional
            Folder with precipitation rasters, one per time step. Only used without
            ``precip_file``. Defaults to None.
        precip_file : str or Path, optional
            Existing meteo file (``.bui``), used instead of the rasters. Defaults to None.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.

        Raises
        ------
        ValueError
            If neither ``precip_folder`` nor ``precip_file`` is given.
        """
        if precip_file is None:
            if precip_folder is None:
                raise ValueError("Provide precip_folder or precip_file.")
            # sorted: the time series follows the order of the files
            paths = sorted(Path(precip_folder).iterdir())
            stats = zonal.zonal_stats_per_raster(
                gpd.GeoDataFrame(areas),
                paths,
                "mean",
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                progress=True,
            )
            result = pd.DataFrame(
                stats.to_numpy().T,
                index=[
                    self.external_forcings.drrmodel._time_from_filename(path)
                    for path in paths
                ],
                columns=["ms_" + str(area) for area in areas.code],
            )
            for column, series in result.items():
                self.external_forcings.add_precip(str(column), series)
        else:
            self.external_forcings.precip = str(precip_file)

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def evap_from_input(
        self,
        areas: ExtendedGeoDataFrame,
        evap_folder: Path | str | None = None,
        evap_file: Path | str | None = None,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add an evaporation time series per meteo area, or use an existing meteo file.

        Parameters
        ----------
        areas : ExtendedGeoDataFrame
            Meteo areas for which time series are created.
        evap_folder : str or Path, optional
            Folder with evaporation rasters, one per time step. Only used without
            ``evap_file``. Defaults to None.
        evap_file : str or Path, optional
            Existing meteo file (``.evp``), used instead of the rasters. Defaults to None.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.

        Raises
        ------
        ValueError
            If neither ``evap_folder`` nor ``evap_file`` is given.
        """
        if evap_file is None:
            if evap_folder is None:
                raise ValueError("Provide evap_folder or evap_file.")
            # aggregated evap
            # areas['dissolve'] = 1
            # agg_areas = areas.iloc[0:len(areas),:].dissolve(by='dissolve',aggfunc='mean')
            # sorted: the time series follows the order of the files
            paths = sorted(Path(evap_folder).iterdir())
            stats = zonal.zonal_stats_per_raster(
                gpd.GeoDataFrame(areas),
                paths,
                "mean",
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                progress=True,
            )
            result = pd.DataFrame(
                stats.to_numpy().T,
                index=[
                    self.external_forcings.drrmodel._time_from_filename(path)
                    for path in paths
                ],
                columns=["ms_" + str(area) for area in areas.code],
            )
            for column, series in result.items():
                self.external_forcings.add_evap(str(column), series)
        else:
            self.external_forcings.evap = str(evap_file)

    # defer_build: drr.DRRModel does not exist yet when drr imports this module
    @validate_call(
        config=ConfigDict(
            arbitrary_types_allowed=True, coerce_numbers_to_str=True, defer_build=True
        )
    )
    def boundary_from_input(
        self,
        boundary_nodes: ExtendedGeoDataFrame,
        catchments: ExtendedGeoDataFrame,
        drrmodel: drr.DRRModel,
        overflows: ExtendedGeoDataFrame | None = None,
        greenhouse_laterals: ExtendedGeoDataFrame | None = None,
    ) -> None:
        """Add the RR boundary nodes, which link the RR nodes to the FM laterals.

        Call this after the RR nodes are added. Catchments without any RR node with an
        area are removed from ``catchments``, in place.

        Parameters
        ----------
        boundary_nodes : ExtendedGeoDataFrame
            Laterals, linked to the catchments by their key.
        catchments : ExtendedGeoDataFrame
            Catchment areas, with a ``boundary_node`` column.
        drrmodel : drr.DRRModel
            The RR model, with its nodes added.
        overflows : ExtendedGeoDataFrame, optional
            Overflow locations, each added as a boundary node. Defaults to None.
        greenhouse_laterals : ExtendedGeoDataFrame, optional
            Outlet points of greenhouse areas, each added as a boundary node. Defaults to
            None.
        """
        # boundary nodes of the RR nodes with an area
        nodes_with_area = set()
        for node in drrmodel.unpaved.unp_nodes.values():
            # an unpaved node has an area per land use
            land_use_areas = [float(area) for area in node["ar"].split(" ")]
            if np.sum(land_use_areas) > 0.0:
                nodes_with_area.add(node["boundary_node"])
        for nodes in (
            drrmodel.paved.pav_nodes,
            drrmodel.greenhouse.gh_nodes,
            drrmodel.openwater.ow_nodes,
        ):
            for node in nodes.values():
                if float(node["ar"]) > 0.0:
                    nodes_with_area.add(node["boundary_node"])

        # the catchments that have no area attached and no nodes that will be attached to the boundary
        not_occurring = [
            node for node in catchments["boundary_node"] if node not in nodes_with_area
        ]

        drop_idx = catchments[
            catchments.boundary_node.isin(not_occurring)
        ].index.to_list()
        if drop_idx:
            logger.warning(
                "%d catchments removed because of an area of 0 m2.",
                len(drop_idx),
            )
            # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
            catchments.drop(drop_idx, inplace=True)  # noqa: PD002

        catchment_lat = DamoRelations.CATCHMENT_LATERAL
        for cat in catchments.itertuples():
            lateral_id = getattr(cat, catchment_lat.foreign_key)
            lat = boundary_nodes[boundary_nodes[catchment_lat.parent_key] == lateral_id]
            if lat.empty:
                logger.warning(
                    f"{cat.code} not connected to a boundary node. Skipping."
                )
                self.external_forcings.add_boundary_node(id="0.0", px="0.0", py="0.0")
                continue
            self.external_forcings.add_boundary_node(
                id=f"lat_{cat.code}",
                px=str(lat.geometry.x.iloc[0]).strip(),
                py=str(lat.geometry.y.iloc[0]).strip(),
            )
        if overflows is not None:
            logger.info("Adding overflows to the boundary nodes.")
            for ovf, ovf_geometry in zip(overflows.itertuples(), overflows.geometry):
                self.external_forcings.add_boundary_node(
                    id=str(ovf.code),
                    px=str(ovf_geometry.coords[0][0]),
                    py=str(ovf_geometry.coords[0][1]),
                )
        if greenhouse_laterals is not None:
            logger.info("Adding greenhouse_laterals to the boundary nodes.")
            for gh, gh_geometry in zip(
                greenhouse_laterals.itertuples(), greenhouse_laterals.geometry
            ):
                self.external_forcings.add_boundary_node(
                    id=str(gh.code),
                    px=str(gh_geometry.coords[0][0]),
                    py=str(gh_geometry.coords[0][1]),
                )
boundary_from_input(boundary_nodes: ExtendedGeoDataFrame, catchments: ExtendedGeoDataFrame, drrmodel: drr.DRRModel, overflows: ExtendedGeoDataFrame | None = None, greenhouse_laterals: ExtendedGeoDataFrame | None = None) -> None

Add the RR boundary nodes, which link the RR nodes to the FM laterals.

Call this after the RR nodes are added. Catchments without any RR node with an area are removed from catchments, in place.

Parameters

boundary_nodes : ExtendedGeoDataFrame Laterals, linked to the catchments by their key. catchments : ExtendedGeoDataFrame Catchment areas, with a boundary_node column. drrmodel : drr.DRRModel The RR model, with its nodes added. overflows : ExtendedGeoDataFrame, optional Overflow locations, each added as a boundary node. Defaults to None. greenhouse_laterals : ExtendedGeoDataFrame, optional Outlet points of greenhouse areas, each added as a boundary node. Defaults to None.

Source code in hydrolib/dhydamo/io/drrreader.py
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
@validate_call(
    config=ConfigDict(
        arbitrary_types_allowed=True, coerce_numbers_to_str=True, defer_build=True
    )
)
def boundary_from_input(
    self,
    boundary_nodes: ExtendedGeoDataFrame,
    catchments: ExtendedGeoDataFrame,
    drrmodel: drr.DRRModel,
    overflows: ExtendedGeoDataFrame | None = None,
    greenhouse_laterals: ExtendedGeoDataFrame | None = None,
) -> None:
    """Add the RR boundary nodes, which link the RR nodes to the FM laterals.

    Call this after the RR nodes are added. Catchments without any RR node with an
    area are removed from ``catchments``, in place.

    Parameters
    ----------
    boundary_nodes : ExtendedGeoDataFrame
        Laterals, linked to the catchments by their key.
    catchments : ExtendedGeoDataFrame
        Catchment areas, with a ``boundary_node`` column.
    drrmodel : drr.DRRModel
        The RR model, with its nodes added.
    overflows : ExtendedGeoDataFrame, optional
        Overflow locations, each added as a boundary node. Defaults to None.
    greenhouse_laterals : ExtendedGeoDataFrame, optional
        Outlet points of greenhouse areas, each added as a boundary node. Defaults to
        None.
    """
    # boundary nodes of the RR nodes with an area
    nodes_with_area = set()
    for node in drrmodel.unpaved.unp_nodes.values():
        # an unpaved node has an area per land use
        land_use_areas = [float(area) for area in node["ar"].split(" ")]
        if np.sum(land_use_areas) > 0.0:
            nodes_with_area.add(node["boundary_node"])
    for nodes in (
        drrmodel.paved.pav_nodes,
        drrmodel.greenhouse.gh_nodes,
        drrmodel.openwater.ow_nodes,
    ):
        for node in nodes.values():
            if float(node["ar"]) > 0.0:
                nodes_with_area.add(node["boundary_node"])

    # the catchments that have no area attached and no nodes that will be attached to the boundary
    not_occurring = [
        node for node in catchments["boundary_node"] if node not in nodes_with_area
    ]

    drop_idx = catchments[
        catchments.boundary_node.isin(not_occurring)
    ].index.to_list()
    if drop_idx:
        logger.warning(
            "%d catchments removed because of an area of 0 m2.",
            len(drop_idx),
        )
        # inplace: returning a copy of an ExtendedGeoDataFrame gives a plain GeoDataFrame
        catchments.drop(drop_idx, inplace=True)  # noqa: PD002

    catchment_lat = DamoRelations.CATCHMENT_LATERAL
    for cat in catchments.itertuples():
        lateral_id = getattr(cat, catchment_lat.foreign_key)
        lat = boundary_nodes[boundary_nodes[catchment_lat.parent_key] == lateral_id]
        if lat.empty:
            logger.warning(
                f"{cat.code} not connected to a boundary node. Skipping."
            )
            self.external_forcings.add_boundary_node(id="0.0", px="0.0", py="0.0")
            continue
        self.external_forcings.add_boundary_node(
            id=f"lat_{cat.code}",
            px=str(lat.geometry.x.iloc[0]).strip(),
            py=str(lat.geometry.y.iloc[0]).strip(),
        )
    if overflows is not None:
        logger.info("Adding overflows to the boundary nodes.")
        for ovf, ovf_geometry in zip(overflows.itertuples(), overflows.geometry):
            self.external_forcings.add_boundary_node(
                id=str(ovf.code),
                px=str(ovf_geometry.coords[0][0]),
                py=str(ovf_geometry.coords[0][1]),
            )
    if greenhouse_laterals is not None:
        logger.info("Adding greenhouse_laterals to the boundary nodes.")
        for gh, gh_geometry in zip(
            greenhouse_laterals.itertuples(), greenhouse_laterals.geometry
        ):
            self.external_forcings.add_boundary_node(
                id=str(gh.code),
                px=str(gh_geometry.coords[0][0]),
                py=str(gh_geometry.coords[0][1]),
            )
evap_from_input(areas: ExtendedGeoDataFrame, evap_folder: Path | str | None = None, evap_file: Path | str | None = None, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add an evaporation time series per meteo area, or use an existing meteo file.

Parameters

areas : ExtendedGeoDataFrame Meteo areas for which time series are created. evap_folder : str or Path, optional Folder with evaporation rasters, one per time step. Only used without evap_file. Defaults to None. evap_file : str or Path, optional Existing meteo file (.evp), used instead of the rasters. Defaults to None. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Raises

ValueError If neither evap_folder nor evap_file is given.

Source code in hydrolib/dhydamo/io/drrreader.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def evap_from_input(
    self,
    areas: ExtendedGeoDataFrame,
    evap_folder: Path | str | None = None,
    evap_file: Path | str | None = None,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add an evaporation time series per meteo area, or use an existing meteo file.

    Parameters
    ----------
    areas : ExtendedGeoDataFrame
        Meteo areas for which time series are created.
    evap_folder : str or Path, optional
        Folder with evaporation rasters, one per time step. Only used without
        ``evap_file``. Defaults to None.
    evap_file : str or Path, optional
        Existing meteo file (``.evp``), used instead of the rasters. Defaults to None.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.

    Raises
    ------
    ValueError
        If neither ``evap_folder`` nor ``evap_file`` is given.
    """
    if evap_file is None:
        if evap_folder is None:
            raise ValueError("Provide evap_folder or evap_file.")
        # aggregated evap
        # areas['dissolve'] = 1
        # agg_areas = areas.iloc[0:len(areas),:].dissolve(by='dissolve',aggfunc='mean')
        # sorted: the time series follows the order of the files
        paths = sorted(Path(evap_folder).iterdir())
        stats = zonal.zonal_stats_per_raster(
            gpd.GeoDataFrame(areas),
            paths,
            "mean",
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            progress=True,
        )
        result = pd.DataFrame(
            stats.to_numpy().T,
            index=[
                self.external_forcings.drrmodel._time_from_filename(path)
                for path in paths
            ],
            columns=["ms_" + str(area) for area in areas.code],
        )
        for column, series in result.items():
            self.external_forcings.add_evap(str(column), series)
    else:
        self.external_forcings.evap = str(evap_file)
precip_from_input(areas: ExtendedGeoDataFrame, precip_folder: Path | str | None = None, precip_file: Path | str | None = None, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add a precipitation time series per meteo area, or use an existing meteo file.

Parameters

areas : ExtendedGeoDataFrame Meteo areas for which time series are created. precip_folder : str or Path, optional Folder with precipitation rasters, one per time step. Only used without precip_file. Defaults to None. precip_file : str or Path, optional Existing meteo file (.bui), used instead of the rasters. Defaults to None. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Raises

ValueError If neither precip_folder nor precip_file is given.

Source code in hydrolib/dhydamo/io/drrreader.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def precip_from_input(
    self,
    areas: ExtendedGeoDataFrame,
    precip_folder: Path | str | None = None,
    precip_file: Path | str | None = None,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add a precipitation time series per meteo area, or use an existing meteo file.

    Parameters
    ----------
    areas : ExtendedGeoDataFrame
        Meteo areas for which time series are created.
    precip_folder : str or Path, optional
        Folder with precipitation rasters, one per time step. Only used without
        ``precip_file``. Defaults to None.
    precip_file : str or Path, optional
        Existing meteo file (``.bui``), used instead of the rasters. Defaults to None.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.

    Raises
    ------
    ValueError
        If neither ``precip_folder`` nor ``precip_file`` is given.
    """
    if precip_file is None:
        if precip_folder is None:
            raise ValueError("Provide precip_folder or precip_file.")
        # sorted: the time series follows the order of the files
        paths = sorted(Path(precip_folder).iterdir())
        stats = zonal.zonal_stats_per_raster(
            gpd.GeoDataFrame(areas),
            paths,
            "mean",
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            progress=True,
        )
        result = pd.DataFrame(
            stats.to_numpy().T,
            index=[
                self.external_forcings.drrmodel._time_from_filename(path)
                for path in paths
            ],
            columns=["ms_" + str(area) for area in areas.code],
        )
        for column, series in result.items():
            self.external_forcings.add_precip(str(column), series)
    else:
        self.external_forcings.precip = str(precip_file)
seepage_from_input(catchments: ExtendedGeoDataFrame, seepage_folder: Path | str, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add a seepage time series per catchment, the mean of each raster in a folder.

The time of each step is read from the raster (IDF or netCDF).

Parameters

catchments : ExtendedGeoDataFrame Catchment areas. seepage_folder : str or Path Folder with the seepage rasters, one per time step. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Source code in hydrolib/dhydamo/io/drrreader.py
 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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def seepage_from_input(
    self,
    catchments: ExtendedGeoDataFrame,
    seepage_folder: Path | str,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add a seepage time series per catchment, the mean of each raster in a folder.

    The time of each step is read from the raster (IDF or netCDF).

    Parameters
    ----------
    catchments : ExtendedGeoDataFrame
        Catchment areas.
    seepage_folder : str or Path
        Folder with the seepage rasters, one per time step.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.
    """
    rasters: list[zonal.Raster] = []
    times: list[pd.Timestamp] = []
    affine = raster_crs = nodata = None
    # sorted: the time series follows the order of the files
    for path in sorted(Path(seepage_folder).iterdir()):
        if path.suffix == ".idf":
            # Lazy: zonal_stats_per_raster reads it when its turn comes.
            dataset = idfreader.open(path).squeeze()
            if affine is None:
                affine = idfreader.affine_from_idf(dataset)
                raster_crs = dataset.attrs.get("crs")
                nodata = dataset.attrs.get("nodata", np.nan)
            elif idfreader.affine_from_idf(dataset) != affine:
                raise ValueError(
                    f"IDF seepage file {path.name} differs in grid from the others."
                )
            rasters.append(dataset)
            # the one time of the file
            times.append(pd.DatetimeIndex(dataset["time"].to_numpy().ravel())[0])
        else:
            rasters.append(path)
            times.append(self.external_forcings.drrmodel._time_from_filename(path))
    stats = zonal.zonal_stats_per_raster(
        gpd.GeoDataFrame(catchments),
        rasters,
        "mean",
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
        affine=affine,
        raster_crs=raster_crs,
        nodata=nodata,
        progress=True,
    )
    result = pd.DataFrame(
        stats.to_numpy().T,
        index=times,
        columns=["sep_" + str(cat) for cat in catchments.code],
    )
    if affine is not None:
        # if an NHI model (IDF files) is used, convert units from m3 to mm/d
        result = (result / (1e-3 * (affine[0] * -affine[4]))) / (
            (times[2] - times[1]).total_seconds() / 86400.0
        )
    for column, series in result.items():
        self.external_forcings.add_seepage(str(column), series)

GreenhouseIO

Fill the greenhouse nodes of an RR model from catchments, greenhouse areas and rasters.

Parameters

greenhouse : drr.Greenhouse The greenhouse nodes of the RR model, filled in place.

Source code in hydrolib/dhydamo/io/drrreader.py
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
class GreenhouseIO:
    """Fill the greenhouse nodes of an RR model from catchments, greenhouse areas and rasters.

    Parameters
    ----------
    greenhouse : drr.Greenhouse
        The greenhouse nodes of the RR model, filled in place.
    """

    def __init__(self, greenhouse: drr.Greenhouse) -> None:
        self.greenhouse = greenhouse

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def greenhouse_from_input(
        self,
        catchments: ExtendedGeoDataFrame,
        landuse: Path | str,
        surface_level: Path | str,
        roof_storage: StrictStr | float,
        meteo_areas: ExtendedGeoDataFrame,
        greenhouse_areas: ExtendedGeoDataFrame | None = None,
        greenhouse_laterals: ExtendedGeoDataFrame | None = None,
        basin_storage_class: int = 2,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add the greenhouse nodes: one per greenhouse area, and one per catchment.

        The catchment node gets the greenhouse area of the land use raster, minus what
        is already in the greenhouse areas.

        Parameters
        ----------
        catchments : ExtendedGeoDataFrame
            Catchment areas.
        landuse : str or Path
            Land use raster.
        surface_level : str or Path
            Surface level raster.
        roof_storage : str or float
            Roof storage (mm): a number for a uniform value, or a raster.
        meteo_areas : ExtendedGeoDataFrame
            Meteo areas; each node gets the meteo station of the area that contains its
            centroid.
        greenhouse_areas : ExtendedGeoDataFrame, optional
            Known greenhouse areas, optionally with a ``basin_storage_class`` column.
            Defaults to None.
        greenhouse_laterals : ExtendedGeoDataFrame, optional
            Outlet points of the greenhouse areas, required with ``greenhouse_areas``.
            Defaults to None.
        basin_storage_class : int, optional
            Basin storage class of greenhouses without their own. Defaults to 2.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.

        Raises
        ------
        ValueError
            If ``greenhouse_areas`` is given without ``greenhouse_laterals``.
        """
        px_area, reference_crs = _raster_metadata(landuse)

        lu_counts = self.greenhouse.drrmodel.zonal_cache.zonal_category_counts(
            gpd.GeoDataFrame(catchments),
            landuse,
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )
        stats_elev = self.greenhouse.drrmodel.zonal_cache.zonal_stats(
            gpd.GeoDataFrame(catchments),
            surface_level,
            statistics=("median",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )
        if greenhouse_areas is not None:
            stats_elev_gh = zonal.zonal_stats(
                gpd.GeoDataFrame(greenhouse_areas),
                surface_level,
                statistics=("median",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
            )

        # optional rasters
        if isinstance(roof_storage, (Path, str)):
            roofstors = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                roof_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
            if greenhouse_areas is not None:
                roofstors_gh = zonal.zonal_stats(
                    gpd.GeoDataFrame(greenhouse_areas),
                    roof_storage,
                    statistics=("mean",),
                    min_coverage_frac=min_coverage_frac,
                    coverage_weight=coverage_weight,
                    strategy="feature-sequential",
                    raster_crs=reference_crs,
                )

        gh_columns = [
            "id",
            "area",
            "surface_level",
            "roof_storage",
            "basin_storage_class",
            "meteo_area",
            "px",
            "py",
            "boundary_node",
        ]
        if greenhouse_areas is not None:
            if greenhouse_laterals is None:
                raise ValueError(
                    "greenhouse_laterals is required with greenhouse_areas."
                )
            for num, (gh, gh_geometry) in enumerate(
                zip(greenhouse_areas.itertuples(), greenhouse_areas.geometry)
            ):
                # find corresponding meteo-station
                if pd.isna(stats_elev_gh.iloc[num]["median"]):
                    logger.warning(NO_RASTERDATA_WARNING, gh.code)
                    self.greenhouse.add_greenhouse(**dict.fromkeys(gh_columns, "0.0"))
                    continue
                ms = _meteo_area(meteo_areas, gh_geometry.centroid)

                elev = stats_elev_gh.iloc[num]["median"]
                # optional columns: a missing column counts as no value
                roof_storage_mm = getattr(gh, "roof_storage_mm", np.nan)
                gh_basin_storage_class = getattr(gh, "basin_storage_class", np.nan)
                if not pd.isna(roof_storage_mm):
                    roof_storage_val = f"{roof_storage_mm:.2f}"
                elif isinstance(roof_storage, float):
                    roof_storage_val = f"{roof_storage:.2f}"
                else:
                    roof_storage_val = f"{roofstors_gh.iloc[num]['mean']:.2f}"
                if not pd.isna(gh_basin_storage_class):
                    basin_storage_class_val = f"{gh_basin_storage_class:g}"
                else:
                    basin_storage_class_val = f"{basin_storage_class:g}"
                gh_area = OwnRelations.GREENHOUSE_LATERAL_AREA
                area_id = getattr(gh, gh_area.parent_key)
                related_laterals = greenhouse_laterals[
                    greenhouse_laterals[gh_area.foreign_key] == area_id
                ]
                latcode = related_laterals.code.to_numpy()[0]
                self.greenhouse.add_greenhouse(
                    id=str(gh.code),
                    area=f"{gh_geometry.area:.2f}",
                    surface_level=f"{elev:.2f}",
                    roof_storage=roof_storage_val,
                    basin_storage_class=basin_storage_class_val,
                    meteo_area=str(ms),
                    px=f"{gh_geometry.centroid.coords[0][0]:.0f}",
                    py=f"{gh_geometry.centroid.coords[0][1]:.0f}",
                    boundary_node=str(latcode),
                )

        for num, (cat, cat_geometry) in enumerate(
            zip(catchments.itertuples(), catchments.geometry)
        ):
            # if no rasterdata could be obtained for this catchment, skip it.
            if pd.isna(stats_elev.iloc[num]["median"]):
                logger.warning(NO_RASTERDATA_WARNING, cat.code)
                self.greenhouse.add_greenhouse(**dict.fromkeys(gh_columns, "0.0"))
                continue

            # find corresponding meteo-station
            ms = _meteo_area(meteo_areas, cat_geometry.centroid)

            if (
                greenhouse_areas is not None
                and cat_geometry.intersects(greenhouse_areas.geometry).any()
            ):
                intersection_area = greenhouse_areas.geometry.intersection(
                    cat_geometry
                ).area
                intersection_area = intersection_area[
                    intersection_area > 0.0
                ].to_numpy()[0]
                landuse_counts = lu_counts.iloc[num]
                if landuse_counts.get(15, 0) > 0:
                    # divide area to subtract between greenhouses and the most occurring area
                    logger.info(
                        "Catchment: %s: subtracting %s m2 from greenhouse area in landuse map.",
                        cat.code,
                        np.min([(landuse_counts[15] * px_area, intersection_area)]),
                    )
                    lu_counts.loc[lu_counts.index[num], 15] = np.max(
                        [
                            0.0,
                            landuse_counts[15] - np.round(intersection_area / px_area),
                        ]
                    )

            elev = stats_elev.iloc[num]["median"]
            roof_storage_val = (
                f"{roof_storage:.2f}"
                if isinstance(roof_storage, float)
                else f"{roofstors.iloc[num]['mean']:.2f}"
            )
            self.greenhouse.add_greenhouse(
                id=str(cat.code),
                area=(str(lu_counts.iloc[num].get(15, 0) * px_area)),
                surface_level=f"{elev:.2f}",
                roof_storage=roof_storage_val,
                basin_storage_class=f"{basin_storage_class:g}",
                meteo_area=str(ms),
                px=f"{cat_geometry.centroid.coords[0][0] + 20:.0f}",
                py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
                boundary_node=str(cat.boundary_node),
            )
greenhouse_from_input(catchments: ExtendedGeoDataFrame, landuse: Path | str, surface_level: Path | str, roof_storage: StrictStr | float, meteo_areas: ExtendedGeoDataFrame, greenhouse_areas: ExtendedGeoDataFrame | None = None, greenhouse_laterals: ExtendedGeoDataFrame | None = None, basin_storage_class: int = 2, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add the greenhouse nodes: one per greenhouse area, and one per catchment.

The catchment node gets the greenhouse area of the land use raster, minus what is already in the greenhouse areas.

Parameters

catchments : ExtendedGeoDataFrame Catchment areas. landuse : str or Path Land use raster. surface_level : str or Path Surface level raster. roof_storage : str or float Roof storage (mm): a number for a uniform value, or a raster. meteo_areas : ExtendedGeoDataFrame Meteo areas; each node gets the meteo station of the area that contains its centroid. greenhouse_areas : ExtendedGeoDataFrame, optional Known greenhouse areas, optionally with a basin_storage_class column. Defaults to None. greenhouse_laterals : ExtendedGeoDataFrame, optional Outlet points of the greenhouse areas, required with greenhouse_areas. Defaults to None. basin_storage_class : int, optional Basin storage class of greenhouses without their own. Defaults to 2. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Raises

ValueError If greenhouse_areas is given without greenhouse_laterals.

Source code in hydrolib/dhydamo/io/drrreader.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
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def greenhouse_from_input(
    self,
    catchments: ExtendedGeoDataFrame,
    landuse: Path | str,
    surface_level: Path | str,
    roof_storage: StrictStr | float,
    meteo_areas: ExtendedGeoDataFrame,
    greenhouse_areas: ExtendedGeoDataFrame | None = None,
    greenhouse_laterals: ExtendedGeoDataFrame | None = None,
    basin_storage_class: int = 2,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add the greenhouse nodes: one per greenhouse area, and one per catchment.

    The catchment node gets the greenhouse area of the land use raster, minus what
    is already in the greenhouse areas.

    Parameters
    ----------
    catchments : ExtendedGeoDataFrame
        Catchment areas.
    landuse : str or Path
        Land use raster.
    surface_level : str or Path
        Surface level raster.
    roof_storage : str or float
        Roof storage (mm): a number for a uniform value, or a raster.
    meteo_areas : ExtendedGeoDataFrame
        Meteo areas; each node gets the meteo station of the area that contains its
        centroid.
    greenhouse_areas : ExtendedGeoDataFrame, optional
        Known greenhouse areas, optionally with a ``basin_storage_class`` column.
        Defaults to None.
    greenhouse_laterals : ExtendedGeoDataFrame, optional
        Outlet points of the greenhouse areas, required with ``greenhouse_areas``.
        Defaults to None.
    basin_storage_class : int, optional
        Basin storage class of greenhouses without their own. Defaults to 2.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.

    Raises
    ------
    ValueError
        If ``greenhouse_areas`` is given without ``greenhouse_laterals``.
    """
    px_area, reference_crs = _raster_metadata(landuse)

    lu_counts = self.greenhouse.drrmodel.zonal_cache.zonal_category_counts(
        gpd.GeoDataFrame(catchments),
        landuse,
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )
    stats_elev = self.greenhouse.drrmodel.zonal_cache.zonal_stats(
        gpd.GeoDataFrame(catchments),
        surface_level,
        statistics=("median",),
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )
    if greenhouse_areas is not None:
        stats_elev_gh = zonal.zonal_stats(
            gpd.GeoDataFrame(greenhouse_areas),
            surface_level,
            statistics=("median",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

    # optional rasters
    if isinstance(roof_storage, (Path, str)):
        roofstors = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            roof_storage,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )
        if greenhouse_areas is not None:
            roofstors_gh = zonal.zonal_stats(
                gpd.GeoDataFrame(greenhouse_areas),
                roof_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )

    gh_columns = [
        "id",
        "area",
        "surface_level",
        "roof_storage",
        "basin_storage_class",
        "meteo_area",
        "px",
        "py",
        "boundary_node",
    ]
    if greenhouse_areas is not None:
        if greenhouse_laterals is None:
            raise ValueError(
                "greenhouse_laterals is required with greenhouse_areas."
            )
        for num, (gh, gh_geometry) in enumerate(
            zip(greenhouse_areas.itertuples(), greenhouse_areas.geometry)
        ):
            # find corresponding meteo-station
            if pd.isna(stats_elev_gh.iloc[num]["median"]):
                logger.warning(NO_RASTERDATA_WARNING, gh.code)
                self.greenhouse.add_greenhouse(**dict.fromkeys(gh_columns, "0.0"))
                continue
            ms = _meteo_area(meteo_areas, gh_geometry.centroid)

            elev = stats_elev_gh.iloc[num]["median"]
            # optional columns: a missing column counts as no value
            roof_storage_mm = getattr(gh, "roof_storage_mm", np.nan)
            gh_basin_storage_class = getattr(gh, "basin_storage_class", np.nan)
            if not pd.isna(roof_storage_mm):
                roof_storage_val = f"{roof_storage_mm:.2f}"
            elif isinstance(roof_storage, float):
                roof_storage_val = f"{roof_storage:.2f}"
            else:
                roof_storage_val = f"{roofstors_gh.iloc[num]['mean']:.2f}"
            if not pd.isna(gh_basin_storage_class):
                basin_storage_class_val = f"{gh_basin_storage_class:g}"
            else:
                basin_storage_class_val = f"{basin_storage_class:g}"
            gh_area = OwnRelations.GREENHOUSE_LATERAL_AREA
            area_id = getattr(gh, gh_area.parent_key)
            related_laterals = greenhouse_laterals[
                greenhouse_laterals[gh_area.foreign_key] == area_id
            ]
            latcode = related_laterals.code.to_numpy()[0]
            self.greenhouse.add_greenhouse(
                id=str(gh.code),
                area=f"{gh_geometry.area:.2f}",
                surface_level=f"{elev:.2f}",
                roof_storage=roof_storage_val,
                basin_storage_class=basin_storage_class_val,
                meteo_area=str(ms),
                px=f"{gh_geometry.centroid.coords[0][0]:.0f}",
                py=f"{gh_geometry.centroid.coords[0][1]:.0f}",
                boundary_node=str(latcode),
            )

    for num, (cat, cat_geometry) in enumerate(
        zip(catchments.itertuples(), catchments.geometry)
    ):
        # if no rasterdata could be obtained for this catchment, skip it.
        if pd.isna(stats_elev.iloc[num]["median"]):
            logger.warning(NO_RASTERDATA_WARNING, cat.code)
            self.greenhouse.add_greenhouse(**dict.fromkeys(gh_columns, "0.0"))
            continue

        # find corresponding meteo-station
        ms = _meteo_area(meteo_areas, cat_geometry.centroid)

        if (
            greenhouse_areas is not None
            and cat_geometry.intersects(greenhouse_areas.geometry).any()
        ):
            intersection_area = greenhouse_areas.geometry.intersection(
                cat_geometry
            ).area
            intersection_area = intersection_area[
                intersection_area > 0.0
            ].to_numpy()[0]
            landuse_counts = lu_counts.iloc[num]
            if landuse_counts.get(15, 0) > 0:
                # divide area to subtract between greenhouses and the most occurring area
                logger.info(
                    "Catchment: %s: subtracting %s m2 from greenhouse area in landuse map.",
                    cat.code,
                    np.min([(landuse_counts[15] * px_area, intersection_area)]),
                )
                lu_counts.loc[lu_counts.index[num], 15] = np.max(
                    [
                        0.0,
                        landuse_counts[15] - np.round(intersection_area / px_area),
                    ]
                )

        elev = stats_elev.iloc[num]["median"]
        roof_storage_val = (
            f"{roof_storage:.2f}"
            if isinstance(roof_storage, float)
            else f"{roofstors.iloc[num]['mean']:.2f}"
        )
        self.greenhouse.add_greenhouse(
            id=str(cat.code),
            area=(str(lu_counts.iloc[num].get(15, 0) * px_area)),
            surface_level=f"{elev:.2f}",
            roof_storage=roof_storage_val,
            basin_storage_class=f"{basin_storage_class:g}",
            meteo_area=str(ms),
            px=f"{cat_geometry.centroid.coords[0][0] + 20:.0f}",
            py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
            boundary_node=str(cat.boundary_node),
        )

OpenwaterIO

Fill the open water nodes of an RR model from catchments and a land use raster.

Parameters

openwater : drr.Openwater The open water nodes of the RR model, filled in place.

Source code in hydrolib/dhydamo/io/drrreader.py
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
class OpenwaterIO:
    """Fill the open water nodes of an RR model from catchments and a land use raster.

    Parameters
    ----------
    openwater : drr.Openwater
        The open water nodes of the RR model, filled in place.
    """

    def __init__(self, openwater: drr.Openwater) -> None:
        self.openwater = openwater

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def openwater_from_input(
        self,
        catchments: ExtendedGeoDataFrame,
        landuse: Path | str,
        meteo_areas: ExtendedGeoDataFrame,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add an open water node per catchment, with the open water area of the land use raster.

        Parameters
        ----------
        catchments : ExtendedGeoDataFrame
            Catchment areas.
        landuse : str or Path
            Land use raster.
        meteo_areas : ExtendedGeoDataFrame
            Meteo areas; each node gets the meteo station of the area that contains its
            centroid.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.
        """
        px_area, _ = _raster_metadata(landuse)

        lu_counts = self.openwater.drrmodel.zonal_cache.zonal_category_counts(
            gpd.GeoDataFrame(catchments),
            landuse,
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

        for num, (cat, cat_geometry) in enumerate(
            zip(catchments.itertuples(), catchments.geometry)
        ):
            # find corresponding meteo-station
            ms = _meteo_area(meteo_areas, cat_geometry.centroid)

            self.openwater.add_openwater(
                id=str(cat.code),
                area=str(lu_counts.iloc[num].get(13, 0) * px_area),
                meteo_area=str(ms),
                px=f"{cat_geometry.centroid.coords[0][0] - 20:.0f}",
                py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
                boundary_node=str(cat.boundary_node),
            )
openwater_from_input(catchments: ExtendedGeoDataFrame, landuse: Path | str, meteo_areas: ExtendedGeoDataFrame, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add an open water node per catchment, with the open water area of the land use raster.

Parameters

catchments : ExtendedGeoDataFrame Catchment areas. landuse : str or Path Land use raster. meteo_areas : ExtendedGeoDataFrame Meteo areas; each node gets the meteo station of the area that contains its centroid. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Source code in hydrolib/dhydamo/io/drrreader.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def openwater_from_input(
    self,
    catchments: ExtendedGeoDataFrame,
    landuse: Path | str,
    meteo_areas: ExtendedGeoDataFrame,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add an open water node per catchment, with the open water area of the land use raster.

    Parameters
    ----------
    catchments : ExtendedGeoDataFrame
        Catchment areas.
    landuse : str or Path
        Land use raster.
    meteo_areas : ExtendedGeoDataFrame
        Meteo areas; each node gets the meteo station of the area that contains its
        centroid.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.
    """
    px_area, _ = _raster_metadata(landuse)

    lu_counts = self.openwater.drrmodel.zonal_cache.zonal_category_counts(
        gpd.GeoDataFrame(catchments),
        landuse,
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )

    for num, (cat, cat_geometry) in enumerate(
        zip(catchments.itertuples(), catchments.geometry)
    ):
        # find corresponding meteo-station
        ms = _meteo_area(meteo_areas, cat_geometry.centroid)

        self.openwater.add_openwater(
            id=str(cat.code),
            area=str(lu_counts.iloc[num].get(13, 0) * px_area),
            meteo_area=str(ms),
            px=f"{cat_geometry.centroid.coords[0][0] - 20:.0f}",
            py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
            boundary_node=str(cat.boundary_node),
        )

PavedIO

Fill the paved nodes of an RR model from catchments, sewer areas and rasters.

Parameters

paved : drr.Paved The paved nodes of the RR model, filled in place.

Source code in hydrolib/dhydamo/io/drrreader.py
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
class PavedIO:
    """Fill the paved nodes of an RR model from catchments, sewer areas and rasters.

    Parameters
    ----------
    paved : drr.Paved
        The paved nodes of the RR model, filled in place.
    """

    def __init__(self, paved: drr.Paved) -> None:
        self.paved = paved

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def paved_from_input(
        self,
        catchments: ExtendedGeoDataFrame,
        landuse: StrictStr | Path,
        surface_level: StrictStr | Path,
        street_storage: StrictStr | Path | float,
        sewer_storage: StrictStr | Path | float,
        pump_capacity: StrictStr | Path | float,
        meteo_areas: ExtendedGeoDataFrame,
        overflows: ExtendedGeoDataFrame | None = None,
        sewer_areas: ExtendedGeoDataFrame | None = None,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add the paved nodes: one per overflow of each sewer area, and one per catchment.

        The paved area of a catchment outside the sewer areas gets a node that drains to
        the catchment's boundary node.

        Parameters
        ----------
        catchments : ExtendedGeoDataFrame
            Catchment areas.
        landuse : str or Path
            Land use raster.
        surface_level : str or Path
            Surface level raster.
        street_storage : str, Path or float
            Street storage (mm): a number for a uniform value, or a raster.
        sewer_storage : str, Path or float
            Sewer storage (mm): a number for a uniform value, or a raster.
        pump_capacity : str, Path or float
            Pump capacity (mm/h): a number for a uniform value, or a raster.
        meteo_areas : ExtendedGeoDataFrame
            Meteo areas; each node gets the meteo station of the area that contains its
            centroid.
        overflows : ExtendedGeoDataFrame, optional
            Overflow locations, required with ``sewer_areas``. Defaults to None.
        sewer_areas : ExtendedGeoDataFrame, optional
            Sewer areas. Defaults to None.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.

        Raises
        ------
        ValueError
            If ``sewer_areas`` is given without ``overflows``.
        """
        px_area, reference_crs = _raster_metadata(landuse)

        lu_counts = self.paved.drrmodel.zonal_cache.zonal_category_counts(
            gpd.GeoDataFrame(catchments),
            landuse,
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )
        stats_elev = self.paved.drrmodel.zonal_cache.zonal_stats(
            gpd.GeoDataFrame(catchments),
            surface_level,
            statistics=("median",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

        if isinstance(street_storage, (Path, str)):
            str_stors = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                street_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )

        if isinstance(sewer_storage, (Path, str)):
            sew_stors = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                sewer_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )

        if isinstance(pump_capacity, (Path, str)):
            # raster of POC in mm/h
            pump_caps = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                pump_capacity,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        paved_columns = [
            "id",
            "area",
            "surface_level",
            "street_storage",
            "sewer_storage",
            "pump_capacity",
            "meteo_area",
            "px",
            "py",
            "boundary_node",
        ]
        if sewer_areas is not None:
            # if the parameters ara rasters, do the zonal statistics per sewage area as well.
            if isinstance(street_storage, (Path, str)):
                str_stors_sa = zonal.zonal_stats(
                    gpd.GeoDataFrame(sewer_areas),
                    street_storage,
                    statistics=("mean",),
                    min_coverage_frac=min_coverage_frac,
                    coverage_weight=coverage_weight,
                    strategy="feature-sequential",
                    raster_crs=reference_crs,
                )
            if isinstance(sewer_storage, (Path, str)):
                sew_stors_sa = zonal.zonal_stats(
                    gpd.GeoDataFrame(sewer_areas),
                    sewer_storage,
                    statistics=("mean",),
                    min_coverage_frac=min_coverage_frac,
                    coverage_weight=coverage_weight,
                    strategy="feature-sequential",
                    raster_crs=reference_crs,
                )
            if isinstance(pump_capacity, (Path, str)):
                pump_caps_sa = zonal.zonal_stats(
                    gpd.GeoDataFrame(sewer_areas),
                    pump_capacity,
                    statistics=("mean",),
                    min_coverage_frac=min_coverage_frac,
                    coverage_weight=coverage_weight,
                    strategy="feature-sequential",
                    raster_crs=reference_crs,
                )
            stats_sa_elev = zonal.zonal_stats(
                gpd.GeoDataFrame(sewer_areas),
                surface_level,
                statistics=("median",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
            )
            sewer_lu_counts = zonal.zonal_category_counts(
                gpd.GeoDataFrame(sewer_areas),
                landuse,
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
            )

            if overflows is None:
                raise ValueError("overflows is required with sewer_areas.")
            # find the paved area in the sewer areas
            for isew, (sew, sew_geometry) in enumerate(
                zip(sewer_areas.itertuples(), sewer_areas.geometry)
            ):
                sewer_pav_area = 0
                pixels = sewer_lu_counts.iloc[isew]
                pav_pixels = pixels.get(14, 0)
                if pav_pixels == 0:
                    logger.warning("No paved area in sewer area %s.", sew.code)
                    self.paved.add_paved(**dict.fromkeys(paved_columns, "0.0"))
                    continue
                sewer_pav_area += pav_pixels * px_area

                # subtract it fromthe total paved area in this catchment, make sure at least 0 remains
                # lu_counts[cat_ind][14.0] -=  pav_pixels
                # if lu_counts[cat_ind][14.0] < 0: lu_counts[cat_ind][14.0]  = 0

                elev = stats_sa_elev.iloc[isew]["median"]
                # find overflows related to this sewer area
                overflow_sa = OwnRelations.OVERFLOW_SEWER_AREA
                sewer_id = getattr(sew, overflow_sa.parent_key)
                ovf = overflows[overflows[overflow_sa.foreign_key] == sewer_id]
                for ov, ov_geometry in zip(ovf.itertuples(), ovf.geometry):
                    # find corresponding meteo-station
                    ms = _meteo_area(meteo_areas, sew_geometry.centroid)

                    # if a float is given, a standard value is passed. If a string is given, a rastername is assumed to zonal statistics are applied.
                    if isinstance(street_storage, float):
                        street_storage_val = f"{street_storage:.2f}"
                    elif isinstance(street_storage, (Path, str)):
                        street_storage_val = f"{str_stors_sa.iloc[isew]['mean']:.2f}"
                    else:
                        raise TypeError(
                            "Street_storage has the wrong datatype. It should be a filename (Path or string) or number (float or int)."
                        )

                    # three options: it can be an attribute of a sewer area, a uniform value or a raster
                    riool_berging_mm = getattr(sew, "riool_berging_mm", None)
                    if (
                        riool_berging_mm is None
                        or np.isnan(riool_berging_mm)
                        or not isinstance(riool_berging_mm, float)
                    ):
                        if isinstance(sewer_storage, float):
                            sewer_storage_val = f"{sewer_storage:.2f}"
                        elif isinstance(sewer_storage, (Path, str)):
                            sewer_storage_val = f"{sew_stors_sa.iloc[isew]['mean']:.2f}"
                        else:
                            raise TypeError(
                                "Sewer_storage has the wrong datatype. It should be a filename (Path or string) or number (float or int)."
                            )
                    else:
                        sewer_storage_val = f"{riool_berging_mm:.2f}"

                    # three options: it can be an attribute of a sewer area, a uniform value or a raster
                    riool_poc_m3s = getattr(sew, "riool_poc_m3s", None)
                    if (
                        riool_poc_m3s is None
                        or np.isnan(riool_poc_m3s)
                        or not isinstance(riool_poc_m3s, float)
                    ):
                        if isinstance(pump_capacity, float):
                            # convert the value from mm/h to m3/s
                            pump_capacity_val = f"{pump_capacity * (float(sewer_pav_area) * ov.fractie) / (1000.0 * 3600.0):.8f}"
                        elif isinstance(pump_capacity, (Path, str)):
                            # convert the value (extracted from the raster) from mm/h to m3/s
                            pump_capacity_val = f"{pump_caps_sa.iloc[isew]['mean'] * (float(sewer_pav_area) * ov.fractie) / (1000.0 * 3600.0):.8f}"
                        else:
                            raise TypeError(
                                "Pump_capacity has the wrong datatype. It should be a filename (Path or string) or number (float or int)."
                            )
                    else:
                        # use the attribute value
                        pump_capacity_val = f"{riool_poc_m3s * ov.fractie:.8f}"

                    # add prefix to the overflow id to create the paved-node id
                    self.paved.add_paved(
                        id=str(ov.code),
                        area=str(sewer_pav_area * ov.fractie),
                        surface_level=f"{elev:.2f}",
                        street_storage=street_storage_val,
                        sewer_storage=sewer_storage_val,
                        pump_capacity=pump_capacity_val,
                        meteo_area=str(ms),
                        px=f"{ov_geometry.coords[0][0] + 10:.0f}",
                        py=f"{ov_geometry.coords[0][1]:.0f}",
                        boundary_node=ov.code,
                    )

        if sewer_areas is not None:
            # Land use of the catchment parts outside the sewer areas, by
            # catchment position. Catchments that overlap no sewer area use
            # lu_counts.
            sewer_union = sewer_areas.union_all()
            # GeoSeries(...): the stubs type reset_index as a plain Series
            geometries = gpd.GeoSeries(catchments.geometry.reset_index(drop=True))
            overlaps = geometries.intersects(sewer_union)
            # the stubs type a masked GeoSeries as Series[BaseGeometry]; it is a GeoSeries
            outside = geometries[overlaps].difference(sewer_union)  # type: ignore[operator]
            outside = outside[outside.area > 0]
            outside_counts = pd.DataFrame()
            if not outside.empty:
                outside_counts = zonal.zonal_category_counts(
                    outside,
                    landuse,
                    min_coverage_frac=min_coverage_frac,
                    coverage_weight=coverage_weight,
                    strategy="feature-sequential",
                )

        for num, (cat, cat_geometry) in enumerate(
            zip(catchments.itertuples(), catchments.geometry)
        ):
            # if no rasterdata could be obtained for this catchment, skip it.
            if pd.isna(stats_elev.iloc[num]["median"]):
                logger.warning(NO_RASTERDATA_WARNING, cat.code)
                self.paved.add_paved(**dict.fromkeys(paved_columns, "0.0"))
                continue
            if sewer_areas is None or not overlaps[num]:
                pav_area = str(lu_counts.iloc[num].get(14, 0) * px_area)
            elif num in outside_counts.index:
                pav_area = str(outside_counts.loc[num].get(14, 0) * px_area)
            else:
                logger.info(
                    f"No paved area outside sewer area in catchments {cat.code}."
                )
                pav_area = "0.0"

            # find corresponding meteo-station
            ms = _meteo_area(meteo_areas, cat_geometry.centroid)

            elev = stats_elev.iloc[num]["median"]
            # if a float is given, a standard value is passed. If a string is given, a rastername is assumed to zonal statistics are applied.
            street_storage_val = (
                f"{street_storage:.2f}"
                if isinstance(street_storage, float)
                else f"{str_stors.iloc[num]['mean']:.2f}"
            )
            sewer_storage_val = (
                f"{sewer_storage:.2f}"
                if isinstance(sewer_storage, float)
                else f"{sew_stors.iloc[num]['mean']:.2f}"
            )
            pump_capacity_val = (
                f"{(pump_capacity * float(pav_area)) / (1000.0 * 3600.0):.8f}"
                if isinstance(pump_capacity, float)
                else f"{pump_caps.iloc[num]['mean'] * (float(pav_area)) / (1000.0 * 3600.0):.8f}"
            )
            self.paved.add_paved(
                id=str(cat.code),
                area=str(pav_area),
                surface_level=f"{elev:.2f}",
                street_storage=street_storage_val,
                sewer_storage=sewer_storage_val,
                pump_capacity=pump_capacity_val,
                meteo_area=str(ms),
                px=f"{cat_geometry.centroid.coords[0][0] + 10:.0f}",
                py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
                boundary_node=str(cat.boundary_node),
            )
paved_from_input(catchments: ExtendedGeoDataFrame, landuse: StrictStr | Path, surface_level: StrictStr | Path, street_storage: StrictStr | Path | float, sewer_storage: StrictStr | Path | float, pump_capacity: StrictStr | Path | float, meteo_areas: ExtendedGeoDataFrame, overflows: ExtendedGeoDataFrame | None = None, sewer_areas: ExtendedGeoDataFrame | None = None, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add the paved nodes: one per overflow of each sewer area, and one per catchment.

The paved area of a catchment outside the sewer areas gets a node that drains to the catchment's boundary node.

Parameters

catchments : ExtendedGeoDataFrame Catchment areas. landuse : str or Path Land use raster. surface_level : str or Path Surface level raster. street_storage : str, Path or float Street storage (mm): a number for a uniform value, or a raster. sewer_storage : str, Path or float Sewer storage (mm): a number for a uniform value, or a raster. pump_capacity : str, Path or float Pump capacity (mm/h): a number for a uniform value, or a raster. meteo_areas : ExtendedGeoDataFrame Meteo areas; each node gets the meteo station of the area that contains its centroid. overflows : ExtendedGeoDataFrame, optional Overflow locations, required with sewer_areas. Defaults to None. sewer_areas : ExtendedGeoDataFrame, optional Sewer areas. Defaults to None. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Raises

ValueError If sewer_areas is given without overflows.

Source code in hydrolib/dhydamo/io/drrreader.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def paved_from_input(
    self,
    catchments: ExtendedGeoDataFrame,
    landuse: StrictStr | Path,
    surface_level: StrictStr | Path,
    street_storage: StrictStr | Path | float,
    sewer_storage: StrictStr | Path | float,
    pump_capacity: StrictStr | Path | float,
    meteo_areas: ExtendedGeoDataFrame,
    overflows: ExtendedGeoDataFrame | None = None,
    sewer_areas: ExtendedGeoDataFrame | None = None,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add the paved nodes: one per overflow of each sewer area, and one per catchment.

    The paved area of a catchment outside the sewer areas gets a node that drains to
    the catchment's boundary node.

    Parameters
    ----------
    catchments : ExtendedGeoDataFrame
        Catchment areas.
    landuse : str or Path
        Land use raster.
    surface_level : str or Path
        Surface level raster.
    street_storage : str, Path or float
        Street storage (mm): a number for a uniform value, or a raster.
    sewer_storage : str, Path or float
        Sewer storage (mm): a number for a uniform value, or a raster.
    pump_capacity : str, Path or float
        Pump capacity (mm/h): a number for a uniform value, or a raster.
    meteo_areas : ExtendedGeoDataFrame
        Meteo areas; each node gets the meteo station of the area that contains its
        centroid.
    overflows : ExtendedGeoDataFrame, optional
        Overflow locations, required with ``sewer_areas``. Defaults to None.
    sewer_areas : ExtendedGeoDataFrame, optional
        Sewer areas. Defaults to None.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.

    Raises
    ------
    ValueError
        If ``sewer_areas`` is given without ``overflows``.
    """
    px_area, reference_crs = _raster_metadata(landuse)

    lu_counts = self.paved.drrmodel.zonal_cache.zonal_category_counts(
        gpd.GeoDataFrame(catchments),
        landuse,
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )
    stats_elev = self.paved.drrmodel.zonal_cache.zonal_stats(
        gpd.GeoDataFrame(catchments),
        surface_level,
        statistics=("median",),
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )

    if isinstance(street_storage, (Path, str)):
        str_stors = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            street_storage,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )

    if isinstance(sewer_storage, (Path, str)):
        sew_stors = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            sewer_storage,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )

    if isinstance(pump_capacity, (Path, str)):
        # raster of POC in mm/h
        pump_caps = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            pump_capacity,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )
    paved_columns = [
        "id",
        "area",
        "surface_level",
        "street_storage",
        "sewer_storage",
        "pump_capacity",
        "meteo_area",
        "px",
        "py",
        "boundary_node",
    ]
    if sewer_areas is not None:
        # if the parameters ara rasters, do the zonal statistics per sewage area as well.
        if isinstance(street_storage, (Path, str)):
            str_stors_sa = zonal.zonal_stats(
                gpd.GeoDataFrame(sewer_areas),
                street_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        if isinstance(sewer_storage, (Path, str)):
            sew_stors_sa = zonal.zonal_stats(
                gpd.GeoDataFrame(sewer_areas),
                sewer_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        if isinstance(pump_capacity, (Path, str)):
            pump_caps_sa = zonal.zonal_stats(
                gpd.GeoDataFrame(sewer_areas),
                pump_capacity,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        stats_sa_elev = zonal.zonal_stats(
            gpd.GeoDataFrame(sewer_areas),
            surface_level,
            statistics=("median",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )
        sewer_lu_counts = zonal.zonal_category_counts(
            gpd.GeoDataFrame(sewer_areas),
            landuse,
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

        if overflows is None:
            raise ValueError("overflows is required with sewer_areas.")
        # find the paved area in the sewer areas
        for isew, (sew, sew_geometry) in enumerate(
            zip(sewer_areas.itertuples(), sewer_areas.geometry)
        ):
            sewer_pav_area = 0
            pixels = sewer_lu_counts.iloc[isew]
            pav_pixels = pixels.get(14, 0)
            if pav_pixels == 0:
                logger.warning("No paved area in sewer area %s.", sew.code)
                self.paved.add_paved(**dict.fromkeys(paved_columns, "0.0"))
                continue
            sewer_pav_area += pav_pixels * px_area

            # subtract it fromthe total paved area in this catchment, make sure at least 0 remains
            # lu_counts[cat_ind][14.0] -=  pav_pixels
            # if lu_counts[cat_ind][14.0] < 0: lu_counts[cat_ind][14.0]  = 0

            elev = stats_sa_elev.iloc[isew]["median"]
            # find overflows related to this sewer area
            overflow_sa = OwnRelations.OVERFLOW_SEWER_AREA
            sewer_id = getattr(sew, overflow_sa.parent_key)
            ovf = overflows[overflows[overflow_sa.foreign_key] == sewer_id]
            for ov, ov_geometry in zip(ovf.itertuples(), ovf.geometry):
                # find corresponding meteo-station
                ms = _meteo_area(meteo_areas, sew_geometry.centroid)

                # if a float is given, a standard value is passed. If a string is given, a rastername is assumed to zonal statistics are applied.
                if isinstance(street_storage, float):
                    street_storage_val = f"{street_storage:.2f}"
                elif isinstance(street_storage, (Path, str)):
                    street_storage_val = f"{str_stors_sa.iloc[isew]['mean']:.2f}"
                else:
                    raise TypeError(
                        "Street_storage has the wrong datatype. It should be a filename (Path or string) or number (float or int)."
                    )

                # three options: it can be an attribute of a sewer area, a uniform value or a raster
                riool_berging_mm = getattr(sew, "riool_berging_mm", None)
                if (
                    riool_berging_mm is None
                    or np.isnan(riool_berging_mm)
                    or not isinstance(riool_berging_mm, float)
                ):
                    if isinstance(sewer_storage, float):
                        sewer_storage_val = f"{sewer_storage:.2f}"
                    elif isinstance(sewer_storage, (Path, str)):
                        sewer_storage_val = f"{sew_stors_sa.iloc[isew]['mean']:.2f}"
                    else:
                        raise TypeError(
                            "Sewer_storage has the wrong datatype. It should be a filename (Path or string) or number (float or int)."
                        )
                else:
                    sewer_storage_val = f"{riool_berging_mm:.2f}"

                # three options: it can be an attribute of a sewer area, a uniform value or a raster
                riool_poc_m3s = getattr(sew, "riool_poc_m3s", None)
                if (
                    riool_poc_m3s is None
                    or np.isnan(riool_poc_m3s)
                    or not isinstance(riool_poc_m3s, float)
                ):
                    if isinstance(pump_capacity, float):
                        # convert the value from mm/h to m3/s
                        pump_capacity_val = f"{pump_capacity * (float(sewer_pav_area) * ov.fractie) / (1000.0 * 3600.0):.8f}"
                    elif isinstance(pump_capacity, (Path, str)):
                        # convert the value (extracted from the raster) from mm/h to m3/s
                        pump_capacity_val = f"{pump_caps_sa.iloc[isew]['mean'] * (float(sewer_pav_area) * ov.fractie) / (1000.0 * 3600.0):.8f}"
                    else:
                        raise TypeError(
                            "Pump_capacity has the wrong datatype. It should be a filename (Path or string) or number (float or int)."
                        )
                else:
                    # use the attribute value
                    pump_capacity_val = f"{riool_poc_m3s * ov.fractie:.8f}"

                # add prefix to the overflow id to create the paved-node id
                self.paved.add_paved(
                    id=str(ov.code),
                    area=str(sewer_pav_area * ov.fractie),
                    surface_level=f"{elev:.2f}",
                    street_storage=street_storage_val,
                    sewer_storage=sewer_storage_val,
                    pump_capacity=pump_capacity_val,
                    meteo_area=str(ms),
                    px=f"{ov_geometry.coords[0][0] + 10:.0f}",
                    py=f"{ov_geometry.coords[0][1]:.0f}",
                    boundary_node=ov.code,
                )

    if sewer_areas is not None:
        # Land use of the catchment parts outside the sewer areas, by
        # catchment position. Catchments that overlap no sewer area use
        # lu_counts.
        sewer_union = sewer_areas.union_all()
        # GeoSeries(...): the stubs type reset_index as a plain Series
        geometries = gpd.GeoSeries(catchments.geometry.reset_index(drop=True))
        overlaps = geometries.intersects(sewer_union)
        # the stubs type a masked GeoSeries as Series[BaseGeometry]; it is a GeoSeries
        outside = geometries[overlaps].difference(sewer_union)  # type: ignore[operator]
        outside = outside[outside.area > 0]
        outside_counts = pd.DataFrame()
        if not outside.empty:
            outside_counts = zonal.zonal_category_counts(
                outside,
                landuse,
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
            )

    for num, (cat, cat_geometry) in enumerate(
        zip(catchments.itertuples(), catchments.geometry)
    ):
        # if no rasterdata could be obtained for this catchment, skip it.
        if pd.isna(stats_elev.iloc[num]["median"]):
            logger.warning(NO_RASTERDATA_WARNING, cat.code)
            self.paved.add_paved(**dict.fromkeys(paved_columns, "0.0"))
            continue
        if sewer_areas is None or not overlaps[num]:
            pav_area = str(lu_counts.iloc[num].get(14, 0) * px_area)
        elif num in outside_counts.index:
            pav_area = str(outside_counts.loc[num].get(14, 0) * px_area)
        else:
            logger.info(
                f"No paved area outside sewer area in catchments {cat.code}."
            )
            pav_area = "0.0"

        # find corresponding meteo-station
        ms = _meteo_area(meteo_areas, cat_geometry.centroid)

        elev = stats_elev.iloc[num]["median"]
        # if a float is given, a standard value is passed. If a string is given, a rastername is assumed to zonal statistics are applied.
        street_storage_val = (
            f"{street_storage:.2f}"
            if isinstance(street_storage, float)
            else f"{str_stors.iloc[num]['mean']:.2f}"
        )
        sewer_storage_val = (
            f"{sewer_storage:.2f}"
            if isinstance(sewer_storage, float)
            else f"{sew_stors.iloc[num]['mean']:.2f}"
        )
        pump_capacity_val = (
            f"{(pump_capacity * float(pav_area)) / (1000.0 * 3600.0):.8f}"
            if isinstance(pump_capacity, float)
            else f"{pump_caps.iloc[num]['mean'] * (float(pav_area)) / (1000.0 * 3600.0):.8f}"
        )
        self.paved.add_paved(
            id=str(cat.code),
            area=str(pav_area),
            surface_level=f"{elev:.2f}",
            street_storage=street_storage_val,
            sewer_storage=sewer_storage_val,
            pump_capacity=pump_capacity_val,
            meteo_area=str(ms),
            px=f"{cat_geometry.centroid.coords[0][0] + 10:.0f}",
            py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
            boundary_node=str(cat.boundary_node),
        )

UnpavedIO

Fill the unpaved nodes of an RR model from catchments and rasters.

Parameters

unpaved : drr.Unpaved The unpaved nodes of the RR model, filled in place.

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

    Parameters
    ----------
    unpaved : drr.Unpaved
        The unpaved nodes of the RR model, filled in place.
    """

    def __init__(self, unpaved: drr.Unpaved) -> None:
        self.unpaved = unpaved

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def unpaved_from_input(
        self,
        catchments: ExtendedGeoDataFrame,
        landuse: StrictStr | Path,
        surface_level: StrictStr | Path,
        soiltype: StrictStr | Path,
        surface_storage: StrictStr | Path | float,
        infiltration_capacity: StrictStr | Path | float,
        initial_gwd: StrictStr | Path | float,
        meteo_areas: ExtendedGeoDataFrame,
        greenhouse_areas: ExtendedGeoDataFrame | None = None,
        *,
        min_coverage_frac: float = 0.0,
        coverage_weight: zonal.CoverageWeight = "fraction",
    ) -> None:
        """Add an unpaved node per catchment, with values from rasters.

        Parameters
        ----------
        catchments : ExtendedGeoDataFrame
            Catchment areas.
        landuse : str or Path
            Land use raster.
        surface_level : str or Path
            Surface level raster.
        soiltype : str or Path
            Soil type raster.
        surface_storage : str, Path or float
            Surface storage (mm): a number for a uniform value, or a raster.
        infiltration_capacity : str, Path or float
            Infiltration capacity (mm/d): a number for a uniform value, or a raster.
        initial_gwd : str, Path or float
            Initial groundwater depth (m): a number for a uniform value, or a raster.
        meteo_areas : ExtendedGeoDataFrame
            Meteo areas; each catchment gets the meteo station of the area that contains
            its centroid.
        greenhouse_areas : ExtendedGeoDataFrame, optional
            Greenhouse areas. Where they are not greenhouse in the land use raster, their
            area is subtracted from the most common land use of the catchment. Defaults
            to None.
        min_coverage_frac : float, optional
            Smallest fraction of a pixel a zone 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 zone covers,
            ``"none"`` counts them fully. Defaults to ``"fraction"``.
        """
        px_area, reference_crs = _raster_metadata(landuse)

        # required rasters
        lu_counts = self.unpaved.drrmodel.zonal_cache.zonal_category_counts(
            gpd.GeoDataFrame(catchments),
            landuse,
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

        soiltypes = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            soiltype,
            statistics=("mode",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

        stats_elev = self.unpaved.drrmodel.zonal_cache.zonal_stats(
            gpd.GeoDataFrame(catchments),
            surface_level,
            statistics=("median",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
        )

        # optional rasters
        if isinstance(surface_storage, (Path, str)):
            sstores = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                surface_storage,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        elif isinstance(surface_storage, int):
            surface_storage = float(surface_storage)
        if isinstance(infiltration_capacity, (Path, str)):
            infcaps = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                infiltration_capacity,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        elif isinstance(infiltration_capacity, int):
            infiltration_capacity = float(infiltration_capacity)
        if isinstance(initial_gwd, (Path, str)):
            ini_gwds = zonal.zonal_stats(
                gpd.GeoDataFrame(catchments),
                initial_gwd,
                statistics=("mean",),
                min_coverage_frac=min_coverage_frac,
                coverage_weight=coverage_weight,
                strategy="feature-sequential",
                raster_crs=reference_crs,
            )
        elif isinstance(initial_gwd, int):
            initial_gwd = float(initial_gwd)

        # HyDAMO Crop code; hydamo name, sobek index, sobek name:
        # 1 aardappelen   3 potatoes
        # 2 graan         5 grain
        # 3 suikerbiet    4 sugarbeet
        # 4 mais          2 corn
        # 5 overige gew. 15 vegetables
        # 6 bloembollen  10 bulbous plants
        # 7 boomgaard     9 orchard
        # 8 gras          1 grass
        # 9 loofbos      11 dediduous
        # 10 naaldbos    12 conferous
        # 11 natuuur     13 nature
        # 12 braak       14 fallow
        sobek_indices = [3, 5, 4, 2, 15, 10, 9, 1, 11, 12, 13, 14]
        for num, (cat, cat_geometry) in enumerate(
            zip(catchments.itertuples(), catchments.geometry)
        ):
            # if no rasterdata could be obtained for this catchment, skip it.
            if pd.isna(stats_elev.iloc[num]["median"]):
                logger.warning(NO_RASTERDATA_WARNING, cat.code)
                self.unpaved.add_unpaved(
                    id="0.0",
                    total_area="0.0",
                    lu_areas="0.0",
                    surface_level="0.0",
                    soiltype="0.0",
                    surface_storage="0.0",
                    infiltration_capacity="0.0",
                    initial_gwd="0.0",
                    meteo_area="0.0",
                    px="0.0",
                    py="0.0",
                    boundary_node="0.0",
                )
                continue
            ms = _meteo_area(meteo_areas, cat_geometry.centroid)
            landuse_counts = lu_counts.iloc[num].copy()
            mapping = np.zeros(16, dtype=int)

            # subtract greenhouse area from most occurring land use if no greenhouse area is in the landuse map
            if (
                greenhouse_areas is not None
                and cat_geometry.intersects(greenhouse_areas.geometry).any()
            ):
                intersection_area = greenhouse_areas.geometry.intersection(
                    cat_geometry
                ).area
                intersection_area = intersection_area[
                    intersection_area > 0.0
                ].to_numpy()[0]
                if landuse_counts.get(15, 0) > 0:
                    # divide area to subtract between greenhouses and the most occurring area
                    remainder = np.max(
                        [0.0, intersection_area - float(landuse_counts[15] * px_area)]
                    )
                else:
                    remainder = intersection_area
                maxind = landuse_counts.idxmax()
                logger.info(
                    "Catchment %s: subtracting %s m2 from class %s for supplied greenhouse area.",
                    cat.code,
                    remainder,
                    maxind,
                )
                landuse_counts[maxind] = np.max(
                    [0.0, landuse_counts[maxind] - np.round(remainder / px_area)]
                )

            for i in range(1, 13):
                mapping[sobek_indices[i - 1] - 1] = landuse_counts.get(i, 0) * px_area
            lu_map = " ".join(map(str, mapping))
            elev = stats_elev.iloc[num]["median"]
            self.unpaved.add_unpaved(
                id=str(cat.code),
                total_area=f"{cat_geometry.area:.0f}",
                lu_areas=lu_map,
                surface_level=f"{elev:.2f}",
                soiltype=f"{soiltypes.iloc[num]['mode'] + 100.0:.0f}",
                surface_storage=(
                    f"{surface_storage:.3f}"
                    if isinstance(surface_storage, float)
                    else f"{sstores.iloc[num]['mean']:.3f}"
                ),
                infiltration_capacity=(
                    f"{infiltration_capacity:.3f}"
                    if isinstance(infiltration_capacity, float)
                    else f"{infcaps.iloc[num]['mean']:.3f}"
                ),
                initial_gwd=(
                    f"{initial_gwd:.2f}"
                    if isinstance(initial_gwd, float)
                    else f"{ini_gwds.iloc[num]['mean']:.2f}"
                ),
                meteo_area=str(ms),
                px=f"{cat_geometry.centroid.coords[0][0] - 10:.0f}",
                py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
                boundary_node=str(cat.boundary_node),
            )

    @validate_call(
        config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
    )
    def ernst_from_input(
        self,
        catchments: ExtendedGeoDataFrame,
        depths: list,
        resistance: list,
        infiltration_resistance: float | None = None,
        runoff_resistance: float | None = None,
    ) -> None:
        """Add the same Ernst definition for the unpaved node of each catchment.

        Parameters
        ----------
        catchments : ExtendedGeoDataFrame
            Catchment areas.
        depths : list
            Layer depths (m).
        resistance : list
            Ernst resistance of each layer (d).
        infiltration_resistance : float, optional
            Resistance to infiltration (d). Defaults to None: 300.
        runoff_resistance : float, optional
            Resistance to surface runoff (d). Defaults to None: 1.
        """
        if infiltration_resistance is None:
            infiltration_resistance = 300.0
        if runoff_resistance is None:
            runoff_resistance = 1.0

        cvo = " ".join([str(res) for res in resistance])
        lv = " ".join([str(depth) for depth in depths])
        cvi = f"{infiltration_resistance:.2f}"
        cvs = f"{runoff_resistance:.2f}"
        for cat in catchments.itertuples():
            self.unpaved.add_ernst_def(
                id=str(cat.code), cvo=cvo, lv=lv, cvi=cvi, cvs=cvs
            )
ernst_from_input(catchments: ExtendedGeoDataFrame, depths: list, resistance: list, infiltration_resistance: float | None = None, runoff_resistance: float | None = None) -> None

Add the same Ernst definition for the unpaved node of each catchment.

Parameters

catchments : ExtendedGeoDataFrame Catchment areas. depths : list Layer depths (m). resistance : list Ernst resistance of each layer (d). infiltration_resistance : float, optional Resistance to infiltration (d). Defaults to None: 300. runoff_resistance : float, optional Resistance to surface runoff (d). Defaults to None: 1.

Source code in hydrolib/dhydamo/io/drrreader.py
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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def ernst_from_input(
    self,
    catchments: ExtendedGeoDataFrame,
    depths: list,
    resistance: list,
    infiltration_resistance: float | None = None,
    runoff_resistance: float | None = None,
) -> None:
    """Add the same Ernst definition for the unpaved node of each catchment.

    Parameters
    ----------
    catchments : ExtendedGeoDataFrame
        Catchment areas.
    depths : list
        Layer depths (m).
    resistance : list
        Ernst resistance of each layer (d).
    infiltration_resistance : float, optional
        Resistance to infiltration (d). Defaults to None: 300.
    runoff_resistance : float, optional
        Resistance to surface runoff (d). Defaults to None: 1.
    """
    if infiltration_resistance is None:
        infiltration_resistance = 300.0
    if runoff_resistance is None:
        runoff_resistance = 1.0

    cvo = " ".join([str(res) for res in resistance])
    lv = " ".join([str(depth) for depth in depths])
    cvi = f"{infiltration_resistance:.2f}"
    cvs = f"{runoff_resistance:.2f}"
    for cat in catchments.itertuples():
        self.unpaved.add_ernst_def(
            id=str(cat.code), cvo=cvo, lv=lv, cvi=cvi, cvs=cvs
        )
unpaved_from_input(catchments: ExtendedGeoDataFrame, landuse: StrictStr | Path, surface_level: StrictStr | Path, soiltype: StrictStr | Path, surface_storage: StrictStr | Path | float, infiltration_capacity: StrictStr | Path | float, initial_gwd: StrictStr | Path | float, meteo_areas: ExtendedGeoDataFrame, greenhouse_areas: ExtendedGeoDataFrame | None = None, *, min_coverage_frac: float = 0.0, coverage_weight: zonal.CoverageWeight = 'fraction') -> None

Add an unpaved node per catchment, with values from rasters.

Parameters

catchments : ExtendedGeoDataFrame Catchment areas. landuse : str or Path Land use raster. surface_level : str or Path Surface level raster. soiltype : str or Path Soil type raster. surface_storage : str, Path or float Surface storage (mm): a number for a uniform value, or a raster. infiltration_capacity : str, Path or float Infiltration capacity (mm/d): a number for a uniform value, or a raster. initial_gwd : str, Path or float Initial groundwater depth (m): a number for a uniform value, or a raster. meteo_areas : ExtendedGeoDataFrame Meteo areas; each catchment gets the meteo station of the area that contains its centroid. greenhouse_areas : ExtendedGeoDataFrame, optional Greenhouse areas. Where they are not greenhouse in the land use raster, their area is subtracted from the most common land use of the catchment. Defaults to None. min_coverage_frac : float, optional Smallest fraction of a pixel a zone 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 zone covers, "none" counts them fully. Defaults to "fraction".

Source code in hydrolib/dhydamo/io/drrreader.py
 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
@validate_call(
    config=ConfigDict(arbitrary_types_allowed=True, coerce_numbers_to_str=True)
)
def unpaved_from_input(
    self,
    catchments: ExtendedGeoDataFrame,
    landuse: StrictStr | Path,
    surface_level: StrictStr | Path,
    soiltype: StrictStr | Path,
    surface_storage: StrictStr | Path | float,
    infiltration_capacity: StrictStr | Path | float,
    initial_gwd: StrictStr | Path | float,
    meteo_areas: ExtendedGeoDataFrame,
    greenhouse_areas: ExtendedGeoDataFrame | None = None,
    *,
    min_coverage_frac: float = 0.0,
    coverage_weight: zonal.CoverageWeight = "fraction",
) -> None:
    """Add an unpaved node per catchment, with values from rasters.

    Parameters
    ----------
    catchments : ExtendedGeoDataFrame
        Catchment areas.
    landuse : str or Path
        Land use raster.
    surface_level : str or Path
        Surface level raster.
    soiltype : str or Path
        Soil type raster.
    surface_storage : str, Path or float
        Surface storage (mm): a number for a uniform value, or a raster.
    infiltration_capacity : str, Path or float
        Infiltration capacity (mm/d): a number for a uniform value, or a raster.
    initial_gwd : str, Path or float
        Initial groundwater depth (m): a number for a uniform value, or a raster.
    meteo_areas : ExtendedGeoDataFrame
        Meteo areas; each catchment gets the meteo station of the area that contains
        its centroid.
    greenhouse_areas : ExtendedGeoDataFrame, optional
        Greenhouse areas. Where they are not greenhouse in the land use raster, their
        area is subtracted from the most common land use of the catchment. Defaults
        to None.
    min_coverage_frac : float, optional
        Smallest fraction of a pixel a zone 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 zone covers,
        ``"none"`` counts them fully. Defaults to ``"fraction"``.
    """
    px_area, reference_crs = _raster_metadata(landuse)

    # required rasters
    lu_counts = self.unpaved.drrmodel.zonal_cache.zonal_category_counts(
        gpd.GeoDataFrame(catchments),
        landuse,
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )

    soiltypes = zonal.zonal_stats(
        gpd.GeoDataFrame(catchments),
        soiltype,
        statistics=("mode",),
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )

    stats_elev = self.unpaved.drrmodel.zonal_cache.zonal_stats(
        gpd.GeoDataFrame(catchments),
        surface_level,
        statistics=("median",),
        min_coverage_frac=min_coverage_frac,
        coverage_weight=coverage_weight,
        strategy="feature-sequential",
    )

    # optional rasters
    if isinstance(surface_storage, (Path, str)):
        sstores = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            surface_storage,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )
    elif isinstance(surface_storage, int):
        surface_storage = float(surface_storage)
    if isinstance(infiltration_capacity, (Path, str)):
        infcaps = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            infiltration_capacity,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )
    elif isinstance(infiltration_capacity, int):
        infiltration_capacity = float(infiltration_capacity)
    if isinstance(initial_gwd, (Path, str)):
        ini_gwds = zonal.zonal_stats(
            gpd.GeoDataFrame(catchments),
            initial_gwd,
            statistics=("mean",),
            min_coverage_frac=min_coverage_frac,
            coverage_weight=coverage_weight,
            strategy="feature-sequential",
            raster_crs=reference_crs,
        )
    elif isinstance(initial_gwd, int):
        initial_gwd = float(initial_gwd)

    # HyDAMO Crop code; hydamo name, sobek index, sobek name:
    # 1 aardappelen   3 potatoes
    # 2 graan         5 grain
    # 3 suikerbiet    4 sugarbeet
    # 4 mais          2 corn
    # 5 overige gew. 15 vegetables
    # 6 bloembollen  10 bulbous plants
    # 7 boomgaard     9 orchard
    # 8 gras          1 grass
    # 9 loofbos      11 dediduous
    # 10 naaldbos    12 conferous
    # 11 natuuur     13 nature
    # 12 braak       14 fallow
    sobek_indices = [3, 5, 4, 2, 15, 10, 9, 1, 11, 12, 13, 14]
    for num, (cat, cat_geometry) in enumerate(
        zip(catchments.itertuples(), catchments.geometry)
    ):
        # if no rasterdata could be obtained for this catchment, skip it.
        if pd.isna(stats_elev.iloc[num]["median"]):
            logger.warning(NO_RASTERDATA_WARNING, cat.code)
            self.unpaved.add_unpaved(
                id="0.0",
                total_area="0.0",
                lu_areas="0.0",
                surface_level="0.0",
                soiltype="0.0",
                surface_storage="0.0",
                infiltration_capacity="0.0",
                initial_gwd="0.0",
                meteo_area="0.0",
                px="0.0",
                py="0.0",
                boundary_node="0.0",
            )
            continue
        ms = _meteo_area(meteo_areas, cat_geometry.centroid)
        landuse_counts = lu_counts.iloc[num].copy()
        mapping = np.zeros(16, dtype=int)

        # subtract greenhouse area from most occurring land use if no greenhouse area is in the landuse map
        if (
            greenhouse_areas is not None
            and cat_geometry.intersects(greenhouse_areas.geometry).any()
        ):
            intersection_area = greenhouse_areas.geometry.intersection(
                cat_geometry
            ).area
            intersection_area = intersection_area[
                intersection_area > 0.0
            ].to_numpy()[0]
            if landuse_counts.get(15, 0) > 0:
                # divide area to subtract between greenhouses and the most occurring area
                remainder = np.max(
                    [0.0, intersection_area - float(landuse_counts[15] * px_area)]
                )
            else:
                remainder = intersection_area
            maxind = landuse_counts.idxmax()
            logger.info(
                "Catchment %s: subtracting %s m2 from class %s for supplied greenhouse area.",
                cat.code,
                remainder,
                maxind,
            )
            landuse_counts[maxind] = np.max(
                [0.0, landuse_counts[maxind] - np.round(remainder / px_area)]
            )

        for i in range(1, 13):
            mapping[sobek_indices[i - 1] - 1] = landuse_counts.get(i, 0) * px_area
        lu_map = " ".join(map(str, mapping))
        elev = stats_elev.iloc[num]["median"]
        self.unpaved.add_unpaved(
            id=str(cat.code),
            total_area=f"{cat_geometry.area:.0f}",
            lu_areas=lu_map,
            surface_level=f"{elev:.2f}",
            soiltype=f"{soiltypes.iloc[num]['mode'] + 100.0:.0f}",
            surface_storage=(
                f"{surface_storage:.3f}"
                if isinstance(surface_storage, float)
                else f"{sstores.iloc[num]['mean']:.3f}"
            ),
            infiltration_capacity=(
                f"{infiltration_capacity:.3f}"
                if isinstance(infiltration_capacity, float)
                else f"{infcaps.iloc[num]['mean']:.3f}"
            ),
            initial_gwd=(
                f"{initial_gwd:.2f}"
                if isinstance(initial_gwd, float)
                else f"{ini_gwds.iloc[num]['mean']:.2f}"
            ),
            meteo_area=str(ms),
            px=f"{cat_geometry.centroid.coords[0][0] - 10:.0f}",
            py=f"{cat_geometry.centroid.coords[0][1]:.0f}",
            boundary_node=str(cat.boundary_node),
        )

drrwriter

Write the files of a D-RR model.

DRRWriter

Write the files of an RR model to the rr folder of a model.

An existing rr folder is removed when the writer is created.

Parameters

rrmodel : DRRModel The RR model to write. output_dir : str or Path Model folder; the files are written to its rr subfolder. name : str, optional Deprecated, not used. Defaults to None. wwtp : tuple[float, float], optional Coordinates of the waste water treatment plant node, to which the paved nodes are linked. Defaults to None: (100000, 500000).

Source code in hydrolib/dhydamo/io/drrwriter.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
 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
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
class DRRWriter:
    """Write the files of an RR model to the ``rr`` folder of a model.

    An existing ``rr`` folder is removed when the writer is created.

    Parameters
    ----------
    rrmodel : DRRModel
        The RR model to write.
    output_dir : str or Path
        Model folder; the files are written to its ``rr`` subfolder.
    name : str, optional
        Deprecated, not used. Defaults to None.
    wwtp : tuple[float, float], optional
        Coordinates of the waste water treatment plant node, to which the paved nodes
        are linked. Defaults to None: (100000, 500000).
    """

    def __init__(
        self,
        rrmodel: DRRModel,
        output_dir: str | Path,
        name: str | None = None,
        wwtp: tuple[float, float] | None = None,
    ) -> None:
        self.rrmodel = rrmodel
        # self.geometries = parent.geometries
        # self.boundary_conditions = parent.boundary_conditions
        self.output_dir = os.path.join(output_dir, "rr")

        if name is not None:
            logger.warning(
                "The 'name' parameter is deprecated and will be removed in a future version.",
            )

        hydamo = HyDAMO()
        self.version = hydamo.version

        if os.path.exists(self.output_dir):
            shutil.rmtree(self.output_dir)

        self.d3b_parameters = rrmodel.d3b_parameters

        self.precip_df = pd.DataFrame()
        self.run_dimrpad = rrmodel.dimr_path

        if wwtp is None:
            self.wwtp = Point((1e5, 5e5))
        else:
            self.wwtp = Point((wwtp[0], wwtp[1]))

    def write_all(self) -> None:  # write all RR files
        """Write all RR files and set the parameters of ``delft_3b.ini``."""
        # copy all 'standard' files from the resources folder
        self.copyRRFiles()

        self.write_topology()

        self.write_unpaved()

        self.write_paved()

        self.write_greenhouse()

        self.write_openwater()

        self.write_meteo()

        # Change d3b parameters
        for parameter, value in self.d3b_parameters.items():
            self.change_d3b_parameter(parameter, value)

    def copyRRFiles(self) -> bool:
        """Copy the standard RR files from the resources folder to the output folder.

        Returns
        -------
        bool
            Always True.
        """
        srcRR = os.path.join(os.path.dirname(__file__), "..", "resources", "RR")
        targetRR = os.path.join(self.output_dir)
        shutil.copytree(srcRR, targetRR)
        return True

    def write_topology(self) -> None:
        """Write the topology files of the RR model.

        - ``3B_NOD.TP``: ids and coordinates of all nodes: unpaved, paved, greenhouse,
          open water and boundary. Only nodes with a total area > 0 are written. Nodes are
          placed up to 20 m east and west of the catchment centroid.
        - ``3B_LINK.TP``: links between all nodes and their boundaries.
        - ``BOUND3B.3B``: coupling information for every RR boundary.
        - ``BoundaryConditions.bc``: see ``BOUND3B.3B``.
        """
        filepath = os.path.join(self.output_dir, "3B_NOD.TP")
        with open(filepath, "w") as f:
            # Unpaved nodes
            if any(self.rrmodel.unpaved.unp_nodes):
                for dct in self.rrmodel.unpaved.unp_nodes.values():
                    if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                        f.write(
                            "NODE id '"
                            + dct["id"]
                            + "' nm '"
                            + dct["id"]
                            + "' ri '-1' mt 1 '2' nt 44 ObID '3B_UNPAVED' px "
                            + dct["px"]
                            + " py "
                            + dct["py"]
                            + " node\n"
                        )

            # Paved nodes
            if any(self.rrmodel.paved.pav_nodes):
                for dct in self.rrmodel.paved.pav_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "NODE id '"
                            + dct["id"]
                            + "' nm '"
                            + dct["id"]
                            + "' ri '-1' mt 1 '1' nt 43 ObID '3B_PAVED' px "
                            + dct["px"]
                            + " py "
                            + dct["py"]
                            + " node\n"
                        )

                f.write(
                    "NODE id 'WWTP' nm 'WWTP' ri '-1' mt 1 '14' nt 56 ObID '3B_WWTP' px "
                    + str(self.wwtp.coords[0][0])
                    + " py "
                    + str(self.wwtp.coords[0][1])
                    + " node\n"
                )
                f.write(
                    "NODE id 'WWTP_BND' nm 'WWTP_BND' ri '-1' mt 1 '6' nt 47 ObID '3B_BOUNDARY' px "
                    + str(self.wwtp.coords[0][0] + 50.0)
                    + " py "
                    + str(self.wwtp.coords[0][1] + 50.0)
                    + " node\n"
                )

            # Greenhouse nodes
            if any(self.rrmodel.greenhouse.gh_nodes):
                for dct in self.rrmodel.greenhouse.gh_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "NODE id '"
                            + dct["id"]
                            + "' nm '"
                            + dct["id"]
                            + "' ri '-1' mt 1 '3' nt 45 ObID '3B_GREENHOUSE' px "
                            + dct["px"]
                            + " py "
                            + dct["py"]
                            + " node\n"
                        )

            # Openwater nodes
            if any(self.rrmodel.openwater.ow_nodes):
                for dct in self.rrmodel.openwater.ow_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "NODE id '"
                            + dct["id"]
                            + "' nm '"
                            + dct["id"]
                            + "' ri '-1' mt 1 '21' nt 46 ObID 'OW_PRECIP' px "
                            + dct["px"]
                            + " py "
                            + dct["py"]
                            + " node\n"
                        )

            # Boundary_nodes
            if any(self.rrmodel.external_forcings.boundary_nodes):
                for dct in self.rrmodel.external_forcings.boundary_nodes.values():
                    f.write(
                        "NODE id '"
                        + dct["id"]
                        + "' nm '"
                        + dct["id"]
                        + "' ri '-1' mt 1 '6' nt 78 ObID 'SBK_SBK-3B-NODE' px "
                        + dct["px"]
                        + " py "
                        + dct["py"]
                        + " node\n"
                    )

        filepath = os.path.join(self.output_dir, "3B_LINK.TP")
        with open(filepath, "w") as f:
            cnt = 0
            if any(self.rrmodel.unpaved.unp_nodes):
                for dct in self.rrmodel.unpaved.unp_nodes.values():
                    if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                        cnt += 1
                        f.write(
                            "BRCH id 'link_"
                            + str(cnt)
                            + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                            + dct["id"]
                            + "' en '"
                            + dct["boundary_node"]
                            + "' brch\n"
                        )
            if any(self.rrmodel.paved.pav_nodes):
                for dct in self.rrmodel.paved.pav_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        cnt += 1
                        f.write(
                            "BRCH id 'link_"
                            + str(cnt)
                            + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                            + dct["id"]
                            + "' en '"
                            + dct["boundary_node"]
                            + "' brch\n"
                        )
                        cnt += 1
                        f.write(
                            "BRCH id 'link_"
                            + str(cnt)
                            + "' ri '-1' mt 1 '1' bt 18 ObID '3B_LINK_RWZI' bn '"
                            + dct["id"]
                            + "' en 'WWTP' brch\n"
                        )
                cnt += 1
                f.write(
                    "BRCH id 'link_"
                    + str(cnt)
                    + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn 'WWTP' en 'WWTP_BND' brch\n"
                )

            if any(self.rrmodel.greenhouse.gh_nodes):
                for dct in self.rrmodel.greenhouse.gh_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        cnt += 1
                        f.write(
                            "BRCH id 'link_"
                            + str(cnt)
                            + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                            + dct["id"]
                            + "' en '"
                            + dct["boundary_node"]
                            + "' brch\n"
                        )
            if any(self.rrmodel.openwater.ow_nodes):
                for dct in self.rrmodel.openwater.ow_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        cnt += 1
                        f.write(
                            "BRCH id 'link_"
                            + str(cnt)
                            + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                            + dct["id"]
                            + "' en '"
                            + dct["boundary_node"]
                            + "' brch\n"
                        )

        # bound3b.3b
        filepath = os.path.join(self.output_dir, "Bound3B.3B")
        with open(filepath, "w") as f:
            for dct in self.rrmodel.external_forcings.boundary_nodes.values():
                f.write("BOUN id '" + dct["id"] + "' bl 2 '0' is 0 boun\n")
            if any(self.rrmodel.paved.pav_nodes):
                f.write("BOUN id 'WWTP_BND' bl 0 -3 is 0 boun\n")

        # BoundaryConditions.bc
        filepath = os.path.join(self.output_dir, "BoundaryConditions.bc")
        header = {"fileVersion": "1.01", "fileType": "boundConds"}
        with open(filepath, "w") as f:
            self._write_dict(f, header, "General", "\n")
            for dct in self.rrmodel.external_forcings.boundary_nodes.values():
                temp = {
                    "name": "" + dct["id"],
                    "function": "constant",
                    "quantity": "water_level",
                    "unit": "m",
                }
                self._write_dict(f, temp, "Boundary", "    0\n\n")
            if any(self.rrmodel.paved.pav_nodes):
                temp = {
                    "name": "WWTP_BND",
                    "function": "constant",
                    "quantity": "water_level",
                    "unit": "m",
                }
                self._write_dict(f, temp, "Boundary", "    0\n\n")

    def write_unpaved(self) -> None:
        """Write the files of the unpaved nodes.

        ``UNPAVED.3B``, ``UNPAVED.ALF``, ``UNPAVED.STO``, ``UNPAVED.INF`` and
        ``UNPAVED.SEP``. All files have a definition for every node, because the values
        may be spatially distributed.
        """
        if any(self.rrmodel.unpaved.unp_nodes):
            filepath = os.path.join(self.output_dir, "UNPAVED.3B")
            with open(filepath, "w") as f:
                for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                    if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                        f.write(
                            "UNPV id '"
                            + dct["id"]
                            + "' na "
                            + dct["na"]
                            + " ga "
                            + dct["ga"]
                            + " ar "
                            + dct["ar"]
                            + " lv "
                            + dct["lv"]
                            + " co "
                            + dct["co"]
                            + " su "
                            + dct["su"]
                            + " sd 'sto_"
                            + dct["id"]
                            + "' ic 'inf_"
                            + dct["id"]
                            + "' bt "
                            + dct["bt"]
                            + " ed '"
                            + dct["ed"]
                            + "' sp '"
                            + dct["sp"]
                            + "' ig 0 "
                            + dct["ig"]
                            + " mg "
                            + dct["mg"]
                            + " gl "
                            + dct["gl"]
                            + " is "
                            + dct["is"]
                            + " ms '"
                            + dct["ms"]
                            + "' unpv\n"
                        )

            filepath = os.path.join(self.output_dir, "UNPAVED.STO")
            with open(filepath, "w") as f:
                for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                    if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                        f.write(
                            "STDF id 'sto_"
                            + dct["id"]
                            + "' nm 'sto_"
                            + dct["id"]
                            + "' ml "
                            + dct["sd"]
                            + " il 0 stdf\n"
                        )

            filepath = os.path.join(self.output_dir, "UNPAVED.INF")
            with open(filepath, "w") as f:
                for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                    if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                        f.write(
                            "INFC id 'inf_"
                            + dct["id"]
                            + "' nm 'inf_"
                            + dct["id"]
                            + "' ic "
                            + dct["ic"]
                            + " infc\n"
                        )

            filepath = os.path.join(self.output_dir, "UNPAVED.ALF")
            with open(filepath, "w") as f:
                for _, dct in self.rrmodel.unpaved.ernst_defs.items():
                    if (
                        np.sum(
                            [
                                float(d)
                                for d in self.rrmodel.unpaved.unp_nodes[_]["ar"].split(
                                    " "
                                )
                            ]
                        )
                        > 0.0
                    ):
                        f.write(
                            "ERNS id '"
                            + dct["id"]
                            + "' nm '"
                            + dct["id"]
                            + "' cvi "
                            + dct["cvi"]
                            + " cvo 0 "
                            + dct["cvo"]
                            + " cvs "
                            + dct["cvs"]
                            + " lv "
                            + dct["lv"]
                            + " erns\n"
                        )

            filepath = os.path.join(self.output_dir, "UNPAVED.SEP")
            with open(filepath, "w") as f:
                for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                    if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                        f.write(
                            "SEEP id '"
                            + dct["sp"]
                            + "' nm '"
                            + dct["sp"]
                            + "' co 4 PDIN 0 0 pdin ss 0\n"
                        )
                        f.write("TBLE\n")
                        seepage = self.rrmodel.external_forcings.seepage[dct["sp"]][
                            "seepage"
                        ]
                        f.writelines(
                            f"'{time.strftime('%Y/%m/%d;%H:%M:%S')}' {value:.5f} <\n"
                            for time, value in zip(
                                pd.DatetimeIndex(seepage.index), seepage
                            )
                        )
                        f.write("tble\nseep\n")

    def write_paved(self) -> None:
        """Write the files of the paved nodes.

        ``PAVED.3B``, ``PAVED.STO`` and ``PAVED.DWA``. The latter has only one definition.
        """
        if any(self.rrmodel.paved.pav_nodes):
            filepath = os.path.join(self.output_dir, "PAVED.3B")
            with open(filepath, "w") as f:
                for dct in self.rrmodel.paved.pav_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "PAVE id '"
                            + dct["id"]
                            + "' ar "
                            + dct["ar"]
                            + " lv "
                            + dct["lv"]
                            + " sd 'sto_"
                            + dct["id"]
                            + "' ss 0 qc 0 "
                            + dct["qc"]
                            + " 0 qo 2 2 ms '"
                            + dct["ms"]
                            + "' is "
                            + dct["is"]
                            + " np "
                            + dct["np"]
                            + " dw 'Def_DWA' ro "
                            + dct["ro"]
                            + " ru "
                            + dct["ru"]
                            + " qh '' pave\n"
                        )

            filepath = os.path.join(self.output_dir, "PAVED.STO")
            with open(filepath, "w") as f:
                for dct in self.rrmodel.paved.pav_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "STDF id 'sto_"
                            + dct["id"]
                            + "' nm 'sto_"
                            + dct["id"]
                            + "' ms "
                            + dct["strs"]
                            + " is 0 mr "
                            + dct["sews"]
                            + " 0.0 ir 0.0 0.0 stdf\n"
                        )

            filepath = os.path.join(self.output_dir, "PAVED.DWA")
            with open(filepath, "w") as f:
                f.write(
                    "DWA id 'Def_DWA' nm 'Def_DWA' do 1 wc 0 wd 0 wh 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 dwa\n"
                )

            filepath = os.path.join(self.output_dir, "WWTP.3B")
            with open(filepath, "w") as f:
                f.write("WWTP id 'WWTP' tb 0  wwtp\n")

            filepath = os.path.join(self.output_dir, "WWTP.tbl")
            with open(filepath, "w") as f:
                f.write("\n")

    def write_greenhouse(self) -> None:
        """Write the files of the greenhouse nodes.

        ``GREENHSE.3B``, ``GREENHSE.RF`` and ``GREENHSE.SIL``. The latter has only one
        definition.
        """
        if any(self.rrmodel.greenhouse.gh_nodes):
            filepath = os.path.join(self.output_dir, "GREENHSE.3B")
            with open(filepath, "w") as f:
                for dct in self.rrmodel.greenhouse.gh_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        area_string = " ".join(
                            ["0" for _ in range(int(dct["basin_storage_class"]) - 1)]
                            + [dct["ar"]]
                            + [
                                "0"
                                for _ in range(10 - (int(dct["basin_storage_class"])))
                            ]
                        )
                        f.write(
                            "GRHS id '"
                            + dct["id"]
                            + "' na 10 ar "
                            + area_string
                            + " sl "
                            + dct["sl"]
                            + " as 0 si 'Def_silo' sd 'sto_"
                            + dct["id"]
                            + "' ms '"
                            + dct["ms"]
                            + "' is "
                            + dct["is"]
                            + " grhs\n"
                        )

            filepath = os.path.join(self.output_dir, "GREENHSE.SIL")
            with open(filepath, "w") as f:
                f.write("SILO id 'Def_silo' nm 'Def_silo' sc 0.0 pc 0.0 silo\n")

            filepath = os.path.join(self.output_dir, "GREENHSE.RF")
            with open(filepath, "w") as f:
                for dct in self.rrmodel.greenhouse.gh_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "STDF id 'sto_"
                            + dct["id"]
                            + "' nm 'sto_"
                            + dct["id"]
                            + "' mk "
                            + dct["sd"]
                            + " ik 0 stdf\n"
                        )

    def write_openwater(self) -> None:
        """Write ``OPENWATE.3B``, the file of the open water nodes."""
        # write openwater.3b
        if any(self.rrmodel.openwater.ow_nodes):
            filepath = os.path.join(self.output_dir, "OPENWATE.3B")
            with open(filepath, "w") as f:
                for dct in self.rrmodel.openwater.ow_nodes.values():
                    if float(dct["ar"]) > 0.0:
                        f.write(
                            "OWRR id '"
                            + dct["id"]
                            + "' ar "
                            + dct["ar"]
                            + " ms '"
                            + dct["ms"]
                            + "' owrr\n"
                        )

    def write_meteo(self) -> None:
        """Write the meteo files ``DEFAULT.BUI`` and ``DEFAULT.EVP``.

        From the time series per meteo area, or as a copy of the meteo file given to the
        RR model.
        """
        # precip
        filepath = os.path.join(self.output_dir, "DEFAULT.BUI")
        if isinstance(self.rrmodel.external_forcings.precip, str):
            shutil.copy(self.rrmodel.external_forcings.precip, filepath)
        else:
            # the precipitation per meteo area, written below the header
            self.precip_df = pd.DataFrame(
                {
                    name: pd.Series(series["precip"])
                    for name, series in self.rrmodel.external_forcings.precip.items()
                }
            )

            with open(filepath, "w") as f:
                f.write("*Name of this file: c:\\Result\\1058\\DEFAULT.BUI\n")
                f.write("*Date and time of construction: 00/00/2000 00:00:00.\n")
                f.write("1\n")
                f.write("*Aantal stations\n")
                f.write(str(len(self.rrmodel.external_forcings.precip)) + "\n")
                f.write("*Namen van stations\n")
                for ms in self.rrmodel.external_forcings.precip.items():
                    f.write("'" + ms[0] + "'" + "\n")
                f.write(
                    "*Aantal gebeurtenissen (omdat het 1 bui betreft is dit altijd 1)\n"
                )
                f.write("*en het aantal seconden per waarnemingstijdstap\n")
                f.write(
                    f"1 {(ms[1]['precip'].index[1] - ms[1]['precip'].index[0]).total_seconds():.0f}\n"
                )
                f.write("*Elke commentaarregel wordt begonnen met een * (asterisk).\n")
                f.write(
                    "*Eerste record bevat startdatum en -tijd, lengte van de gebeurtenis in dd hh mm ss\n"
                )
                f.write("*Het format is: yyyymmdd:hhmmss:ddhhmmss")
                f.write("*Daarna voor elk station de neerslag in mm per tijdstap.\n")
                duration = (
                    ms[1]["precip"].index[-1] - ms[1]["precip"].index[0]
                ).total_seconds()
                f.write(
                    ms[1]["precip"].index[0].strftime("%Y %#m %#d %#H %#M %#S ")
                    + str(int(duration / 86400.0))
                    + " "
                    + str(int(np.remainder(duration, 86400.0) / 3600.0))
                    + " 0 0\n"
                )
            self.precip_df.to_csv(
                filepath,
                header=False,
                index=False,
                sep=" ",
                float_format="%.3f",
                mode="a",
            )
        # %%

        # %%%
        # evaporation
        filepath = os.path.join(self.output_dir, "DEFAULT.EVP")
        if isinstance(self.rrmodel.external_forcings.evap, str):
            shutil.copy(self.rrmodel.external_forcings.evap, filepath)
        else:
            with open(filepath, "w") as f:
                f.write("*Verdampingsfile\n")
                f.write("*Meteo data: evaporation intensity in mm/day\n")
                f.write("*First record: start date, data in mm/day\n")
                f.write(
                    "*Datum (year month day), verdamping (mm/dag) voor elk weerstation\n"
                )
                f.write("*jaar maand dag verdamping[mm]\n")
            table = next(iter(self.rrmodel.external_forcings.evap.values()))["evap"]
            table = table.sort_index()
            date_format = "%#Y  %#m  %#d "
            float_format = "%.3f"
            sep = " "
            with open(filepath, "a") as f:
                for ts, val in zip(pd.DatetimeIndex(table.index), table):
                    date = ts.strftime(date_format)
                    f.write(f"{date}{sep}{float_format % val}\n")

    def _write_dict(
        self, f: TextIO, dct: dict[str, str], header: str, endline: str
    ) -> None:
        """Write a dictionary as an INI section, without transforming the values."""
        # Write header
        f.write(f"[{header}]\n")
        f.writelines(f"    {key:20s} = {value:20s}\n" for key, value in dct.items())
        f.write(endline)

    def change_d3b_parameter(self, parameter: str, value: str | float) -> None:
        """Change the value of a parameter in ``delft_3b.ini``, in place.

        Parameters
        ----------
        parameter : str
            Parameter name, case-insensitive.
        value : str or float
            New value.
        """
        with open(os.path.join(self.output_dir, "delft_3b.ini")) as f:
            lines = f.readlines()

        for i, line in enumerate(lines):
            if line.lower().strip().startswith(parameter.lower()):
                items = re.split("=", line)
                key, oldvalue = items[0], items[1]
                if key.strip().lower() != parameter.lower():
                    continue
                lines[i] = line.replace("=" + oldvalue, f"={value}\n")
                break

        with open(os.path.join(self.output_dir, "delft_3b.ini"), "w") as f:
            f.write("".join(lines))
change_d3b_parameter(parameter: str, value: str | float) -> None

Change the value of a parameter in delft_3b.ini, in place.

Parameters

parameter : str Parameter name, case-insensitive. value : str or float New value.

Source code in hydrolib/dhydamo/io/drrwriter.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def change_d3b_parameter(self, parameter: str, value: str | float) -> None:
    """Change the value of a parameter in ``delft_3b.ini``, in place.

    Parameters
    ----------
    parameter : str
        Parameter name, case-insensitive.
    value : str or float
        New value.
    """
    with open(os.path.join(self.output_dir, "delft_3b.ini")) as f:
        lines = f.readlines()

    for i, line in enumerate(lines):
        if line.lower().strip().startswith(parameter.lower()):
            items = re.split("=", line)
            key, oldvalue = items[0], items[1]
            if key.strip().lower() != parameter.lower():
                continue
            lines[i] = line.replace("=" + oldvalue, f"={value}\n")
            break

    with open(os.path.join(self.output_dir, "delft_3b.ini"), "w") as f:
        f.write("".join(lines))
copyRRFiles() -> bool

Copy the standard RR files from the resources folder to the output folder.

Returns

bool Always True.

Source code in hydrolib/dhydamo/io/drrwriter.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def copyRRFiles(self) -> bool:
    """Copy the standard RR files from the resources folder to the output folder.

    Returns
    -------
    bool
        Always True.
    """
    srcRR = os.path.join(os.path.dirname(__file__), "..", "resources", "RR")
    targetRR = os.path.join(self.output_dir)
    shutil.copytree(srcRR, targetRR)
    return True
write_all() -> None

Write all RR files and set the parameters of delft_3b.ini.

Source code in hydrolib/dhydamo/io/drrwriter.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def write_all(self) -> None:  # write all RR files
    """Write all RR files and set the parameters of ``delft_3b.ini``."""
    # copy all 'standard' files from the resources folder
    self.copyRRFiles()

    self.write_topology()

    self.write_unpaved()

    self.write_paved()

    self.write_greenhouse()

    self.write_openwater()

    self.write_meteo()

    # Change d3b parameters
    for parameter, value in self.d3b_parameters.items():
        self.change_d3b_parameter(parameter, value)
write_greenhouse() -> None

Write the files of the greenhouse nodes.

GREENHSE.3B, GREENHSE.RF and GREENHSE.SIL. The latter has only one definition.

Source code in hydrolib/dhydamo/io/drrwriter.py
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
def write_greenhouse(self) -> None:
    """Write the files of the greenhouse nodes.

    ``GREENHSE.3B``, ``GREENHSE.RF`` and ``GREENHSE.SIL``. The latter has only one
    definition.
    """
    if any(self.rrmodel.greenhouse.gh_nodes):
        filepath = os.path.join(self.output_dir, "GREENHSE.3B")
        with open(filepath, "w") as f:
            for dct in self.rrmodel.greenhouse.gh_nodes.values():
                if float(dct["ar"]) > 0.0:
                    area_string = " ".join(
                        ["0" for _ in range(int(dct["basin_storage_class"]) - 1)]
                        + [dct["ar"]]
                        + [
                            "0"
                            for _ in range(10 - (int(dct["basin_storage_class"])))
                        ]
                    )
                    f.write(
                        "GRHS id '"
                        + dct["id"]
                        + "' na 10 ar "
                        + area_string
                        + " sl "
                        + dct["sl"]
                        + " as 0 si 'Def_silo' sd 'sto_"
                        + dct["id"]
                        + "' ms '"
                        + dct["ms"]
                        + "' is "
                        + dct["is"]
                        + " grhs\n"
                    )

        filepath = os.path.join(self.output_dir, "GREENHSE.SIL")
        with open(filepath, "w") as f:
            f.write("SILO id 'Def_silo' nm 'Def_silo' sc 0.0 pc 0.0 silo\n")

        filepath = os.path.join(self.output_dir, "GREENHSE.RF")
        with open(filepath, "w") as f:
            for dct in self.rrmodel.greenhouse.gh_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "STDF id 'sto_"
                        + dct["id"]
                        + "' nm 'sto_"
                        + dct["id"]
                        + "' mk "
                        + dct["sd"]
                        + " ik 0 stdf\n"
                    )
write_meteo() -> None

Write the meteo files DEFAULT.BUI and DEFAULT.EVP.

From the time series per meteo area, or as a copy of the meteo file given to the RR model.

Source code in hydrolib/dhydamo/io/drrwriter.py
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
def write_meteo(self) -> None:
    """Write the meteo files ``DEFAULT.BUI`` and ``DEFAULT.EVP``.

    From the time series per meteo area, or as a copy of the meteo file given to the
    RR model.
    """
    # precip
    filepath = os.path.join(self.output_dir, "DEFAULT.BUI")
    if isinstance(self.rrmodel.external_forcings.precip, str):
        shutil.copy(self.rrmodel.external_forcings.precip, filepath)
    else:
        # the precipitation per meteo area, written below the header
        self.precip_df = pd.DataFrame(
            {
                name: pd.Series(series["precip"])
                for name, series in self.rrmodel.external_forcings.precip.items()
            }
        )

        with open(filepath, "w") as f:
            f.write("*Name of this file: c:\\Result\\1058\\DEFAULT.BUI\n")
            f.write("*Date and time of construction: 00/00/2000 00:00:00.\n")
            f.write("1\n")
            f.write("*Aantal stations\n")
            f.write(str(len(self.rrmodel.external_forcings.precip)) + "\n")
            f.write("*Namen van stations\n")
            for ms in self.rrmodel.external_forcings.precip.items():
                f.write("'" + ms[0] + "'" + "\n")
            f.write(
                "*Aantal gebeurtenissen (omdat het 1 bui betreft is dit altijd 1)\n"
            )
            f.write("*en het aantal seconden per waarnemingstijdstap\n")
            f.write(
                f"1 {(ms[1]['precip'].index[1] - ms[1]['precip'].index[0]).total_seconds():.0f}\n"
            )
            f.write("*Elke commentaarregel wordt begonnen met een * (asterisk).\n")
            f.write(
                "*Eerste record bevat startdatum en -tijd, lengte van de gebeurtenis in dd hh mm ss\n"
            )
            f.write("*Het format is: yyyymmdd:hhmmss:ddhhmmss")
            f.write("*Daarna voor elk station de neerslag in mm per tijdstap.\n")
            duration = (
                ms[1]["precip"].index[-1] - ms[1]["precip"].index[0]
            ).total_seconds()
            f.write(
                ms[1]["precip"].index[0].strftime("%Y %#m %#d %#H %#M %#S ")
                + str(int(duration / 86400.0))
                + " "
                + str(int(np.remainder(duration, 86400.0) / 3600.0))
                + " 0 0\n"
            )
        self.precip_df.to_csv(
            filepath,
            header=False,
            index=False,
            sep=" ",
            float_format="%.3f",
            mode="a",
        )
    # %%

    # %%%
    # evaporation
    filepath = os.path.join(self.output_dir, "DEFAULT.EVP")
    if isinstance(self.rrmodel.external_forcings.evap, str):
        shutil.copy(self.rrmodel.external_forcings.evap, filepath)
    else:
        with open(filepath, "w") as f:
            f.write("*Verdampingsfile\n")
            f.write("*Meteo data: evaporation intensity in mm/day\n")
            f.write("*First record: start date, data in mm/day\n")
            f.write(
                "*Datum (year month day), verdamping (mm/dag) voor elk weerstation\n"
            )
            f.write("*jaar maand dag verdamping[mm]\n")
        table = next(iter(self.rrmodel.external_forcings.evap.values()))["evap"]
        table = table.sort_index()
        date_format = "%#Y  %#m  %#d "
        float_format = "%.3f"
        sep = " "
        with open(filepath, "a") as f:
            for ts, val in zip(pd.DatetimeIndex(table.index), table):
                date = ts.strftime(date_format)
                f.write(f"{date}{sep}{float_format % val}\n")
write_openwater() -> None

Write OPENWATE.3B, the file of the open water nodes.

Source code in hydrolib/dhydamo/io/drrwriter.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def write_openwater(self) -> None:
    """Write ``OPENWATE.3B``, the file of the open water nodes."""
    # write openwater.3b
    if any(self.rrmodel.openwater.ow_nodes):
        filepath = os.path.join(self.output_dir, "OPENWATE.3B")
        with open(filepath, "w") as f:
            for dct in self.rrmodel.openwater.ow_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "OWRR id '"
                        + dct["id"]
                        + "' ar "
                        + dct["ar"]
                        + " ms '"
                        + dct["ms"]
                        + "' owrr\n"
                    )
write_paved() -> None

Write the files of the paved nodes.

PAVED.3B, PAVED.STO and PAVED.DWA. The latter has only one definition.

Source code in hydrolib/dhydamo/io/drrwriter.py
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
def write_paved(self) -> None:
    """Write the files of the paved nodes.

    ``PAVED.3B``, ``PAVED.STO`` and ``PAVED.DWA``. The latter has only one definition.
    """
    if any(self.rrmodel.paved.pav_nodes):
        filepath = os.path.join(self.output_dir, "PAVED.3B")
        with open(filepath, "w") as f:
            for dct in self.rrmodel.paved.pav_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "PAVE id '"
                        + dct["id"]
                        + "' ar "
                        + dct["ar"]
                        + " lv "
                        + dct["lv"]
                        + " sd 'sto_"
                        + dct["id"]
                        + "' ss 0 qc 0 "
                        + dct["qc"]
                        + " 0 qo 2 2 ms '"
                        + dct["ms"]
                        + "' is "
                        + dct["is"]
                        + " np "
                        + dct["np"]
                        + " dw 'Def_DWA' ro "
                        + dct["ro"]
                        + " ru "
                        + dct["ru"]
                        + " qh '' pave\n"
                    )

        filepath = os.path.join(self.output_dir, "PAVED.STO")
        with open(filepath, "w") as f:
            for dct in self.rrmodel.paved.pav_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "STDF id 'sto_"
                        + dct["id"]
                        + "' nm 'sto_"
                        + dct["id"]
                        + "' ms "
                        + dct["strs"]
                        + " is 0 mr "
                        + dct["sews"]
                        + " 0.0 ir 0.0 0.0 stdf\n"
                    )

        filepath = os.path.join(self.output_dir, "PAVED.DWA")
        with open(filepath, "w") as f:
            f.write(
                "DWA id 'Def_DWA' nm 'Def_DWA' do 1 wc 0 wd 0 wh 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 dwa\n"
            )

        filepath = os.path.join(self.output_dir, "WWTP.3B")
        with open(filepath, "w") as f:
            f.write("WWTP id 'WWTP' tb 0  wwtp\n")

        filepath = os.path.join(self.output_dir, "WWTP.tbl")
        with open(filepath, "w") as f:
            f.write("\n")
write_topology() -> None

Write the topology files of the RR model.

  • 3B_NOD.TP: ids and coordinates of all nodes: unpaved, paved, greenhouse, open water and boundary. Only nodes with a total area > 0 are written. Nodes are placed up to 20 m east and west of the catchment centroid.
  • 3B_LINK.TP: links between all nodes and their boundaries.
  • BOUND3B.3B: coupling information for every RR boundary.
  • BoundaryConditions.bc: see BOUND3B.3B.
Source code in hydrolib/dhydamo/io/drrwriter.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
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
def write_topology(self) -> None:
    """Write the topology files of the RR model.

    - ``3B_NOD.TP``: ids and coordinates of all nodes: unpaved, paved, greenhouse,
      open water and boundary. Only nodes with a total area > 0 are written. Nodes are
      placed up to 20 m east and west of the catchment centroid.
    - ``3B_LINK.TP``: links between all nodes and their boundaries.
    - ``BOUND3B.3B``: coupling information for every RR boundary.
    - ``BoundaryConditions.bc``: see ``BOUND3B.3B``.
    """
    filepath = os.path.join(self.output_dir, "3B_NOD.TP")
    with open(filepath, "w") as f:
        # Unpaved nodes
        if any(self.rrmodel.unpaved.unp_nodes):
            for dct in self.rrmodel.unpaved.unp_nodes.values():
                if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                    f.write(
                        "NODE id '"
                        + dct["id"]
                        + "' nm '"
                        + dct["id"]
                        + "' ri '-1' mt 1 '2' nt 44 ObID '3B_UNPAVED' px "
                        + dct["px"]
                        + " py "
                        + dct["py"]
                        + " node\n"
                    )

        # Paved nodes
        if any(self.rrmodel.paved.pav_nodes):
            for dct in self.rrmodel.paved.pav_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "NODE id '"
                        + dct["id"]
                        + "' nm '"
                        + dct["id"]
                        + "' ri '-1' mt 1 '1' nt 43 ObID '3B_PAVED' px "
                        + dct["px"]
                        + " py "
                        + dct["py"]
                        + " node\n"
                    )

            f.write(
                "NODE id 'WWTP' nm 'WWTP' ri '-1' mt 1 '14' nt 56 ObID '3B_WWTP' px "
                + str(self.wwtp.coords[0][0])
                + " py "
                + str(self.wwtp.coords[0][1])
                + " node\n"
            )
            f.write(
                "NODE id 'WWTP_BND' nm 'WWTP_BND' ri '-1' mt 1 '6' nt 47 ObID '3B_BOUNDARY' px "
                + str(self.wwtp.coords[0][0] + 50.0)
                + " py "
                + str(self.wwtp.coords[0][1] + 50.0)
                + " node\n"
            )

        # Greenhouse nodes
        if any(self.rrmodel.greenhouse.gh_nodes):
            for dct in self.rrmodel.greenhouse.gh_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "NODE id '"
                        + dct["id"]
                        + "' nm '"
                        + dct["id"]
                        + "' ri '-1' mt 1 '3' nt 45 ObID '3B_GREENHOUSE' px "
                        + dct["px"]
                        + " py "
                        + dct["py"]
                        + " node\n"
                    )

        # Openwater nodes
        if any(self.rrmodel.openwater.ow_nodes):
            for dct in self.rrmodel.openwater.ow_nodes.values():
                if float(dct["ar"]) > 0.0:
                    f.write(
                        "NODE id '"
                        + dct["id"]
                        + "' nm '"
                        + dct["id"]
                        + "' ri '-1' mt 1 '21' nt 46 ObID 'OW_PRECIP' px "
                        + dct["px"]
                        + " py "
                        + dct["py"]
                        + " node\n"
                    )

        # Boundary_nodes
        if any(self.rrmodel.external_forcings.boundary_nodes):
            for dct in self.rrmodel.external_forcings.boundary_nodes.values():
                f.write(
                    "NODE id '"
                    + dct["id"]
                    + "' nm '"
                    + dct["id"]
                    + "' ri '-1' mt 1 '6' nt 78 ObID 'SBK_SBK-3B-NODE' px "
                    + dct["px"]
                    + " py "
                    + dct["py"]
                    + " node\n"
                )

    filepath = os.path.join(self.output_dir, "3B_LINK.TP")
    with open(filepath, "w") as f:
        cnt = 0
        if any(self.rrmodel.unpaved.unp_nodes):
            for dct in self.rrmodel.unpaved.unp_nodes.values():
                if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                    cnt += 1
                    f.write(
                        "BRCH id 'link_"
                        + str(cnt)
                        + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                        + dct["id"]
                        + "' en '"
                        + dct["boundary_node"]
                        + "' brch\n"
                    )
        if any(self.rrmodel.paved.pav_nodes):
            for dct in self.rrmodel.paved.pav_nodes.values():
                if float(dct["ar"]) > 0.0:
                    cnt += 1
                    f.write(
                        "BRCH id 'link_"
                        + str(cnt)
                        + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                        + dct["id"]
                        + "' en '"
                        + dct["boundary_node"]
                        + "' brch\n"
                    )
                    cnt += 1
                    f.write(
                        "BRCH id 'link_"
                        + str(cnt)
                        + "' ri '-1' mt 1 '1' bt 18 ObID '3B_LINK_RWZI' bn '"
                        + dct["id"]
                        + "' en 'WWTP' brch\n"
                    )
            cnt += 1
            f.write(
                "BRCH id 'link_"
                + str(cnt)
                + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn 'WWTP' en 'WWTP_BND' brch\n"
            )

        if any(self.rrmodel.greenhouse.gh_nodes):
            for dct in self.rrmodel.greenhouse.gh_nodes.values():
                if float(dct["ar"]) > 0.0:
                    cnt += 1
                    f.write(
                        "BRCH id 'link_"
                        + str(cnt)
                        + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                        + dct["id"]
                        + "' en '"
                        + dct["boundary_node"]
                        + "' brch\n"
                    )
        if any(self.rrmodel.openwater.ow_nodes):
            for dct in self.rrmodel.openwater.ow_nodes.values():
                if float(dct["ar"]) > 0.0:
                    cnt += 1
                    f.write(
                        "BRCH id 'link_"
                        + str(cnt)
                        + "' ri '-1' mt 1 '0' bt 17 ObID '3B_LINK' bn '"
                        + dct["id"]
                        + "' en '"
                        + dct["boundary_node"]
                        + "' brch\n"
                    )

    # bound3b.3b
    filepath = os.path.join(self.output_dir, "Bound3B.3B")
    with open(filepath, "w") as f:
        for dct in self.rrmodel.external_forcings.boundary_nodes.values():
            f.write("BOUN id '" + dct["id"] + "' bl 2 '0' is 0 boun\n")
        if any(self.rrmodel.paved.pav_nodes):
            f.write("BOUN id 'WWTP_BND' bl 0 -3 is 0 boun\n")

    # BoundaryConditions.bc
    filepath = os.path.join(self.output_dir, "BoundaryConditions.bc")
    header = {"fileVersion": "1.01", "fileType": "boundConds"}
    with open(filepath, "w") as f:
        self._write_dict(f, header, "General", "\n")
        for dct in self.rrmodel.external_forcings.boundary_nodes.values():
            temp = {
                "name": "" + dct["id"],
                "function": "constant",
                "quantity": "water_level",
                "unit": "m",
            }
            self._write_dict(f, temp, "Boundary", "    0\n\n")
        if any(self.rrmodel.paved.pav_nodes):
            temp = {
                "name": "WWTP_BND",
                "function": "constant",
                "quantity": "water_level",
                "unit": "m",
            }
            self._write_dict(f, temp, "Boundary", "    0\n\n")
write_unpaved() -> None

Write the files of the unpaved nodes.

UNPAVED.3B, UNPAVED.ALF, UNPAVED.STO, UNPAVED.INF and UNPAVED.SEP. All files have a definition for every node, because the values may be spatially distributed.

Source code in hydrolib/dhydamo/io/drrwriter.py
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
def write_unpaved(self) -> None:
    """Write the files of the unpaved nodes.

    ``UNPAVED.3B``, ``UNPAVED.ALF``, ``UNPAVED.STO``, ``UNPAVED.INF`` and
    ``UNPAVED.SEP``. All files have a definition for every node, because the values
    may be spatially distributed.
    """
    if any(self.rrmodel.unpaved.unp_nodes):
        filepath = os.path.join(self.output_dir, "UNPAVED.3B")
        with open(filepath, "w") as f:
            for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                    f.write(
                        "UNPV id '"
                        + dct["id"]
                        + "' na "
                        + dct["na"]
                        + " ga "
                        + dct["ga"]
                        + " ar "
                        + dct["ar"]
                        + " lv "
                        + dct["lv"]
                        + " co "
                        + dct["co"]
                        + " su "
                        + dct["su"]
                        + " sd 'sto_"
                        + dct["id"]
                        + "' ic 'inf_"
                        + dct["id"]
                        + "' bt "
                        + dct["bt"]
                        + " ed '"
                        + dct["ed"]
                        + "' sp '"
                        + dct["sp"]
                        + "' ig 0 "
                        + dct["ig"]
                        + " mg "
                        + dct["mg"]
                        + " gl "
                        + dct["gl"]
                        + " is "
                        + dct["is"]
                        + " ms '"
                        + dct["ms"]
                        + "' unpv\n"
                    )

        filepath = os.path.join(self.output_dir, "UNPAVED.STO")
        with open(filepath, "w") as f:
            for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                    f.write(
                        "STDF id 'sto_"
                        + dct["id"]
                        + "' nm 'sto_"
                        + dct["id"]
                        + "' ml "
                        + dct["sd"]
                        + " il 0 stdf\n"
                    )

        filepath = os.path.join(self.output_dir, "UNPAVED.INF")
        with open(filepath, "w") as f:
            for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                    f.write(
                        "INFC id 'inf_"
                        + dct["id"]
                        + "' nm 'inf_"
                        + dct["id"]
                        + "' ic "
                        + dct["ic"]
                        + " infc\n"
                    )

        filepath = os.path.join(self.output_dir, "UNPAVED.ALF")
        with open(filepath, "w") as f:
            for _, dct in self.rrmodel.unpaved.ernst_defs.items():
                if (
                    np.sum(
                        [
                            float(d)
                            for d in self.rrmodel.unpaved.unp_nodes[_]["ar"].split(
                                " "
                            )
                        ]
                    )
                    > 0.0
                ):
                    f.write(
                        "ERNS id '"
                        + dct["id"]
                        + "' nm '"
                        + dct["id"]
                        + "' cvi "
                        + dct["cvi"]
                        + " cvo 0 "
                        + dct["cvo"]
                        + " cvs "
                        + dct["cvs"]
                        + " lv "
                        + dct["lv"]
                        + " erns\n"
                    )

        filepath = os.path.join(self.output_dir, "UNPAVED.SEP")
        with open(filepath, "w") as f:
            for _, dct in self.rrmodel.unpaved.unp_nodes.items():
                if np.sum([float(d) for d in dct["ar"].split(" ")]) > 0.0:
                    f.write(
                        "SEEP id '"
                        + dct["sp"]
                        + "' nm '"
                        + dct["sp"]
                        + "' co 4 PDIN 0 0 pdin ss 0\n"
                    )
                    f.write("TBLE\n")
                    seepage = self.rrmodel.external_forcings.seepage[dct["sp"]][
                        "seepage"
                    ]
                    f.writelines(
                        f"'{time.strftime('%Y/%m/%d;%H:%M:%S')}' {value:.5f} <\n"
                        for time, value in zip(
                            pd.DatetimeIndex(seepage.index), seepage
                        )
                    )
                    f.write("tble\nseep\n")

idfreader

Functions for reading and writing iMOD Data Files (IDFs) to xarray objects.

The primary functions to use are :func:imod.idf.open and :func:imod.idf.save, though lower level functions are also available.

The function in this file are taken from the imod-python package version 0.10.1.

The only functionality needed in dhydamo is the capability to read IDF files. imod itself is not a dependency: it needs Python >= 3.12 and brings gdal, numba, pymetis and more.

Compared with imod 1.1.0 (November 2026), whose reading code was restructured but is otherwise the same, this copy:

  • takes .item() of the top and bottom in _scalar_z_coord, as 1.1.0 does (numpy deprecates float() of a one-element array);
  • has type hints only for open and affine_from_idf, the functions dhydamo uses; mypy does not require them for the rest of this module (see pyproject.toml);
  • adds affine_from_idf.

affine_from_idf(dataset: xr.DataArray) -> Affine

Build a rasterio affine transform from an opened IDF dataset.

Parameters

dataset : xarray.DataArray Single-time, single-layer array as returned by idfreader.open(...).squeeze(), with scalar dx/dy coordinates and pixel-centre x/y coordinates.

Returns

affine.Affine Geotransform for the raster, derived from its pixel-centre coordinates and cell size.

Source code in hydrolib/dhydamo/io/idfreader.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
def affine_from_idf(dataset: xr.DataArray) -> Affine:
    """Build a rasterio affine transform from an opened IDF dataset.

    Parameters
    ----------
    dataset : xarray.DataArray
        Single-time, single-layer array as returned by
        ``idfreader.open(...).squeeze()``, with scalar ``dx``/``dy``
        coordinates and pixel-centre ``x``/``y`` coordinates.

    Returns
    -------
    affine.Affine
        Geotransform for the raster, derived from its pixel-centre
        coordinates and cell size.
    """
    dx = float(dataset["dx"])
    dy = float(dataset["dy"])
    west = float(dataset["x"].min()) - dx / 2.0
    north = float(dataset["y"].max()) - dy / 2.0
    return from_origin(west, north, dx, -dy)

decompose(path, pattern=None)

Parse a path, returning a dict of the parts, following the iMOD conventions.

Parameters

path : str or pathlib.Path Path to the file. Upper case is ignored. pattern : str, regex pattern, optional If the path is not made up of standard paths, and the default decompose does not produce the right result, specify the used pattern here. See the examples below.

Returns

d : dict Dictionary with name of variable and dimensions

Examples

Decompose a path, relying on default conventions:

decompose("head_20010101_l1.idf")

Do the same, by specifying a format string pattern, excluding extension:

decompose("head_20010101_l1.idf", pattern="{name}_{time}_l{layer}")

This supports an arbitrary number of variables:

decompose("head_slr_20010101_l1.idf", pattern="{name}{scenario}{time}_l{layer}")

The format string pattern will only work on tidy paths, where variables are separated by underscores. You can also pass a compiled regex pattern. Make sure to include the re.IGNORECASE flag since all paths are lowered.

import re pattern = re.compile(r"(?P[\w]+)L(?P[\d+]*)") decompose("headL11", pattern=pattern)

However, this requires constructing regular expressions, which is generally a fiddly process. The website https://regex101.com is a nice help. Alternatively, the most pragmatic solution may be to just rename your files.

Source code in hydrolib/dhydamo/io/idfreader.py
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
def decompose(path, pattern=None):
    r"""
    Parse a path, returning a dict of the parts, following the iMOD conventions.

    Parameters
    ----------
    path : str or pathlib.Path
        Path to the file. Upper case is ignored.
    pattern : str, regex pattern, optional
        If the path is not made up of standard paths, and the default decompose
        does not produce the right result, specify the used pattern here. See
        the examples below.

    Returns
    -------
    d : dict
        Dictionary with name of variable and dimensions

    Examples
    --------
    Decompose a path, relying on default conventions:

    >>> decompose("head_20010101_l1.idf")

    Do the same, by specifying a format string pattern, excluding extension:

    >>> decompose("head_20010101_l1.idf", pattern="{name}_{time}_l{layer}")

    This supports an arbitrary number of variables:

    >>> decompose("head_slr_20010101_l1.idf", pattern="{name}_{scenario}_{time}_l{layer}")

    The format string pattern will only work on tidy paths, where variables are
    separated by underscores. You can also pass a compiled regex pattern.
    Make sure to include the ``re.IGNORECASE`` flag since all paths are lowered.

    >>> import re
    >>> pattern = re.compile(r"(?P<name>[\w]+)L(?P<layer>[\d+]*)")
    >>> decompose("headL11", pattern=pattern)

    However, this requires constructing regular expressions, which is generally
    a fiddly process. The website https://regex101.com is a nice help.
    Alternatively, the most pragmatic solution may be to just rename your files.
    """
    path = pathlib.Path(path)
    # We'll ignore upper case
    stem = path.stem.lower()

    d = _groupdict(stem, pattern)
    dims = list(d.keys())
    # If name is not provided, generate one from other fields
    if "name" not in d:
        d["name"] = "_".join(d.values())
    else:
        dims.remove("name")

    # String -> type conversion
    if "layer" in d:
        d["layer"] = int(d["layer"])
    if "species" in d:
        d["species"] = int(d["species"])
    if "time" in d:
        d["time"] = to_datetime(d["time"])
    if "steady-state" in d["name"]:
        # steady-state as time identifier isn't picked up by <time>[0-9] regex
        d["name"] = d["name"].replace("_steady-state", "")
        d["time"] = "steady-state"
        dims.append("time")

    d["extension"] = path.suffix
    d["directory"] = path.parent
    d["dims"] = dims
    return d

header(path, pattern)

Read the IDF header information into a dictionary

Source code in hydrolib/dhydamo/io/idfreader.py
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
def header(path, pattern):
    """Read the IDF header information into a dictionary"""
    attrs = decompose(path, pattern)
    with f_open(path, "rb") as f:
        reclen_id = struct.unpack("i", f.read(4))[0]  # Lahey RecordLength Ident.
        if reclen_id == 1271:
            floatsize = intsize = 4
            floatformat = "f"
            intformat = "i"
            dtype = "float32"
            doubleprecision = False
        # 2296 was a typo in the iMOD manual. Keep 2296 around in case some IDFs
        # were written with this identifier to avoid possible incompatibility
        # issues.
        elif reclen_id == 2295 or reclen_id == 2296:
            floatsize = intsize = 8
            floatformat = "d"
            intformat = "q"
            dtype = "float64"
            doubleprecision = True
        else:
            raise ValueError(
                f"Not a supported IDF file: {path}\n"
                "Record length identifier should be 1271 or 2295, "
                f"received {reclen_id} instead."
            )

        # Header is fully doubled in size in case of double precision ...
        # This means integers are also turned into 8 bytes
        # and requires padding with some additional bytes
        if doubleprecision:
            f.read(4)  # not used

        ncol = struct.unpack(intformat, f.read(intsize))[0]
        nrow = struct.unpack(intformat, f.read(intsize))[0]
        attrs["xmin"] = struct.unpack(floatformat, f.read(floatsize))[0]
        attrs["xmax"] = struct.unpack(floatformat, f.read(floatsize))[0]
        attrs["ymin"] = struct.unpack(floatformat, f.read(floatsize))[0]
        attrs["ymax"] = struct.unpack(floatformat, f.read(floatsize))[0]
        # dmin and dmax are recomputed during writing
        f.read(floatsize)  # dmin, minimum data value present
        f.read(floatsize)  # dmax, maximum data value present
        nodata = struct.unpack(floatformat, f.read(floatsize))[0]
        attrs["nodata"] = nodata
        # flip definition here such that True means equidistant
        # equidistant IDFs
        ieq = not struct.unpack("?", f.read(1))[0]
        itb = struct.unpack("?", f.read(1))[0]

        f.read(2)  # not used
        if doubleprecision:
            f.read(4)  # not used

        if ieq:
            # dx and dy are stored positively in the IDF
            # dy is made negative here to be consistent with the nonequidistant case
            attrs["dx"] = struct.unpack(floatformat, f.read(floatsize))[0]
            attrs["dy"] = -struct.unpack(floatformat, f.read(floatsize))[0]

        if itb:
            attrs["top"] = struct.unpack(floatformat, f.read(floatsize))[0]
            attrs["bot"] = struct.unpack(floatformat, f.read(floatsize))[0]

        if not ieq:
            # dx and dy are stored positive in the IDF, but since the difference between
            # successive y coordinates is negative, it is made negative here
            attrs["dx"] = np.fromfile(f, dtype, ncol)
            attrs["dy"] = -np.fromfile(f, dtype, nrow)

        # These are derived, remove after using them downstream
        attrs["headersize"] = f.tell()
        attrs["ncol"] = ncol
        attrs["nrow"] = nrow
        attrs["dtype"] = dtype

    return attrs

open(path: str | pathlib.Path | list[pathlib.Path], use_cftime: bool = False, pattern: str | re.Pattern[str] | None = None) -> xr.DataArray

Open one or more IDF files as an xarray.DataArray.

In accordance with xarray's design, open loads the data of IDF files lazily. This means the data of the IDFs are not loaded into memory until the data is needed. This allows for easier handling of large datasets, and more efficient computations.

Parameters

path : str, Path or list This can be a single file, 'head_l1.idf', a glob pattern expansion, 'head_l*.idf', or a list of files, ['head_l1.idf', 'head_l2.idf']. Note that each file needs to be of the same name (part before the first underscore) but have a different layer and/or timestamp, such that they can be combined in a single xarray.DataArray. use_cftime : bool, optional Use cftime.DatetimeProlepticGregorian instead of np.datetime64[ns] for the time axis.

Dates are normally encoded as ``np.datetime64[ns]``; however, if dates
fall before 1678 or after 2261, they are automatically encoded as
``cftime.DatetimeProlepticGregorian`` objects rather than
``np.datetime64[ns]``.

pattern : str, regex pattern, optional If the filenames do match default naming conventions of {name}_{time}_l{layer}, a custom pattern can be defined here either as a string, or as a compiled regular expression pattern. See the examples below.

Returns

xarray.DataArray A float xarray.DataArray of the values in the IDF file(s). All metadata needed for writing the file to IDF or other formats using imod.rasterio are included in the xarray.DataArray.attrs.

Examples

Open an IDF file:

da = imod.idf.open("example.idf")

Open an IDF file, relying on default naming conventions to identify layer:

da = imod.idf.open("example_l1.idf")

Open an IDF file, relying on default naming conventions to identify layer and time:

head = imod.idf.open("head_20010101_l1.idf")

Open multiple IDF files, in this case files for the year 2001 for all layers, again relying on default conventions for naming:

head = imod.idf.open("head_2001_l.idf")

The same, this time explicitly specifying name, time, and layer:

head = imod.idf.open("head_2001_l.idf", pattern="{name}_{time}_l{layer}")

The format string pattern will only work on tidy paths, where variables are separated by underscores. You can also pass a compiled regex pattern. Make sure to include the re.IGNORECASE flag since all paths are lowered.

import re pattern = re.compile(r"(?P[\w]+)L(?P[\d+]*)", re.IGNORECASE) head = imod.idf.open("headL11", pattern=pattern)

However, this requires constructing regular expressions, which is generally a fiddly process. Regex notation is also impossible to remember. The website https://regex101.com is a nice help. Alternatively, the most pragmatic solution may be to just rename your files.

Source code in hydrolib/dhydamo/io/idfreader.py
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
def open(
    path: str | pathlib.Path | list[pathlib.Path],
    use_cftime: bool = False,
    pattern: str | re.Pattern[str] | None = None,
) -> xr.DataArray:
    r"""
    Open one or more IDF files as an xarray.DataArray.

    In accordance with xarray's design, ``open`` loads the data of IDF files
    lazily. This means the data of the IDFs are not loaded into memory until the
    data is needed. This allows for easier handling of large datasets, and
    more efficient computations.

    Parameters
    ----------
    path : str, Path or list
        This can be a single file, 'head_l1.idf', a glob pattern expansion,
        'head_l*.idf', or a list of files, ['head_l1.idf', 'head_l2.idf'].
        Note that each file needs to be of the same name (part before the
        first underscore) but have a different layer and/or timestamp,
        such that they can be combined in a single xarray.DataArray.
    use_cftime : bool, optional
        Use ``cftime.DatetimeProlepticGregorian`` instead of `np.datetime64[ns]`
        for the time axis.

        Dates are normally encoded as ``np.datetime64[ns]``; however, if dates
        fall before 1678 or after 2261, they are automatically encoded as
        ``cftime.DatetimeProlepticGregorian`` objects rather than
        ``np.datetime64[ns]``.
    pattern : str, regex pattern, optional
        If the filenames do match default naming conventions of
        {name}_{time}_l{layer}, a custom pattern can be defined here either
        as a string, or as a compiled regular expression pattern. See the
        examples below.

    Returns
    -------
    xarray.DataArray
        A float xarray.DataArray of the values in the IDF file(s).
        All metadata needed for writing the file to IDF or other formats
        using imod.rasterio are included in the xarray.DataArray.attrs.

    Examples
    --------
    Open an IDF file:

    >>> da = imod.idf.open("example.idf")

    Open an IDF file, relying on default naming conventions to identify
    layer:

    >>> da = imod.idf.open("example_l1.idf")

    Open an IDF file, relying on default naming conventions to identify layer
    and time:

    >>> head = imod.idf.open("head_20010101_l1.idf")

    Open multiple IDF files, in this case files for the year 2001 for all
    layers, again relying on default conventions for naming:

    >>> head = imod.idf.open("head_2001*_l*.idf")

    The same, this time explicitly specifying ``name``, ``time``, and ``layer``:

    >>> head = imod.idf.open("head_2001*_l*.idf", pattern="{name}_{time}_l{layer}")

    The format string pattern will only work on tidy paths, where variables are
    separated by underscores. You can also pass a compiled regex pattern.
    Make sure to include the ``re.IGNORECASE`` flag since all paths are lowered.

    >>> import re
    >>> pattern = re.compile(r"(?P<name>[\w]+)L(?P<layer>[\d+]*)", re.IGNORECASE)
    >>> head = imod.idf.open("headL11", pattern=pattern)

    However, this requires constructing regular expressions, which is
    generally a fiddly process. Regex notation is also impossible to
    remember. The website https://regex101.com is a nice help. Alternatively,
    the most pragmatic solution may be to just rename your files.
    """
    if isinstance(path, list):
        return _load(path, use_cftime, pattern, _read, header)
    elif isinstance(path, pathlib.Path):
        path = str(path)

    paths = [pathlib.Path(p) for p in glob.glob(path)]
    n = len(paths)
    if n == 0:
        raise FileNotFoundError(f"Could not find any files matching {path}")
    return _load(paths, use_cftime, pattern, _read, header)

read(path, pattern=None)

Read a single IDF file to a numpy.ndarray

Parameters

path : str or Path Path to the IDF file to be read pattern : str, regex pattern, optional If the filenames do match default naming conventions of {name}_{time}_l{layer}, a custom pattern can be defined here either as a string, or as a compiled regular expression pattern. Please refer to the examples for imod.idf.open.

Returns

numpy.ndarray A float numpy.ndarray with shape (nrow, ncol) of the values in the IDF file. On opening all nodata values are changed to NaN in the numpy.ndarray. dict A dict with all metadata.

Source code in hydrolib/dhydamo/io/idfreader.py
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
def read(path, pattern=None):
    """
    Read a single IDF file to a numpy.ndarray

    Parameters
    ----------
    path : str or Path
        Path to the IDF file to be read
    pattern : str, regex pattern, optional
        If the filenames do match default naming conventions of
        {name}_{time}_l{layer}, a custom pattern can be defined here either
        as a string, or as a compiled regular expression pattern. Please refer
        to the examples for ``imod.idf.open``.

    Returns
    -------
    numpy.ndarray
        A float numpy.ndarray with shape (nrow, ncol) of the values
        in the IDF file. On opening all nodata values are changed
        to NaN in the numpy.ndarray.
    dict
        A dict with all metadata.
    """
    warnings.warn(
        "The idf.read() function is deprecated. To get a numpy array of an IDF, "
        "use instead: imod.idf.open(path).values",
        FutureWarning,
    )
    attrs = header(path, pattern)
    headersize = attrs.pop("headersize")
    nrow = attrs.pop("nrow")
    ncol = attrs.pop("ncol")
    nodata = attrs.pop("nodata")
    dtype = attrs.pop("dtype")
    return _read(path, headersize, nrow, ncol, nodata, dtype), attrs

netcdfreader

Read D-Flow FM output files.

time_index(dataset: Dataset, time: datetime | pd.Timestamp | str, tolerance: float = 1.0) -> int

Return the index of the time step closest to a given time.

Works for D-Flow FM output files: map, his or fou.

Parameters

dataset : Dataset Opened netCDF file with a time variable. time : datetime, pd.Timestamp or str Requested time, e.g. "2016-06-02 12:00". A time without a time zone is taken in the time zone of the file (usually UTC). tolerance : float, optional Maximum difference in seconds that is accepted without a warning. Defaults to 1.0.

Returns

int Index of the nearest time step.

Raises

ValueError If the file has no time variable, or the time is outside its period.

Source code in hydrolib/dhydamo/io/netcdfreader.py
13
14
15
16
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
def time_index(
    dataset: Dataset, time: datetime | pd.Timestamp | str, tolerance: float = 1.0
) -> int:
    """Return the index of the time step closest to a given time.

    Works for D-Flow FM output files: map, his or fou.

    Parameters
    ----------
    dataset : Dataset
        Opened netCDF file with a ``time`` variable.
    time : datetime, pd.Timestamp or str
        Requested time, e.g. ``"2016-06-02 12:00"``. A time without a time zone is
        taken in the time zone of the file (usually UTC).
    tolerance : float, optional
        Maximum difference in seconds that is accepted without a warning. Defaults to
        1.0.

    Returns
    -------
    int
        Index of the nearest time step.

    Raises
    ------
    ValueError
        If the file has no time variable, or the time is outside its period.
    """
    if "time" not in dataset.variables:
        raise ValueError(f"No time variable in {dataset.filepath()}.")
    variable = dataset["time"]
    # the netCDF4 stubs return datetime | ndarray; for the array of all times this is always an ndarray
    times = pd.DatetimeIndex(
        num2date(
            variable[:],
            variable.units,
            only_use_cftime_datetimes=False,
            only_use_python_datetimes=True,
        )  # type: ignore[arg-type]
    )
    requested = pd.Timestamp(time)
    if requested.tzinfo is not None:
        requested = requested.tz_convert("UTC").tz_localize(None)

    if requested < times[0] or requested > times[-1]:
        raise ValueError(
            f"Time {requested} is outside the period of {dataset.filepath()}: {times[0]} - {times[-1]}."
        )
    index = int(np.argmin(np.abs((times - requested).total_seconds())))
    difference = abs((times[index] - requested).total_seconds())
    if difference > tolerance:
        logger.warning(
            f"No output at {requested}; the nearest time step {times[index]} is used."
        )
    else:
        logger.info(f"Time step {index} ({times[index]}) is used.")
    return index

rasterwriter

Write rasters.

write_raster(path: Path | str, array: np.ndarray, transform: Affine, crs: CRS | str | None = None, nodata: float = -999.0, compress: bool = True) -> Path

Write a single band raster.

The format follows from the extension: GeoTIFF for .tif and .tiff, ASCII grid for .asc. Missing folders are created.

Parameters

path : Path or str Output file. array : np.ndarray 2D array with values. transform : Affine Raster transform. crs : CRS or str, optional Coordinate reference system. Defaults to None. nodata : float, optional Nodata value. Defaults to -999.0. compress : bool, optional Deflate compression for GeoTIFF. Defaults to True.

Returns

Path Path of the written raster.

Raises

ValueError If the extension is not supported.

Source code in hydrolib/dhydamo/io/rasterwriter.py
13
14
15
16
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
def write_raster(
    path: Path | str,
    array: np.ndarray,
    transform: Affine,
    crs: CRS | str | None = None,
    nodata: float = -999.0,
    compress: bool = True,
) -> Path:
    """Write a single band raster.

    The format follows from the extension: GeoTIFF for ``.tif`` and ``.tiff``, ASCII
    grid for ``.asc``. Missing folders are created.

    Parameters
    ----------
    path : Path or str
        Output file.
    array : np.ndarray
        2D array with values.
    transform : Affine
        Raster transform.
    crs : CRS or str, optional
        Coordinate reference system. Defaults to None.
    nodata : float, optional
        Nodata value. Defaults to -999.0.
    compress : bool, optional
        Deflate compression for GeoTIFF. Defaults to True.

    Returns
    -------
    Path
        Path of the written raster.

    Raises
    ------
    ValueError
        If the extension is not supported.
    """
    path = Path(path)
    suffix = path.suffix.lower()
    if suffix not in DRIVERS:
        raise ValueError(
            f"Unsupported raster extension '{path.suffix}', use one of {list(DRIVERS)}."
        )
    driver = DRIVERS[suffix]
    profile = {
        "driver": driver,
        "height": array.shape[0],
        "width": array.shape[1],
        "count": 1,
        "dtype": array.dtype,
        "crs": crs,
        "transform": transform,
        "nodata": nodata,
    }
    if driver == "GTiff" and compress:
        profile["compress"] = "deflate"
    path.parent.mkdir(parents=True, exist_ok=True)
    with rasterio.open(path, "w", **profile) as dst:
        dst.write(array, 1)
    return path