Skip to content

I/O Module#

The I/O module is responsible for handling input/output operations in the D-FAST Bank Erosion software. It provides functionality for reading configuration files, loading and saving data, and logging.

Overview#

The I/O module serves as the interface between the D-FAST Bank Erosion software and external data sources and destinations. It handles reading configuration files, loading hydrodynamic simulation results, saving bank lines and erosion results, and logging information during the execution of the software.

Components#

The I/O module consists of the following components:

Configuration#

dfastbe.io.config #

Copyright (C) 2020 Stichting Deltares.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 2.1.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, see http://www.gnu.org/licenses/.

contact: delft3d.support@deltares.nl Stichting Deltares P.O. Box 177 2600 MH Delft, The Netherlands

All indications and logos of, and references to, "Delft3D" and "Deltares" are registered trademarks of Stichting Deltares, and remain the property of Stichting Deltares. All rights reserved.

INFORMATION This file is part of D-FAST Bank Erosion: https://github.com/Deltares/D-FAST_Bank_Erosion

ConfigFile #

Class to read configuration files for D-FAST Bank Erosion.

This class provides methods to read, write, and manage configuration files for the D-FAST Bank Erosion analysis. It also allows access to configuration settings and supports upgrading older configuration formats.

Source code in src/dfastbe/io/config.py
  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
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
class ConfigFile:
    """Class to read configuration files for D-FAST Bank Erosion.

    This class provides methods to read, write, and manage configuration files
    for the D-FAST Bank Erosion analysis. It also allows access to configuration
    settings and supports upgrading older configuration formats.
    """

    def __init__(self, config: ConfigParser, path: Union[Path, str] = None):
        """
        Initialize the ConfigFile object.

        Args:
            config (ConfigParser):
                Settings for the D-FAST Bank Erosion analysis.
            path (Union[Path, str]):
                Path to the configuration file.

        Examples:
            Reading a configuration file:
                ```python
                >>> import tempfile
                >>> from dfastbe.io.config import ConfigFile
                >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
                >>> print(config_file.config["General"]["Version"])
                1.0

                ```
            Writing a configuration file:
                ```python
                >>> from dfastbe.io.config import ConfigFile
                >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
                >>> with tempfile.TemporaryDirectory() as tmpdirname:
                ...     config_file.write(f"{tmpdirname}/meuse_manual_out.cfg")

                ```
        """
        self._config = config
        self.crs = "EPSG:28992"
        if path:
            self.path = Path(path)
            self.root_dir = self.path.parent
            self.make_paths_absolute()

    @property
    def config(self) -> ConfigParser:
        """ConfigParser: Get the configuration settings."""
        return self._config

    @config.setter
    def config(self, value: ConfigParser):
        self._config = value

    @property
    def version(self) -> str:
        """str: Get the version of the configuration file."""
        return self.get_str("General", "Version")

    @property
    def debug(self) -> bool:
        """bool: Get the debug flag."""
        return self.get_bool("General", "DebugOutput", False)

    @property
    def root_dir(self) -> Path | str:
        """Path: Get the root directory of the configuration file."""
        return self._root_dir

    @root_dir.setter
    def root_dir(self, value: str):
        self._root_dir = value

    @classmethod
    def read(cls, path: Union[str, Path]) -> "ConfigFile":
        """Read a configParser object (configuration file).

        Reads the config file using the standard `configparser`. Falls back to a
        dedicated reader compatible with old waqbank files.

        Args:
            path (Union[str, Path]): Path to the configuration file.

        Returns:
            ConfigFile: Settings for the D-FAST Bank Erosion analysis.

        Raises:
            FileNotFoundError: If the configuration file does not exist.
            Exception: If there is an error reading the config file.

        Examples:
            Read a config file:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")

            ```
        """
        if not Path(path).exists():
            raise FileNotFoundError(f"The Config-File: {path} does not exist")

        try:
            config = ConfigParser(comment_prefixes="%")
            with open(path, "r") as configfile:
                config.read_file(configfile)
        except ConfigparserError as e:
            print(f"Error during reading the config file: {e}")
            config = cls.config_file_callback_parser(path)

        # if version != "1.0":
        config = cls._upgrade(config)
        return cls(config, path=path)

    @staticmethod
    def config_file_callback_parser(path: str) -> ConfigParser:
        """Parse a configuration file as fallback to the read method.

        Args:
            path (str): Path to the configuration file.

        Returns:
            ConfigParser: Parsed configuration file.
        """
        config = ConfigParser()
        config["General"] = {}
        all_lines = open(path, "r").read().splitlines()
        for line in all_lines:
            perc = line.find("%")
            if perc >= 0:
                line = line[:perc]
            data = line.split()
            if len(data) >= 3:
                config["General"][data[0]] = data[2]
        return config

    @staticmethod
    def _upgrade(config: ConfigParser) -> ConfigParser:
        """Upgrade the configuration data structure to version 1.0 format.

        Args:
            config (ConfigParser): D-FAST Bank Erosion settings in 0.1 format.

        Returns:
            ConfigParser: D-FAST Bank Erosion settings in 1.0 format.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> result = config_file._upgrade(config_file.config)
            >>> isinstance(result, ConfigParser)
            True

            ```
        """
        try:
            version = config["General"]["Version"]
        except KeyError:
            version = "0.1"

        if version == "0.1":
            config["General"]["Version"] = "1.0"

            config["Detect"] = {}
            config = _move_parameter_location(
                config, "General", "Delft3Dfile", "Detect", "SimFile", convert=_sim2nc
            )
            config = _move_parameter_location(
                config, "General", "SDSfile", "Detect", "SimFile", convert=_sim2nc
            )
            config = _move_parameter_location(config, "General", "SimFile", "Detect")
            config = _move_parameter_location(config, "General", "NBank", "Detect")
            config_file = ConfigFile(config)
            n_bank = config_file.get_int("Detect", "NBank", default=0, positive=True)
            for i in range(1, n_bank + 1):
                config = _move_parameter_location(
                    config, "General", f"Line{i}", "Detect"
                )

            config = _move_parameter_location(config, "General", "WaterDepth", "Detect")
            config = _move_parameter_location(config, "General", "DLines", "Detect")

            config["Erosion"] = {}
            config = _move_parameter_location(config, "General", "TErosion", "Erosion")
            config = _move_parameter_location(config, "General", "RiverAxis", "Erosion")
            config = _move_parameter_location(config, "General", "Fairway", "Erosion")
            config = _move_parameter_location(config, "General", "RefLevel", "Erosion")
            config = _move_parameter_location(
                config, "General", "OutputInterval", "Erosion"
            )
            config = _move_parameter_location(config, "General", "OutputDir", "Erosion")
            config = _move_parameter_location(config, "General", "BankNew", "Erosion")
            config = _move_parameter_location(config, "General", "BankEq", "Erosion")
            config = _move_parameter_location(config, "General", "EroVol", "Erosion")
            config = _move_parameter_location(
                config, "General", "EroVolEqui", "Erosion"
            )
            config = _move_parameter_location(config, "General", "NLevel", "Erosion")
            config_file = ConfigFile(config)
            n_level = config_file.get_int("Erosion", "NLevel", default=0, positive=True)

            for i in range(1, n_level + 1):
                config = _move_parameter_location(
                    config,
                    "General",
                    f"Delft3Dfile{i}",
                    "Erosion",
                    f"SimFile{i}",
                    convert=_sim2nc,
                )
                config = _move_parameter_location(
                    config,
                    "General",
                    f"SDSfile{i}",
                    "Erosion",
                    f"SimFile{i}",
                    convert=_sim2nc,
                )
                config = _move_parameter_location(
                    config, "General", f"SimFile{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"PDischarge{i}", "Erosion"
                )

            config = _move_parameter_location(config, "General", "ShipType", "Erosion")
            config = _move_parameter_location(config, "General", "VShip", "Erosion")
            config = _move_parameter_location(config, "General", "NShip", "Erosion")
            config = _move_parameter_location(config, "General", "NWave", "Erosion")
            config = _move_parameter_location(config, "General", "Draught", "Erosion")
            config = _move_parameter_location(config, "General", "Wave0", "Erosion")
            config = _move_parameter_location(config, "General", "Wave1", "Erosion")

            config = _move_parameter_location(config, "General", "Classes", "Erosion")
            config = _move_parameter_location(config, "General", "BankType", "Erosion")
            config = _move_parameter_location(
                config, "General", "ProtectLevel", "Erosion", "ProtectionLevel"
            )
            config = _move_parameter_location(config, "General", "Slope", "Erosion")
            config = _move_parameter_location(config, "General", "Reed", "Erosion")
            config = _move_parameter_location(config, "General", "VelFilter", "Erosion")

            for i in range(1, n_level + 1):
                config = _move_parameter_location(
                    config, "General", f"ShipType{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"VShip{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"NShip{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"NWave{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"Draught{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"Slope{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"Reed{i}", "Erosion"
                )
                config = _move_parameter_location(
                    config, "General", f"EroVol{i}", "Erosion"
                )

        return config

    def write(self, filename: str) -> None:
        """Pretty print a configParser object (configuration file) to file.

        Pretty prints a `configparser` object to a file. Aligns the equal signs for
        all keyword/value pairs, adds a two-space indentation to all keyword lines,
        and adds an empty line before the start of a new block.

        Args:
            filename (str): Name of the configuration file to be written.

        Examples:
            ```python
            >>> import tempfile
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> with tempfile.TemporaryDirectory() as tmpdirname:
            ...     config_file.write(f"{tmpdirname}/meuse_manual_out.cfg")

            ```
        """
        sections = self.config.sections()
        max_length = 0
        for section in sections:
            options = self.config.options(section)
            max_length = max(max_length, *[len(option) for option in options])

        with open(filename, "w") as configfile:
            for index, section in enumerate(sections):
                if index > 0:
                    configfile.write("\n")
                configfile.write(f"[{section}]\n")

                for option in self.config.options(section):
                    configfile.write(
                        f"  {option:<{max_length}} = {self.config[section][option]}\n"
                    )

    def make_paths_absolute(self) -> str:
        """Convert all relative paths in the configuration to absolute paths.

        Returns:
            str: Absolute path of the configuration file's root directory.
        """
        self.resolve(self.root_dir)

        return self.root_dir

    def get_str(
        self,
        group: str,
        key: str,
        default: Optional[str] = None,
    ) -> str:
        """Get a string from a selected group and keyword in the analysis settings.

        Args:
            group (str): Name of the group from which to read.
            key (str): Name of the keyword from which to read.
            default (Optional[str]): Optional default value.

        Raises:
            ConfigFileError: If the keyword isn't specified and no default value is given.

        Returns:
            str: value of the keyword as string.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> result = config_file.get_str("General", "BankDir")
            >>> expected = Path("tests/data/erosion/output/banklines").resolve()
            >>> str(expected) == result
            True

            ```
        """
        try:
            val = self.config[group][key]
        except KeyError as e:
            if default is not None:
                val = default
            else:
                raise ConfigFileError(
                    f"No value specified for required keyword {key} in block {group}."
                ) from e
        return val

    def get_bool(
        self,
        group: str,
        key: str,
        default: Optional[bool] = None,
    ) -> bool:
        """Get a boolean from a selected group and keyword in the analysis settings.

        Args:
            group (str): Name of the group from which to read.
            key (str): Name of the keyword from which to read.
            default (Optional[bool]): Optional default value.

        Raises:
            ConfigFileError: If the keyword isn't specified and no default value is given.

        Returns:
            bool: value of the keyword as boolean.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.get_bool("General", "Plotting")
            True

            ```
        """
        try:
            str_val = self.config[group][key].lower()
            val = (
                (str_val == "yes")
                or (str_val == "y")
                or (str_val == "true")
                or (str_val == "t")
                or (str_val == "1")
            )
        except KeyError as e:
            if default is not None:
                val = default
            else:
                raise ConfigFileError(
                    f"No boolean value specified for required keyword {key} in block {group}."
                ) from e

        return val

    def get_float(
        self,
        group: str,
        key: str,
        default: Optional[float] = None,
        positive: bool = False,
    ) -> float:
        """Get a floating point value from a selected group and keyword in the analysis settings.

        Args:
            group (str): Name of the group from which to read.
            key (str): Name of the keyword from which to read.
            default (Optional[float]): Optional default value.
            positive (bool): Flag specifying which floats are accepted.
                All floats are accepted (if False), or only positive floats (if True).

        Raises:
            ConfigFileError: If the keyword isn't specified and no default value is given.
            ConfigFileError: If a negative value is specified when a positive value is required.


        Returns:
            float: value of the keyword as float.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.get_float("General", "ZoomStepKM")
            1.0

            ```
        """
        try:
            val = float(self.config[group][key])
        except (KeyError, ValueError) as e:
            if default is not None:
                val = default
            else:
                raise ConfigFileError(
                    f"No floating point value specified for required keyword {key} in block {group}."
                ) from e
        if positive and val < 0.0:
            raise ConfigFileError(
                f"Value for {key} in block {group} must be positive, not {val}."
            )
        return val

    def get_int(
        self,
        group: str,
        key: str,
        default: Optional[int] = None,
        positive: bool = False,
    ) -> int:
        """Get an integer from a selected group and keyword in the analysis settings.

        Args:
            group (str): Name of the group from which to read.
            key (str): Name of the keyword from which to read.
            default (Optional[int]): Optional default value.
            positive (bool): Flag specifying which floats are accepted.
                All floats are accepted (if False), or only positive floats (if True).

        Raises:
            ConfigFileError: If the keyword isn't specified and no default value is given.
            ConfigFileError: If a negative or zero value is specified when a positive value is required.


        Returns:
            int: value of the keyword as int.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.get_int("Detect", "NBank")
            2

            ```
        """
        try:
            val = int(self.config[group][key])
        except (KeyError, ValueError) as e:
            if default is not None:
                val = default
            else:
                raise ConfigFileError(
                    f"No integer value specified for required keyword {key} in block {group}."
                ) from e
        if positive and val <= 0:
            raise ConfigFileError(
                f"Value for {key} in block {group} must be positive, not {val}."
            )
        return val

    def get_sim_file(self, group: str, istr: str) -> str:
        """Get the name of the simulation file from the analysis settings.

        Args:
            group (str): Name of the group in which to search for the simulation file name.
            istr (str): Postfix for the simulation file name keyword;
                typically a string representation of the index.

        Returns:
            str: Name of the simulation file (empty string if keywords are not found).

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> result = config_file.get_sim_file("Erosion", "1")
            >>> expected = Path("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc").resolve()
            >>> str(expected) == result
            True

            ```
        """
        sim_file = self.config[group].get(f"SimFile{istr}", "")
        return sim_file

    def get_start_end_stations(self) -> Tuple[float, float]:
        """Get the start and end station for the river.

        Returns:
            Tuple[float, float]: start and end station.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.get_start_end_stations()
            (123.0, 128.0)

            ```
        """
        stations = self.get_range("General", "Boundaries")

        return stations

    def get_search_lines(self) -> List[LineString]:
        """Get the search lines for the bank lines from the analysis settings.

        Returns:
            List[np.ndarray]: List of arrays containing the x,y-coordinates of a bank search lines.
        """
        # read guiding bank line
        n_bank = self.get_int("Detect", "NBank")
        line = []
        for b in range(n_bank):
            bankfile = self.config["Detect"][f"Line{b + 1}"]
            log_text("read_search_line", data={"nr": b + 1, "file": bankfile})
            line.append(XYCModel.read(bankfile))
        return line

    def read_bank_lines(self, bank_dir: str) -> List[np.ndarray] | GeoDataFrame:
        """Get the bank lines from the detection step.

        Args:
            bank_dir (str): Name of directory in which the bank lines files are located.

        Returns:
            List[np.ndarray]: List of arrays containing the x,y-coordinates of a bank lines.
        """
        bank_name = self.get_str("General", "BankFile", "bankfile")
        bankfile = Path(bank_dir) / f"{bank_name}.shp"
        if bankfile.exists():
            log_text("read_banklines", data={"file": str(bankfile)})
            return gpd.read_file(bankfile)

        bankfile = Path(bank_dir) / f"{bank_name}_#.xyc"
        log_text("read_banklines", data={"file": str(bankfile)})
        bankline_list = []
        b = 1
        while True:
            xyc_file = Path(bank_dir) / f"{bank_name}_{b}.xyc"
            if not xyc_file.exists():
                break

            xy_bank = XYCModel.read(xyc_file)
            bankline_list.append(LineString(xy_bank))
            b += 1
        bankline_series = GeoSeries(bankline_list, crs=self.crs)
        banklines = GeoDataFrame(geometry=bankline_series)
        return banklines

    def get_parameter(
        self,
        group: str,
        key: str,
        num_stations_per_bank: List[int],
        default: Any = None,
        ext: str = "",
        positive: bool = False,
        valid: Optional[List[float]] = None,
        onefile: bool = False,
    ) -> List[np.ndarray]:
        """Get a parameter field from a selected group and keyword in the analysis settings.

        Args:
            group (str):
                Name of the group from which to read.
            key (str):
                Name of the keyword from which to read.
            num_stations_per_bank (List[int]):
                Number of stations (points) For each bank (bank chainage locations).
            default (Optional[Union[float, List[np.ndarray]]]):
                Optional default value or default parameter field; default None.
            ext (str):
                File name extension; default empty string.
            positive (bool):
                Flag specifying which boolean values are accepted.
                All values are accepted (if False), or only strictly positive values (if True); default False.
            valid (Optional[List[float]]):
                Optional list of valid values; default None.
            onefile (bool):
                Flag indicating whether parameters are read from one file.
                One file should be used for all bank lines (True) or one file per bank line (False; default).

        Raises:
            Exception:
                If a parameter isn't provided in the configuration, but no default value provided either.
                If the value is negative while a positive value is required (positive = True).
                If the value doesn't match one of the value values (valid is not None).

        Returns:
            List[np.ndarray]: Parameter field
                For each bank a parameter value per bank point (bank chainage location).

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> bank_km = [np.array([0, 1, 2]), np.array([3, 4, 5, 6, 7])]
            >>> num_stations_per_bank = [len(bank) for bank in bank_km]
            >>> config_file.get_parameter("General", "ZoomStepKM", num_stations_per_bank)
            [array([1., 1., 1.]), array([1., 1., 1., 1., 1.])]

            ```
        """
        try:
            value = self.config[group][key]
            use_default = False
        except (KeyError, TypeError) as e:
            value = None
            if default is None:
                raise ConfigFileError(
                    f'No value specified for required keyword "{key}" in block "{group}".'
                ) from e
            use_default = True

        return self.process_parameter(
            value=value,
            key=key,
            num_stations_per_bank=num_stations_per_bank,
            use_default=use_default,
            default=default,
            ext=ext,
            positive=positive,
            valid=valid,
            onefile=onefile,
        )

    def validate_parameter_value(
        self,
        value: float,
        key: str,
        positive: bool = False,
        valid: Optional[List[float]] = None,
    ) -> float:
        """Validate a parameter value against constraints.

        Args:
            value (float): The parameter value to validate.
            key (str): Name of the parameter for error messages.
            positive (bool): Flag specifying whether all values are accepted (if False),
                or only positive values (if True); default False.
            valid (Optional[List[float]]): Optional list of valid values; default None.

        Raises:
            ValueError: If the value doesn't meet the constraints.

        Returns:
            float: The validated parameter value.
        """
        if positive and value < 0:
            raise ValueError(f'Value of "{key}" should be positive, not {value}.')
        if valid is not None and valid.count(value) == 0:
            raise ValueError(f'Value of "{key}" should be in {valid}, not {value}.')
        return value

    def process_parameter(
        self,
        value: Union[str, float],
        key: str,
        num_stations_per_bank: List[int],
        use_default: bool = False,
        default: Any = None,
        ext: str = "",
        positive: bool = False,
        valid: Optional[List[float]] = None,
        onefile: bool = False,
    ) -> List[np.ndarray]:
        """
        Process a parameter value into arrays for each bank.

        Args:
            value (Union[str, float]):
                The parameter value or a path to a file.
            key (str):
                Name of the parameter for error messages.
            num_stations_per_bank (List[int]):
                Number of stations for each bank.
            use_default (bool):
                Whether to use the default value.
            default (Optional[float], default=None):
                Default value used if `use_default` is True.
            ext (str, default=''):
                File name extension.
            positive (bool, default=False):
                If True, only positive values are allowed.
            valid (Optional[List[float]], default=None):
                List of valid values.
            onefile (bool, default=False):
                If True, parameters are read from a single file for all banks;
                otherwise, one file per bank.

        Returns:
            List[np.ndarray]: Parameter values for each bank.
        """
        # if val is value then use that value globally
        parameter_values = []
        try:
            if use_default:
                if isinstance(default, list):
                    return default
                real_val = default
            else:
                real_val = float(value)
                self.validate_parameter_value(real_val, key, positive, valid)

            for num_stations in num_stations_per_bank:
                parameter_values.append(np.zeros(num_stations) + real_val)

        except (ValueError, TypeError):
            if onefile:
                log_text("read_param", data={"param": key, "file": value})
                km_thr, val = _get_stations(value, key, positive)

            for ib, num_stations in enumerate(num_stations_per_bank):
                if not onefile:
                    filename_i = f"{value}_{ib + 1}{ext}"
                    log_text(
                        "read_param_one_bank",
                        data={"param": key, "i": ib + 1, "file": filename_i},
                    )
                    km_thr, val = _get_stations(filename_i, key, positive)

                if km_thr is None:
                    parameter_values.append(np.zeros(num_stations) + val[0])
                else:
                    idx = np.zeros(num_stations, dtype=int)

                    for thr in km_thr:
                        idx[num_stations >= thr] += 1
                    parameter_values.append(val[idx])

        return parameter_values

    def get_bank_search_distances(self, num_search_lines: int) -> List[float]:
        """Get the search distance per bank line from the analysis settings.

        Args:
            num_search_lines (int): Number of bank search lines.

        Returns:
            List[float]: Array of length nbank containing the search distance value per bank line (default value: 50).

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.get_bank_search_distances(2)
            [50.0, 50.0]

            ```
        """
        d_lines_key = self.config["Detect"].get("DLines", None)
        if d_lines_key is None:
            d_lines = [50] * num_search_lines
        elif d_lines_key[0] == "[" and d_lines_key[-1] == "]":
            d_lines_split = d_lines_key[1:-1].split(",")
            d_lines = [float(d) for d in d_lines_split]
            if not all([d > 0 for d in d_lines]):
                raise ValueError(
                    "keyword DLINES should contain positive values in the configuration file."
                )
            if len(d_lines) != num_search_lines:
                raise ConfigFileError(
                    "keyword DLINES should contain NBANK values in the configuration file."
                )
        return d_lines

    def get_range(self, group: str, key: str) -> Tuple[float, float]:
        """Get a start and end value from a selected group and keyword in the analysis settings.

        Args:
            group (str): Name of the group from which to read.
            key (str): Name of the keyword from which to read.

        Returns:
            Tuple[float,float]: Lower and upper limit of the range.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.get_range("General", "Boundaries")
            (123.0, 128.0)

            ```
        """
        str_val = self.get_str(group, key)
        try:
            obrack = str_val.find("[")
            cbrack = str_val.find("]")
            if obrack >= 0 and cbrack >= 0:
                str_val = str_val[obrack + 1 : cbrack - 1]
            val_list = [float(fstr) for fstr in str_val.split(":")]
            if val_list[0] > val_list[1]:
                val = (val_list[1], val_list[0])
            else:
                val = (val_list[0], val_list[1])
        except ValueError as e:
            raise ValueError(
                f'Invalid range specification "{str_val}" for required keyword "{key}" in block "{group}".'
            ) from e
        return val

    def get_river_center_line(self) -> LineString:
        """Get the river center line from the xyc file as a linestring.

        Returns:
            LineString: Chainage line.
        """
        # get the chainage file
        river_center_line_file = self.get_str("General", "RiverKM")
        log_text("read_chainage", data={"file": river_center_line_file})
        river_center_line = XYCModel.read(river_center_line_file, num_columns=3)

        # make sure that chainage is increasing with node index
        if river_center_line.coords[0][2] > river_center_line.coords[1][2]:
            river_center_line = LineString(river_center_line.coords[::-1])

        return river_center_line

    def resolve(self, rootdir: str):
        """Convert a configuration object to contain absolute paths (for editing).

        Args:
            rootdir (str): The path to be used as base for the absolute paths.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.resolve("tests/data/erosion")

            ```
        """
        if "General" in self.config:
            self.resolve_parameter("General", "RiverKM", rootdir)
            self.resolve_parameter("General", "BankDir", rootdir)
            self.resolve_parameter("General", "FigureDir", rootdir)

        if "Detect" in self.config:
            self.resolve_parameter("Detect", "SimFile", rootdir)
            i = 0
            while True:
                i = i + 1
                line_i = "Line" + str(i)
                if line_i in self.config["Detect"]:
                    self.resolve_parameter("Detect", line_i, rootdir)
                else:
                    break

        if "Erosion" in self.config:
            self.resolve_parameter("Erosion", "RiverAxis", rootdir)
            self.resolve_parameter("Erosion", "Fairway", rootdir)
            self.resolve_parameter("Erosion", "OutputDir", rootdir)

            self.resolve_parameter("Erosion", "ShipType", rootdir)
            self.resolve_parameter("Erosion", "VShip", rootdir)
            self.resolve_parameter("Erosion", "NShip", rootdir)
            self.resolve_parameter("Erosion", "NWave", rootdir)
            self.resolve_parameter("Erosion", "Draught", rootdir)
            self.resolve_parameter("Erosion", "Wave0", rootdir)
            self.resolve_parameter("Erosion", "Wave1", rootdir)

            self.resolve_parameter("Erosion", "BankType", rootdir)
            self.resolve_parameter("Erosion", "ProtectionLevel", rootdir)
            self.resolve_parameter("Erosion", "Slope", rootdir)
            self.resolve_parameter("Erosion", "Reed", rootdir)

            n_level = self.get_int("Erosion", "NLevel", default=0)
            for i in range(1, n_level + 1):
                self.resolve_parameter("Erosion", f"SimFile{i}", rootdir)
                self.resolve_parameter("Erosion", f"ShipType{i}", rootdir)
                self.resolve_parameter("Erosion", f"VShip{i}", rootdir)
                self.resolve_parameter("Erosion", f"NShip{i}", rootdir)
                self.resolve_parameter("Erosion", f"NWave{i}", rootdir)
                self.resolve_parameter("Erosion", f"Draught{i}", rootdir)
                self.resolve_parameter("Erosion", f"Slope{i}", rootdir)
                self.resolve_parameter("Erosion", f"Reed{i}", rootdir)

    def relative_to(self, rootdir: str) -> None:
        """Convert a configuration object to contain relative paths (for saving).

        Args:
            rootdir (str): The path to be used as base for the relative paths.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.relative_to("testing/data/erosion")

            ```
        """
        if "General" in self.config:
            self.parameter_relative_to("General", "RiverKM", rootdir)
            self.parameter_relative_to("General", "BankDir", rootdir)
            self.parameter_relative_to("General", "FigureDir", rootdir)

        if "Detect" in self.config:
            self.parameter_relative_to("Detect", "SimFile", rootdir)

            i = 0
            while True:
                i = i + 1
                line_i = f"Line{i}"
                if line_i in self.config["Detect"]:
                    self.parameter_relative_to("Detect", line_i, rootdir)
                else:
                    break

        if "Erosion" in self.config:
            self.parameter_relative_to("Erosion", "RiverAxis", rootdir)
            self.parameter_relative_to("Erosion", "Fairway", rootdir)
            self.parameter_relative_to("Erosion", "OutputDir", rootdir)

            self.parameter_relative_to("Erosion", "ShipType", rootdir)
            self.parameter_relative_to("Erosion", "VShip", rootdir)
            self.parameter_relative_to("Erosion", "NShip", rootdir)
            self.parameter_relative_to("Erosion", "NWave", rootdir)
            self.parameter_relative_to("Erosion", "Draught", rootdir)
            self.parameter_relative_to("Erosion", "Wave0", rootdir)
            self.parameter_relative_to("Erosion", "Wave1", rootdir)

            self.parameter_relative_to("Erosion", "BankType", rootdir)
            self.parameter_relative_to("Erosion", "ProtectionLevel", rootdir)
            self.parameter_relative_to("Erosion", "Slope", rootdir)
            self.parameter_relative_to("Erosion", "Reed", rootdir)

            n_level = self.get_int("Erosion", "NLevel", default=0)
            for i in range(1, n_level + 1):
                self.parameter_relative_to("Erosion", f"SimFile{i}", rootdir)
                self.parameter_relative_to("Erosion", f"ShipType{i}", rootdir)
                self.parameter_relative_to("Erosion", f"VShip{i}", rootdir)
                self.parameter_relative_to("Erosion", f"NShip{i}", rootdir)
                self.parameter_relative_to("Erosion", f"NWave{i}", rootdir)
                self.parameter_relative_to("Erosion", f"Draught{i}", rootdir)
                self.parameter_relative_to("Erosion", f"Slope{i}", rootdir)
                self.parameter_relative_to("Erosion", f"Reed{i}", rootdir)

    def resolve_parameter(self, group: str, key: str, rootdir: str):
        """Convert a parameter value to contain an absolute path.

        Determine whether the string represents a number.
        If not, try to convert to an absolute path.

        Args:
            group (str): Name of the group in the configuration.
            key (str): Name of the key in the configuration.
            rootdir (str): The path to be used as base for the absolute paths.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.resolve_parameter("General", "RiverKM", "tests/data/erosion")

            ```
        """
        if key in self.config[group]:
            val_str = self.config[group][key]
            try:
                float(val_str)
            except ValueError:
                self.config[group][key] = absolute_path(rootdir, val_str)

    def parameter_relative_to(self, group: str, key: str, rootdir: str):
        """Convert a parameter value to contain a relative path.

        Determine whether the string represents a number.
        If not, try to convert to a relative path.

        Args:
            group (str): Name of the group in the configuration.
            key (str): Name of the key in the configuration.
            rootdir (str): The path to be used as base for the relative paths.

        Examples:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> config_file.parameter_relative_to("General", "RiverKM", "tests/data/erosion")

            ```
        """
        if key in self.config[group]:
            val_str = self.config[group][key]

            try:
                float(val_str)
            except ValueError:
                self.config[group][key] = relative_path(rootdir, val_str)

    def get_plotting_flags(self, root_dir: Path | str) -> Dict[str, bool]:
        """Get the plotting flags from the configuration file.

        Returns:
            data (Dict[str, bool]):
                Dictionary containing the plotting flags.
                save_plot (bool): Flag indicating whether to save the plot.
                save_plot_zoomed (bool): Flag indicating whether to save the zoomed plot.
                zoom_km_step (float): Step size for zooming in on the plot.
                close_plot (bool): Flag indicating whether to close the plot.
        """
        plot_data = self.get_bool("General", "Plotting", True)

        if plot_data:
            save_plot = self.get_bool("General", "SavePlots", True)
            save_plot_zoomed = self.get_bool("General", "SaveZoomPlots", True)
            zoom_km_step = self.get_float("General", "ZoomStepKM", 1.0)
            if zoom_km_step < 0.01:
                save_plot_zoomed = False
            close_plot = self.get_bool("General", "ClosePlots", False)
        else:
            save_plot = False
            save_plot_zoomed = False
            close_plot = False

        data = {
            "plot_data": plot_data,
            "save_plot": save_plot,
            "save_plot_zoomed": save_plot_zoomed,
            "zoom_km_step": zoom_km_step,
            "close_plot": close_plot,
        }

        # as appropriate, check output dir for figures and file format
        if save_plot:
            fig_dir = self.get_str("General", "FigureDir", Path(root_dir) / "figure")
            log_text("figure_dir", data={"dir": fig_dir})
            path_fig_dir = Path(fig_dir)
            if path_fig_dir.exists():
                log_text("overwrite_dir", data={"dir": fig_dir})
            path_fig_dir.mkdir(parents=True, exist_ok=True)
            plot_ext = self.get_str("General", "FigureExt", ".png")
            data = data | {
                "fig_dir": fig_dir,
                "plot_ext": plot_ext,
            }

        return data

    def get_output_dir(self, option: str) -> Path:
        """Get the output directory for the analysis.

        Args:
            option (str):
                Option for which to get the output directory. "banklines" for bank lines, else the erosion output
                directory will be returned.
        Returns:
            output_dir (Path):
                Path to the output directory.
        """
        if option == "banklines":
            output_dir = self.get_str("General", "BankDir")
        else:
            output_dir = self.get_str("Erosion", "OutputDir")

        output_dir = Path(output_dir)
        log_text(f"{option}_out", data={"dir": output_dir})
        if output_dir.exists():
            log_text("overwrite_dir", data={"dir": output_dir})
        else:
            output_dir.mkdir(parents=True, exist_ok=True)

        return output_dir

config: ConfigParser property writable #

ConfigParser: Get the configuration settings.

debug: bool property #

bool: Get the debug flag.

root_dir: Path | str property writable #

Path: Get the root directory of the configuration file.

version: str property #

str: Get the version of the configuration file.

__init__(config: ConfigParser, path: Union[Path, str] = None) #

Initialize the ConfigFile object.

Parameters:

Name Type Description Default
config ConfigParser

Settings for the D-FAST Bank Erosion analysis.

required
path Union[Path, str]

Path to the configuration file.

None

Examples:

Reading a configuration file:

>>> import tempfile
>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> print(config_file.config["General"]["Version"])
1.0
Writing a configuration file:
>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     config_file.write(f"{tmpdirname}/meuse_manual_out.cfg")

Source code in src/dfastbe/io/config.py
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
def __init__(self, config: ConfigParser, path: Union[Path, str] = None):
    """
    Initialize the ConfigFile object.

    Args:
        config (ConfigParser):
            Settings for the D-FAST Bank Erosion analysis.
        path (Union[Path, str]):
            Path to the configuration file.

    Examples:
        Reading a configuration file:
            ```python
            >>> import tempfile
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> print(config_file.config["General"]["Version"])
            1.0

            ```
        Writing a configuration file:
            ```python
            >>> from dfastbe.io.config import ConfigFile
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> with tempfile.TemporaryDirectory() as tmpdirname:
            ...     config_file.write(f"{tmpdirname}/meuse_manual_out.cfg")

            ```
    """
    self._config = config
    self.crs = "EPSG:28992"
    if path:
        self.path = Path(path)
        self.root_dir = self.path.parent
        self.make_paths_absolute()

config_file_callback_parser(path: str) -> ConfigParser staticmethod #

Parse a configuration file as fallback to the read method.

Parameters:

Name Type Description Default
path str

Path to the configuration file.

required

Returns:

Name Type Description
ConfigParser ConfigParser

Parsed configuration file.

Source code in src/dfastbe/io/config.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
@staticmethod
def config_file_callback_parser(path: str) -> ConfigParser:
    """Parse a configuration file as fallback to the read method.

    Args:
        path (str): Path to the configuration file.

    Returns:
        ConfigParser: Parsed configuration file.
    """
    config = ConfigParser()
    config["General"] = {}
    all_lines = open(path, "r").read().splitlines()
    for line in all_lines:
        perc = line.find("%")
        if perc >= 0:
            line = line[:perc]
        data = line.split()
        if len(data) >= 3:
            config["General"][data[0]] = data[2]
    return config

get_bank_search_distances(num_search_lines: int) -> List[float] #

Get the search distance per bank line from the analysis settings.

Parameters:

Name Type Description Default
num_search_lines int

Number of bank search lines.

required

Returns:

Type Description
List[float]

List[float]: Array of length nbank containing the search distance value per bank line (default value: 50).

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.get_bank_search_distances(2)
[50.0, 50.0]
Source code in src/dfastbe/io/config.py
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
def get_bank_search_distances(self, num_search_lines: int) -> List[float]:
    """Get the search distance per bank line from the analysis settings.

    Args:
        num_search_lines (int): Number of bank search lines.

    Returns:
        List[float]: Array of length nbank containing the search distance value per bank line (default value: 50).

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.get_bank_search_distances(2)
        [50.0, 50.0]

        ```
    """
    d_lines_key = self.config["Detect"].get("DLines", None)
    if d_lines_key is None:
        d_lines = [50] * num_search_lines
    elif d_lines_key[0] == "[" and d_lines_key[-1] == "]":
        d_lines_split = d_lines_key[1:-1].split(",")
        d_lines = [float(d) for d in d_lines_split]
        if not all([d > 0 for d in d_lines]):
            raise ValueError(
                "keyword DLINES should contain positive values in the configuration file."
            )
        if len(d_lines) != num_search_lines:
            raise ConfigFileError(
                "keyword DLINES should contain NBANK values in the configuration file."
            )
    return d_lines

get_bool(group: str, key: str, default: Optional[bool] = None) -> bool #

Get a boolean from a selected group and keyword in the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group from which to read.

required
key str

Name of the keyword from which to read.

required
default Optional[bool]

Optional default value.

None

Raises:

Type Description
ConfigFileError

If the keyword isn't specified and no default value is given.

Returns:

Name Type Description
bool bool

value of the keyword as boolean.

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.get_bool("General", "Plotting")
True
Source code in src/dfastbe/io/config.py
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
def get_bool(
    self,
    group: str,
    key: str,
    default: Optional[bool] = None,
) -> bool:
    """Get a boolean from a selected group and keyword in the analysis settings.

    Args:
        group (str): Name of the group from which to read.
        key (str): Name of the keyword from which to read.
        default (Optional[bool]): Optional default value.

    Raises:
        ConfigFileError: If the keyword isn't specified and no default value is given.

    Returns:
        bool: value of the keyword as boolean.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.get_bool("General", "Plotting")
        True

        ```
    """
    try:
        str_val = self.config[group][key].lower()
        val = (
            (str_val == "yes")
            or (str_val == "y")
            or (str_val == "true")
            or (str_val == "t")
            or (str_val == "1")
        )
    except KeyError as e:
        if default is not None:
            val = default
        else:
            raise ConfigFileError(
                f"No boolean value specified for required keyword {key} in block {group}."
            ) from e

    return val

get_float(group: str, key: str, default: Optional[float] = None, positive: bool = False) -> float #

Get a floating point value from a selected group and keyword in the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group from which to read.

required
key str

Name of the keyword from which to read.

required
default Optional[float]

Optional default value.

None
positive bool

Flag specifying which floats are accepted. All floats are accepted (if False), or only positive floats (if True).

False

Raises:

Type Description
ConfigFileError

If the keyword isn't specified and no default value is given.

ConfigFileError

If a negative value is specified when a positive value is required.

Returns:

Name Type Description
float float

value of the keyword as float.

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.get_float("General", "ZoomStepKM")
1.0
Source code in src/dfastbe/io/config.py
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
def get_float(
    self,
    group: str,
    key: str,
    default: Optional[float] = None,
    positive: bool = False,
) -> float:
    """Get a floating point value from a selected group and keyword in the analysis settings.

    Args:
        group (str): Name of the group from which to read.
        key (str): Name of the keyword from which to read.
        default (Optional[float]): Optional default value.
        positive (bool): Flag specifying which floats are accepted.
            All floats are accepted (if False), or only positive floats (if True).

    Raises:
        ConfigFileError: If the keyword isn't specified and no default value is given.
        ConfigFileError: If a negative value is specified when a positive value is required.


    Returns:
        float: value of the keyword as float.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.get_float("General", "ZoomStepKM")
        1.0

        ```
    """
    try:
        val = float(self.config[group][key])
    except (KeyError, ValueError) as e:
        if default is not None:
            val = default
        else:
            raise ConfigFileError(
                f"No floating point value specified for required keyword {key} in block {group}."
            ) from e
    if positive and val < 0.0:
        raise ConfigFileError(
            f"Value for {key} in block {group} must be positive, not {val}."
        )
    return val

get_int(group: str, key: str, default: Optional[int] = None, positive: bool = False) -> int #

Get an integer from a selected group and keyword in the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group from which to read.

required
key str

Name of the keyword from which to read.

required
default Optional[int]

Optional default value.

None
positive bool

Flag specifying which floats are accepted. All floats are accepted (if False), or only positive floats (if True).

False

Raises:

Type Description
ConfigFileError

If the keyword isn't specified and no default value is given.

ConfigFileError

If a negative or zero value is specified when a positive value is required.

Returns:

Name Type Description
int int

value of the keyword as int.

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.get_int("Detect", "NBank")
2
Source code in src/dfastbe/io/config.py
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
def get_int(
    self,
    group: str,
    key: str,
    default: Optional[int] = None,
    positive: bool = False,
) -> int:
    """Get an integer from a selected group and keyword in the analysis settings.

    Args:
        group (str): Name of the group from which to read.
        key (str): Name of the keyword from which to read.
        default (Optional[int]): Optional default value.
        positive (bool): Flag specifying which floats are accepted.
            All floats are accepted (if False), or only positive floats (if True).

    Raises:
        ConfigFileError: If the keyword isn't specified and no default value is given.
        ConfigFileError: If a negative or zero value is specified when a positive value is required.


    Returns:
        int: value of the keyword as int.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.get_int("Detect", "NBank")
        2

        ```
    """
    try:
        val = int(self.config[group][key])
    except (KeyError, ValueError) as e:
        if default is not None:
            val = default
        else:
            raise ConfigFileError(
                f"No integer value specified for required keyword {key} in block {group}."
            ) from e
    if positive and val <= 0:
        raise ConfigFileError(
            f"Value for {key} in block {group} must be positive, not {val}."
        )
    return val

get_output_dir(option: str) -> Path #

Get the output directory for the analysis.

Parameters:

Name Type Description Default
option str

Option for which to get the output directory. "banklines" for bank lines, else the erosion output directory will be returned.

required

Returns: output_dir (Path): Path to the output directory.

Source code in src/dfastbe/io/config.py
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
def get_output_dir(self, option: str) -> Path:
    """Get the output directory for the analysis.

    Args:
        option (str):
            Option for which to get the output directory. "banklines" for bank lines, else the erosion output
            directory will be returned.
    Returns:
        output_dir (Path):
            Path to the output directory.
    """
    if option == "banklines":
        output_dir = self.get_str("General", "BankDir")
    else:
        output_dir = self.get_str("Erosion", "OutputDir")

    output_dir = Path(output_dir)
    log_text(f"{option}_out", data={"dir": output_dir})
    if output_dir.exists():
        log_text("overwrite_dir", data={"dir": output_dir})
    else:
        output_dir.mkdir(parents=True, exist_ok=True)

    return output_dir

get_parameter(group: str, key: str, num_stations_per_bank: List[int], default: Any = None, ext: str = '', positive: bool = False, valid: Optional[List[float]] = None, onefile: bool = False) -> List[np.ndarray] #

Get a parameter field from a selected group and keyword in the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group from which to read.

required
key str

Name of the keyword from which to read.

required
num_stations_per_bank List[int]

Number of stations (points) For each bank (bank chainage locations).

required
default Optional[Union[float, List[ndarray]]]

Optional default value or default parameter field; default None.

None
ext str

File name extension; default empty string.

''
positive bool

Flag specifying which boolean values are accepted. All values are accepted (if False), or only strictly positive values (if True); default False.

False
valid Optional[List[float]]

Optional list of valid values; default None.

None
onefile bool

Flag indicating whether parameters are read from one file. One file should be used for all bank lines (True) or one file per bank line (False; default).

False

Raises:

Type Description
Exception

If a parameter isn't provided in the configuration, but no default value provided either. If the value is negative while a positive value is required (positive = True). If the value doesn't match one of the value values (valid is not None).

Returns:

Type Description
List[ndarray]

List[np.ndarray]: Parameter field For each bank a parameter value per bank point (bank chainage location).

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> bank_km = [np.array([0, 1, 2]), np.array([3, 4, 5, 6, 7])]
>>> num_stations_per_bank = [len(bank) for bank in bank_km]
>>> config_file.get_parameter("General", "ZoomStepKM", num_stations_per_bank)
[array([1., 1., 1.]), array([1., 1., 1., 1., 1.])]
Source code in src/dfastbe/io/config.py
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
def get_parameter(
    self,
    group: str,
    key: str,
    num_stations_per_bank: List[int],
    default: Any = None,
    ext: str = "",
    positive: bool = False,
    valid: Optional[List[float]] = None,
    onefile: bool = False,
) -> List[np.ndarray]:
    """Get a parameter field from a selected group and keyword in the analysis settings.

    Args:
        group (str):
            Name of the group from which to read.
        key (str):
            Name of the keyword from which to read.
        num_stations_per_bank (List[int]):
            Number of stations (points) For each bank (bank chainage locations).
        default (Optional[Union[float, List[np.ndarray]]]):
            Optional default value or default parameter field; default None.
        ext (str):
            File name extension; default empty string.
        positive (bool):
            Flag specifying which boolean values are accepted.
            All values are accepted (if False), or only strictly positive values (if True); default False.
        valid (Optional[List[float]]):
            Optional list of valid values; default None.
        onefile (bool):
            Flag indicating whether parameters are read from one file.
            One file should be used for all bank lines (True) or one file per bank line (False; default).

    Raises:
        Exception:
            If a parameter isn't provided in the configuration, but no default value provided either.
            If the value is negative while a positive value is required (positive = True).
            If the value doesn't match one of the value values (valid is not None).

    Returns:
        List[np.ndarray]: Parameter field
            For each bank a parameter value per bank point (bank chainage location).

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> bank_km = [np.array([0, 1, 2]), np.array([3, 4, 5, 6, 7])]
        >>> num_stations_per_bank = [len(bank) for bank in bank_km]
        >>> config_file.get_parameter("General", "ZoomStepKM", num_stations_per_bank)
        [array([1., 1., 1.]), array([1., 1., 1., 1., 1.])]

        ```
    """
    try:
        value = self.config[group][key]
        use_default = False
    except (KeyError, TypeError) as e:
        value = None
        if default is None:
            raise ConfigFileError(
                f'No value specified for required keyword "{key}" in block "{group}".'
            ) from e
        use_default = True

    return self.process_parameter(
        value=value,
        key=key,
        num_stations_per_bank=num_stations_per_bank,
        use_default=use_default,
        default=default,
        ext=ext,
        positive=positive,
        valid=valid,
        onefile=onefile,
    )

get_plotting_flags(root_dir: Path | str) -> Dict[str, bool] #

Get the plotting flags from the configuration file.

Returns:

Name Type Description
data Dict[str, bool]

Dictionary containing the plotting flags. save_plot (bool): Flag indicating whether to save the plot. save_plot_zoomed (bool): Flag indicating whether to save the zoomed plot. zoom_km_step (float): Step size for zooming in on the plot. close_plot (bool): Flag indicating whether to close the plot.

Source code in src/dfastbe/io/config.py
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
def get_plotting_flags(self, root_dir: Path | str) -> Dict[str, bool]:
    """Get the plotting flags from the configuration file.

    Returns:
        data (Dict[str, bool]):
            Dictionary containing the plotting flags.
            save_plot (bool): Flag indicating whether to save the plot.
            save_plot_zoomed (bool): Flag indicating whether to save the zoomed plot.
            zoom_km_step (float): Step size for zooming in on the plot.
            close_plot (bool): Flag indicating whether to close the plot.
    """
    plot_data = self.get_bool("General", "Plotting", True)

    if plot_data:
        save_plot = self.get_bool("General", "SavePlots", True)
        save_plot_zoomed = self.get_bool("General", "SaveZoomPlots", True)
        zoom_km_step = self.get_float("General", "ZoomStepKM", 1.0)
        if zoom_km_step < 0.01:
            save_plot_zoomed = False
        close_plot = self.get_bool("General", "ClosePlots", False)
    else:
        save_plot = False
        save_plot_zoomed = False
        close_plot = False

    data = {
        "plot_data": plot_data,
        "save_plot": save_plot,
        "save_plot_zoomed": save_plot_zoomed,
        "zoom_km_step": zoom_km_step,
        "close_plot": close_plot,
    }

    # as appropriate, check output dir for figures and file format
    if save_plot:
        fig_dir = self.get_str("General", "FigureDir", Path(root_dir) / "figure")
        log_text("figure_dir", data={"dir": fig_dir})
        path_fig_dir = Path(fig_dir)
        if path_fig_dir.exists():
            log_text("overwrite_dir", data={"dir": fig_dir})
        path_fig_dir.mkdir(parents=True, exist_ok=True)
        plot_ext = self.get_str("General", "FigureExt", ".png")
        data = data | {
            "fig_dir": fig_dir,
            "plot_ext": plot_ext,
        }

    return data

get_range(group: str, key: str) -> Tuple[float, float] #

Get a start and end value from a selected group and keyword in the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group from which to read.

required
key str

Name of the keyword from which to read.

required

Returns:

Type Description
Tuple[float, float]

Tuple[float,float]: Lower and upper limit of the range.

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.get_range("General", "Boundaries")
(123.0, 128.0)
Source code in src/dfastbe/io/config.py
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
def get_range(self, group: str, key: str) -> Tuple[float, float]:
    """Get a start and end value from a selected group and keyword in the analysis settings.

    Args:
        group (str): Name of the group from which to read.
        key (str): Name of the keyword from which to read.

    Returns:
        Tuple[float,float]: Lower and upper limit of the range.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.get_range("General", "Boundaries")
        (123.0, 128.0)

        ```
    """
    str_val = self.get_str(group, key)
    try:
        obrack = str_val.find("[")
        cbrack = str_val.find("]")
        if obrack >= 0 and cbrack >= 0:
            str_val = str_val[obrack + 1 : cbrack - 1]
        val_list = [float(fstr) for fstr in str_val.split(":")]
        if val_list[0] > val_list[1]:
            val = (val_list[1], val_list[0])
        else:
            val = (val_list[0], val_list[1])
    except ValueError as e:
        raise ValueError(
            f'Invalid range specification "{str_val}" for required keyword "{key}" in block "{group}".'
        ) from e
    return val

get_river_center_line() -> LineString #

Get the river center line from the xyc file as a linestring.

Returns:

Name Type Description
LineString LineString

Chainage line.

Source code in src/dfastbe/io/config.py
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def get_river_center_line(self) -> LineString:
    """Get the river center line from the xyc file as a linestring.

    Returns:
        LineString: Chainage line.
    """
    # get the chainage file
    river_center_line_file = self.get_str("General", "RiverKM")
    log_text("read_chainage", data={"file": river_center_line_file})
    river_center_line = XYCModel.read(river_center_line_file, num_columns=3)

    # make sure that chainage is increasing with node index
    if river_center_line.coords[0][2] > river_center_line.coords[1][2]:
        river_center_line = LineString(river_center_line.coords[::-1])

    return river_center_line

get_search_lines() -> List[LineString] #

Get the search lines for the bank lines from the analysis settings.

Returns:

Type Description
List[LineString]

List[np.ndarray]: List of arrays containing the x,y-coordinates of a bank search lines.

Source code in src/dfastbe/io/config.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def get_search_lines(self) -> List[LineString]:
    """Get the search lines for the bank lines from the analysis settings.

    Returns:
        List[np.ndarray]: List of arrays containing the x,y-coordinates of a bank search lines.
    """
    # read guiding bank line
    n_bank = self.get_int("Detect", "NBank")
    line = []
    for b in range(n_bank):
        bankfile = self.config["Detect"][f"Line{b + 1}"]
        log_text("read_search_line", data={"nr": b + 1, "file": bankfile})
        line.append(XYCModel.read(bankfile))
    return line

get_sim_file(group: str, istr: str) -> str #

Get the name of the simulation file from the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group in which to search for the simulation file name.

required
istr str

Postfix for the simulation file name keyword; typically a string representation of the index.

required

Returns:

Name Type Description
str str

Name of the simulation file (empty string if keywords are not found).

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> result = config_file.get_sim_file("Erosion", "1")
>>> expected = Path("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc").resolve()
>>> str(expected) == result
True
Source code in src/dfastbe/io/config.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def get_sim_file(self, group: str, istr: str) -> str:
    """Get the name of the simulation file from the analysis settings.

    Args:
        group (str): Name of the group in which to search for the simulation file name.
        istr (str): Postfix for the simulation file name keyword;
            typically a string representation of the index.

    Returns:
        str: Name of the simulation file (empty string if keywords are not found).

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> result = config_file.get_sim_file("Erosion", "1")
        >>> expected = Path("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc").resolve()
        >>> str(expected) == result
        True

        ```
    """
    sim_file = self.config[group].get(f"SimFile{istr}", "")
    return sim_file

get_start_end_stations() -> Tuple[float, float] #

Get the start and end station for the river.

Returns:

Type Description
Tuple[float, float]

Tuple[float, float]: start and end station.

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.get_start_end_stations()
(123.0, 128.0)
Source code in src/dfastbe/io/config.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
def get_start_end_stations(self) -> Tuple[float, float]:
    """Get the start and end station for the river.

    Returns:
        Tuple[float, float]: start and end station.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.get_start_end_stations()
        (123.0, 128.0)

        ```
    """
    stations = self.get_range("General", "Boundaries")

    return stations

get_str(group: str, key: str, default: Optional[str] = None) -> str #

Get a string from a selected group and keyword in the analysis settings.

Parameters:

Name Type Description Default
group str

Name of the group from which to read.

required
key str

Name of the keyword from which to read.

required
default Optional[str]

Optional default value.

None

Raises:

Type Description
ConfigFileError

If the keyword isn't specified and no default value is given.

Returns:

Name Type Description
str str

value of the keyword as string.

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> result = config_file.get_str("General", "BankDir")
>>> expected = Path("tests/data/erosion/output/banklines").resolve()
>>> str(expected) == result
True
Source code in src/dfastbe/io/config.py
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
def get_str(
    self,
    group: str,
    key: str,
    default: Optional[str] = None,
) -> str:
    """Get a string from a selected group and keyword in the analysis settings.

    Args:
        group (str): Name of the group from which to read.
        key (str): Name of the keyword from which to read.
        default (Optional[str]): Optional default value.

    Raises:
        ConfigFileError: If the keyword isn't specified and no default value is given.

    Returns:
        str: value of the keyword as string.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> result = config_file.get_str("General", "BankDir")
        >>> expected = Path("tests/data/erosion/output/banklines").resolve()
        >>> str(expected) == result
        True

        ```
    """
    try:
        val = self.config[group][key]
    except KeyError as e:
        if default is not None:
            val = default
        else:
            raise ConfigFileError(
                f"No value specified for required keyword {key} in block {group}."
            ) from e
    return val

make_paths_absolute() -> str #

Convert all relative paths in the configuration to absolute paths.

Returns:

Name Type Description
str str

Absolute path of the configuration file's root directory.

Source code in src/dfastbe/io/config.py
354
355
356
357
358
359
360
361
362
def make_paths_absolute(self) -> str:
    """Convert all relative paths in the configuration to absolute paths.

    Returns:
        str: Absolute path of the configuration file's root directory.
    """
    self.resolve(self.root_dir)

    return self.root_dir

parameter_relative_to(group: str, key: str, rootdir: str) #

Convert a parameter value to contain a relative path.

Determine whether the string represents a number. If not, try to convert to a relative path.

Parameters:

Name Type Description Default
group str

Name of the group in the configuration.

required
key str

Name of the key in the configuration.

required
rootdir str

The path to be used as base for the relative paths.

required

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.parameter_relative_to("General", "RiverKM", "tests/data/erosion")
Source code in src/dfastbe/io/config.py
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
def parameter_relative_to(self, group: str, key: str, rootdir: str):
    """Convert a parameter value to contain a relative path.

    Determine whether the string represents a number.
    If not, try to convert to a relative path.

    Args:
        group (str): Name of the group in the configuration.
        key (str): Name of the key in the configuration.
        rootdir (str): The path to be used as base for the relative paths.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.parameter_relative_to("General", "RiverKM", "tests/data/erosion")

        ```
    """
    if key in self.config[group]:
        val_str = self.config[group][key]

        try:
            float(val_str)
        except ValueError:
            self.config[group][key] = relative_path(rootdir, val_str)

process_parameter(value: Union[str, float], key: str, num_stations_per_bank: List[int], use_default: bool = False, default: Any = None, ext: str = '', positive: bool = False, valid: Optional[List[float]] = None, onefile: bool = False) -> List[np.ndarray] #

Process a parameter value into arrays for each bank.

Parameters:

Name Type Description Default
value Union[str, float]

The parameter value or a path to a file.

required
key str

Name of the parameter for error messages.

required
num_stations_per_bank List[int]

Number of stations for each bank.

required
use_default bool

Whether to use the default value.

False
default Optional[float], default=None

Default value used if use_default is True.

None
ext str, default=''

File name extension.

''
positive bool, default=False

If True, only positive values are allowed.

False
valid Optional[List[float]], default=None

List of valid values.

None
onefile bool, default=False

If True, parameters are read from a single file for all banks; otherwise, one file per bank.

False

Returns:

Type Description
List[ndarray]

List[np.ndarray]: Parameter values for each bank.

Source code in src/dfastbe/io/config.py
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
def process_parameter(
    self,
    value: Union[str, float],
    key: str,
    num_stations_per_bank: List[int],
    use_default: bool = False,
    default: Any = None,
    ext: str = "",
    positive: bool = False,
    valid: Optional[List[float]] = None,
    onefile: bool = False,
) -> List[np.ndarray]:
    """
    Process a parameter value into arrays for each bank.

    Args:
        value (Union[str, float]):
            The parameter value or a path to a file.
        key (str):
            Name of the parameter for error messages.
        num_stations_per_bank (List[int]):
            Number of stations for each bank.
        use_default (bool):
            Whether to use the default value.
        default (Optional[float], default=None):
            Default value used if `use_default` is True.
        ext (str, default=''):
            File name extension.
        positive (bool, default=False):
            If True, only positive values are allowed.
        valid (Optional[List[float]], default=None):
            List of valid values.
        onefile (bool, default=False):
            If True, parameters are read from a single file for all banks;
            otherwise, one file per bank.

    Returns:
        List[np.ndarray]: Parameter values for each bank.
    """
    # if val is value then use that value globally
    parameter_values = []
    try:
        if use_default:
            if isinstance(default, list):
                return default
            real_val = default
        else:
            real_val = float(value)
            self.validate_parameter_value(real_val, key, positive, valid)

        for num_stations in num_stations_per_bank:
            parameter_values.append(np.zeros(num_stations) + real_val)

    except (ValueError, TypeError):
        if onefile:
            log_text("read_param", data={"param": key, "file": value})
            km_thr, val = _get_stations(value, key, positive)

        for ib, num_stations in enumerate(num_stations_per_bank):
            if not onefile:
                filename_i = f"{value}_{ib + 1}{ext}"
                log_text(
                    "read_param_one_bank",
                    data={"param": key, "i": ib + 1, "file": filename_i},
                )
                km_thr, val = _get_stations(filename_i, key, positive)

            if km_thr is None:
                parameter_values.append(np.zeros(num_stations) + val[0])
            else:
                idx = np.zeros(num_stations, dtype=int)

                for thr in km_thr:
                    idx[num_stations >= thr] += 1
                parameter_values.append(val[idx])

    return parameter_values

read(path: Union[str, Path]) -> ConfigFile classmethod #

Read a configParser object (configuration file).

Reads the config file using the standard configparser. Falls back to a dedicated reader compatible with old waqbank files.

Parameters:

Name Type Description Default
path Union[str, Path]

Path to the configuration file.

required

Returns:

Name Type Description
ConfigFile ConfigFile

Settings for the D-FAST Bank Erosion analysis.

Raises:

Type Description
FileNotFoundError

If the configuration file does not exist.

Exception

If there is an error reading the config file.

Examples:

Read a config file:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")

Source code in src/dfastbe/io/config.py
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
@classmethod
def read(cls, path: Union[str, Path]) -> "ConfigFile":
    """Read a configParser object (configuration file).

    Reads the config file using the standard `configparser`. Falls back to a
    dedicated reader compatible with old waqbank files.

    Args:
        path (Union[str, Path]): Path to the configuration file.

    Returns:
        ConfigFile: Settings for the D-FAST Bank Erosion analysis.

    Raises:
        FileNotFoundError: If the configuration file does not exist.
        Exception: If there is an error reading the config file.

    Examples:
        Read a config file:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")

        ```
    """
    if not Path(path).exists():
        raise FileNotFoundError(f"The Config-File: {path} does not exist")

    try:
        config = ConfigParser(comment_prefixes="%")
        with open(path, "r") as configfile:
            config.read_file(configfile)
    except ConfigparserError as e:
        print(f"Error during reading the config file: {e}")
        config = cls.config_file_callback_parser(path)

    # if version != "1.0":
    config = cls._upgrade(config)
    return cls(config, path=path)

read_bank_lines(bank_dir: str) -> List[np.ndarray] | GeoDataFrame #

Get the bank lines from the detection step.

Parameters:

Name Type Description Default
bank_dir str

Name of directory in which the bank lines files are located.

required

Returns:

Type Description
List[ndarray] | GeoDataFrame

List[np.ndarray]: List of arrays containing the x,y-coordinates of a bank lines.

Source code in src/dfastbe/io/config.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def read_bank_lines(self, bank_dir: str) -> List[np.ndarray] | GeoDataFrame:
    """Get the bank lines from the detection step.

    Args:
        bank_dir (str): Name of directory in which the bank lines files are located.

    Returns:
        List[np.ndarray]: List of arrays containing the x,y-coordinates of a bank lines.
    """
    bank_name = self.get_str("General", "BankFile", "bankfile")
    bankfile = Path(bank_dir) / f"{bank_name}.shp"
    if bankfile.exists():
        log_text("read_banklines", data={"file": str(bankfile)})
        return gpd.read_file(bankfile)

    bankfile = Path(bank_dir) / f"{bank_name}_#.xyc"
    log_text("read_banklines", data={"file": str(bankfile)})
    bankline_list = []
    b = 1
    while True:
        xyc_file = Path(bank_dir) / f"{bank_name}_{b}.xyc"
        if not xyc_file.exists():
            break

        xy_bank = XYCModel.read(xyc_file)
        bankline_list.append(LineString(xy_bank))
        b += 1
    bankline_series = GeoSeries(bankline_list, crs=self.crs)
    banklines = GeoDataFrame(geometry=bankline_series)
    return banklines

relative_to(rootdir: str) -> None #

Convert a configuration object to contain relative paths (for saving).

Parameters:

Name Type Description Default
rootdir str

The path to be used as base for the relative paths.

required

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.relative_to("testing/data/erosion")
Source code in src/dfastbe/io/config.py
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
def relative_to(self, rootdir: str) -> None:
    """Convert a configuration object to contain relative paths (for saving).

    Args:
        rootdir (str): The path to be used as base for the relative paths.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.relative_to("testing/data/erosion")

        ```
    """
    if "General" in self.config:
        self.parameter_relative_to("General", "RiverKM", rootdir)
        self.parameter_relative_to("General", "BankDir", rootdir)
        self.parameter_relative_to("General", "FigureDir", rootdir)

    if "Detect" in self.config:
        self.parameter_relative_to("Detect", "SimFile", rootdir)

        i = 0
        while True:
            i = i + 1
            line_i = f"Line{i}"
            if line_i in self.config["Detect"]:
                self.parameter_relative_to("Detect", line_i, rootdir)
            else:
                break

    if "Erosion" in self.config:
        self.parameter_relative_to("Erosion", "RiverAxis", rootdir)
        self.parameter_relative_to("Erosion", "Fairway", rootdir)
        self.parameter_relative_to("Erosion", "OutputDir", rootdir)

        self.parameter_relative_to("Erosion", "ShipType", rootdir)
        self.parameter_relative_to("Erosion", "VShip", rootdir)
        self.parameter_relative_to("Erosion", "NShip", rootdir)
        self.parameter_relative_to("Erosion", "NWave", rootdir)
        self.parameter_relative_to("Erosion", "Draught", rootdir)
        self.parameter_relative_to("Erosion", "Wave0", rootdir)
        self.parameter_relative_to("Erosion", "Wave1", rootdir)

        self.parameter_relative_to("Erosion", "BankType", rootdir)
        self.parameter_relative_to("Erosion", "ProtectionLevel", rootdir)
        self.parameter_relative_to("Erosion", "Slope", rootdir)
        self.parameter_relative_to("Erosion", "Reed", rootdir)

        n_level = self.get_int("Erosion", "NLevel", default=0)
        for i in range(1, n_level + 1):
            self.parameter_relative_to("Erosion", f"SimFile{i}", rootdir)
            self.parameter_relative_to("Erosion", f"ShipType{i}", rootdir)
            self.parameter_relative_to("Erosion", f"VShip{i}", rootdir)
            self.parameter_relative_to("Erosion", f"NShip{i}", rootdir)
            self.parameter_relative_to("Erosion", f"NWave{i}", rootdir)
            self.parameter_relative_to("Erosion", f"Draught{i}", rootdir)
            self.parameter_relative_to("Erosion", f"Slope{i}", rootdir)
            self.parameter_relative_to("Erosion", f"Reed{i}", rootdir)

resolve(rootdir: str) #

Convert a configuration object to contain absolute paths (for editing).

Parameters:

Name Type Description Default
rootdir str

The path to be used as base for the absolute paths.

required

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.resolve("tests/data/erosion")
Source code in src/dfastbe/io/config.py
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
def resolve(self, rootdir: str):
    """Convert a configuration object to contain absolute paths (for editing).

    Args:
        rootdir (str): The path to be used as base for the absolute paths.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.resolve("tests/data/erosion")

        ```
    """
    if "General" in self.config:
        self.resolve_parameter("General", "RiverKM", rootdir)
        self.resolve_parameter("General", "BankDir", rootdir)
        self.resolve_parameter("General", "FigureDir", rootdir)

    if "Detect" in self.config:
        self.resolve_parameter("Detect", "SimFile", rootdir)
        i = 0
        while True:
            i = i + 1
            line_i = "Line" + str(i)
            if line_i in self.config["Detect"]:
                self.resolve_parameter("Detect", line_i, rootdir)
            else:
                break

    if "Erosion" in self.config:
        self.resolve_parameter("Erosion", "RiverAxis", rootdir)
        self.resolve_parameter("Erosion", "Fairway", rootdir)
        self.resolve_parameter("Erosion", "OutputDir", rootdir)

        self.resolve_parameter("Erosion", "ShipType", rootdir)
        self.resolve_parameter("Erosion", "VShip", rootdir)
        self.resolve_parameter("Erosion", "NShip", rootdir)
        self.resolve_parameter("Erosion", "NWave", rootdir)
        self.resolve_parameter("Erosion", "Draught", rootdir)
        self.resolve_parameter("Erosion", "Wave0", rootdir)
        self.resolve_parameter("Erosion", "Wave1", rootdir)

        self.resolve_parameter("Erosion", "BankType", rootdir)
        self.resolve_parameter("Erosion", "ProtectionLevel", rootdir)
        self.resolve_parameter("Erosion", "Slope", rootdir)
        self.resolve_parameter("Erosion", "Reed", rootdir)

        n_level = self.get_int("Erosion", "NLevel", default=0)
        for i in range(1, n_level + 1):
            self.resolve_parameter("Erosion", f"SimFile{i}", rootdir)
            self.resolve_parameter("Erosion", f"ShipType{i}", rootdir)
            self.resolve_parameter("Erosion", f"VShip{i}", rootdir)
            self.resolve_parameter("Erosion", f"NShip{i}", rootdir)
            self.resolve_parameter("Erosion", f"NWave{i}", rootdir)
            self.resolve_parameter("Erosion", f"Draught{i}", rootdir)
            self.resolve_parameter("Erosion", f"Slope{i}", rootdir)
            self.resolve_parameter("Erosion", f"Reed{i}", rootdir)

resolve_parameter(group: str, key: str, rootdir: str) #

Convert a parameter value to contain an absolute path.

Determine whether the string represents a number. If not, try to convert to an absolute path.

Parameters:

Name Type Description Default
group str

Name of the group in the configuration.

required
key str

Name of the key in the configuration.

required
rootdir str

The path to be used as base for the absolute paths.

required

Examples:

>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> config_file.resolve_parameter("General", "RiverKM", "tests/data/erosion")
Source code in src/dfastbe/io/config.py
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
def resolve_parameter(self, group: str, key: str, rootdir: str):
    """Convert a parameter value to contain an absolute path.

    Determine whether the string represents a number.
    If not, try to convert to an absolute path.

    Args:
        group (str): Name of the group in the configuration.
        key (str): Name of the key in the configuration.
        rootdir (str): The path to be used as base for the absolute paths.

    Examples:
        ```python
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> config_file.resolve_parameter("General", "RiverKM", "tests/data/erosion")

        ```
    """
    if key in self.config[group]:
        val_str = self.config[group][key]
        try:
            float(val_str)
        except ValueError:
            self.config[group][key] = absolute_path(rootdir, val_str)

validate_parameter_value(value: float, key: str, positive: bool = False, valid: Optional[List[float]] = None) -> float #

Validate a parameter value against constraints.

Parameters:

Name Type Description Default
value float

The parameter value to validate.

required
key str

Name of the parameter for error messages.

required
positive bool

Flag specifying whether all values are accepted (if False), or only positive values (if True); default False.

False
valid Optional[List[float]]

Optional list of valid values; default None.

None

Raises:

Type Description
ValueError

If the value doesn't meet the constraints.

Returns:

Name Type Description
float float

The validated parameter value.

Source code in src/dfastbe/io/config.py
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
def validate_parameter_value(
    self,
    value: float,
    key: str,
    positive: bool = False,
    valid: Optional[List[float]] = None,
) -> float:
    """Validate a parameter value against constraints.

    Args:
        value (float): The parameter value to validate.
        key (str): Name of the parameter for error messages.
        positive (bool): Flag specifying whether all values are accepted (if False),
            or only positive values (if True); default False.
        valid (Optional[List[float]]): Optional list of valid values; default None.

    Raises:
        ValueError: If the value doesn't meet the constraints.

    Returns:
        float: The validated parameter value.
    """
    if positive and value < 0:
        raise ValueError(f'Value of "{key}" should be positive, not {value}.')
    if valid is not None and valid.count(value) == 0:
        raise ValueError(f'Value of "{key}" should be in {valid}, not {value}.')
    return value

write(filename: str) -> None #

Pretty print a configParser object (configuration file) to file.

Pretty prints a configparser object to a file. Aligns the equal signs for all keyword/value pairs, adds a two-space indentation to all keyword lines, and adds an empty line before the start of a new block.

Parameters:

Name Type Description Default
filename str

Name of the configuration file to be written.

required

Examples:

>>> import tempfile
>>> from dfastbe.io.config import ConfigFile
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     config_file.write(f"{tmpdirname}/meuse_manual_out.cfg")
Source code in src/dfastbe/io/config.py
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
def write(self, filename: str) -> None:
    """Pretty print a configParser object (configuration file) to file.

    Pretty prints a `configparser` object to a file. Aligns the equal signs for
    all keyword/value pairs, adds a two-space indentation to all keyword lines,
    and adds an empty line before the start of a new block.

    Args:
        filename (str): Name of the configuration file to be written.

    Examples:
        ```python
        >>> import tempfile
        >>> from dfastbe.io.config import ConfigFile
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> with tempfile.TemporaryDirectory() as tmpdirname:
        ...     config_file.write(f"{tmpdirname}/meuse_manual_out.cfg")

        ```
    """
    sections = self.config.sections()
    max_length = 0
    for section in sections:
        options = self.config.options(section)
        max_length = max(max_length, *[len(option) for option in options])

    with open(filename, "w") as configfile:
        for index, section in enumerate(sections):
            if index > 0:
                configfile.write("\n")
            configfile.write(f"[{section}]\n")

            for option in self.config.options(section):
                configfile.write(
                    f"  {option:<{max_length}} = {self.config[section][option]}\n"
                )

ConfigFileError #

Bases: Exception

Custom exception for configuration file errors.

Source code in src/dfastbe/io/config.py
1306
1307
1308
1309
class ConfigFileError(Exception):
    """Custom exception for configuration file errors."""

    pass

SimulationFilesError #

Bases: Exception

Custom exception for configuration file errors.

Source code in src/dfastbe/io/config.py
1312
1313
1314
1315
class SimulationFilesError(Exception):
    """Custom exception for configuration file errors."""

    pass

get_bbox(coords: np.ndarray, buffer: float = 0.1) -> Tuple[float, float, float, float] #

Derive the bounding box from a line.

Parameters:

Name Type Description Default
coords ndarray

An N x M array containing x- and y-coordinates as first two M entries

required
buffer

float Buffer fraction surrounding the tight bounding box

0.1

Returns:

Name Type Description
bbox Tuple[float, float, float, float]

Tuple bounding box consisting of [min x, min y, max x, max y)

Source code in src/dfastbe/io/config.py
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
def get_bbox(
    coords: np.ndarray, buffer: float = 0.1
) -> Tuple[float, float, float, float]:
    """
    Derive the bounding box from a line.

    Args:
        coords (np.ndarray):
            An N x M array containing x- and y-coordinates as first two M entries
        buffer : float
            Buffer fraction surrounding the tight bounding box

    Returns:
        bbox (Tuple[float, float, float, float]):
            Tuple bounding box consisting of [min x, min y, max x, max y)
    """
    x = coords[:, 0]
    y = coords[:, 1]
    x_min = x.min()
    y_min = y.min()
    x_max = x.max()
    y_max = y.max()
    d = buffer * max(x_max - x_min, y_max - y_min)
    bbox = (x_min - d, y_min - d, x_max + d, y_max + d)

    return bbox

The configuration component handles reading and parsing configuration files, which specify parameters for bank line detection and erosion calculation.

Data Models#

dfastbe.io.data_models #

Copyright (C) 2020 Stichting Deltares.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 2.1.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, see http://www.gnu.org/licenses/.

contact: delft3d.support@deltares.nl Stichting Deltares P.O. Box 177 2600 MH Delft, The Netherlands

All indications and logos of, and references to, "Delft3D" and "Deltares" are registered trademarks of Stichting Deltares, and remain the property of Stichting Deltares. All rights reserved.

INFORMATION This file is part of D-FAST Bank Erosion: https://github.com/Deltares/D-FAST_Bank_Erosion

BaseRiverData #

River data class.

Source code in src/dfastbe/io/data_models.py
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
class BaseRiverData:
    """River data class."""

    def __init__(self, config_file: ConfigFile):
        """River Data initialization.

        Args:
            config_file : ConfigFile
                Configuration file with settings for the analysis.

        Examples:
            ```python
            >>> from dfastbe.io.data_models import ConfigFile, BaseRiverData
            >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
            >>> river_data = BaseRiverData(config_file)
            No message found for read_chainage
            No message found for clip_chainage

            ```
        """
        self.config_file = config_file
        center_line = config_file.get_river_center_line()
        bounds = config_file.get_start_end_stations()
        self._river_center_line = LineGeometry(center_line, bounds, crs=config_file.crs)
        self._station_bounds: Tuple = config_file.get_start_end_stations()

    @property
    def river_center_line(self) -> LineGeometry:
        """LineGeometry: the clipped river center line."""
        return self._river_center_line

    @property
    def station_bounds(self) -> Tuple[float, float]:
        """Tuple: the lower and upper bounds of the river center line."""
        return self._station_bounds

    @staticmethod
    def get_bbox(
        coords: np.ndarray, buffer: float = 0.1
    ) -> Tuple[float, float, float, float]:
        """
        Derive the bounding box from an array of coordinates.

        Args:
            coords (np.ndarray):
                An N x M array containing x- and y-coordinates as first two M entries
            buffer : float
                Buffer fraction surrounding the tight bounding box

        Returns:
            bbox (Tuple[float, float, float, float]):
                Tuple bounding box consisting of [min x, min y, max x, max y)
        """
        return get_bbox(coords, buffer)

    def get_erosion_sim_data(self, num_discharge_levels: int) -> Tuple[List[str], List[float]]:
        # get pdischarges
        sim_files = []
        p_discharge = []
        for iq in range(num_discharge_levels):
            iq_str = str(iq + 1)
            sim_files.append(self.config_file.get_sim_file("Erosion", iq_str))
            p_discharge.append(
                self.config_file.get_float("Erosion", f"PDischarge{iq_str}")
            )
        return sim_files, p_discharge

river_center_line: LineGeometry property #

LineGeometry: the clipped river center line.

station_bounds: Tuple[float, float] property #

Tuple: the lower and upper bounds of the river center line.

__init__(config_file: ConfigFile) #

River Data initialization.

Parameters:

Name Type Description Default
config_file

ConfigFile Configuration file with settings for the analysis.

required

Examples:

>>> from dfastbe.io.data_models import ConfigFile, BaseRiverData
>>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
>>> river_data = BaseRiverData(config_file)
No message found for read_chainage
No message found for clip_chainage
Source code in src/dfastbe/io/data_models.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def __init__(self, config_file: ConfigFile):
    """River Data initialization.

    Args:
        config_file : ConfigFile
            Configuration file with settings for the analysis.

    Examples:
        ```python
        >>> from dfastbe.io.data_models import ConfigFile, BaseRiverData
        >>> config_file = ConfigFile.read("tests/data/erosion/meuse_manual.cfg")
        >>> river_data = BaseRiverData(config_file)
        No message found for read_chainage
        No message found for clip_chainage

        ```
    """
    self.config_file = config_file
    center_line = config_file.get_river_center_line()
    bounds = config_file.get_start_end_stations()
    self._river_center_line = LineGeometry(center_line, bounds, crs=config_file.crs)
    self._station_bounds: Tuple = config_file.get_start_end_stations()

get_bbox(coords: np.ndarray, buffer: float = 0.1) -> Tuple[float, float, float, float] staticmethod #

Derive the bounding box from an array of coordinates.

Parameters:

Name Type Description Default
coords ndarray

An N x M array containing x- and y-coordinates as first two M entries

required
buffer

float Buffer fraction surrounding the tight bounding box

0.1

Returns:

Name Type Description
bbox Tuple[float, float, float, float]

Tuple bounding box consisting of [min x, min y, max x, max y)

Source code in src/dfastbe/io/data_models.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
@staticmethod
def get_bbox(
    coords: np.ndarray, buffer: float = 0.1
) -> Tuple[float, float, float, float]:
    """
    Derive the bounding box from an array of coordinates.

    Args:
        coords (np.ndarray):
            An N x M array containing x- and y-coordinates as first two M entries
        buffer : float
            Buffer fraction surrounding the tight bounding box

    Returns:
        bbox (Tuple[float, float, float, float]):
            Tuple bounding box consisting of [min x, min y, max x, max y)
    """
    return get_bbox(coords, buffer)

BaseSimulationData #

Class to hold simulation data.

This class contains the simulation data read from a UGRID netCDF file. It includes methods to read the data from the file and clip the simulation mesh to a specified area of interest.

Source code in src/dfastbe/io/data_models.py
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
class BaseSimulationData:
    """Class to hold simulation data.

    This class contains the simulation data read from a UGRID netCDF file.
    It includes methods to read the data from the file and clip the simulation
    mesh to a specified area of interest.
    """

    def __init__(
        self,
        x_node: np.ndarray,
        y_node: np.ndarray,
        n_nodes: np.ndarray,
        face_node: np.ma.masked_array,
        bed_elevation_location: np.ndarray,
        bed_elevation_values: np.ndarray,
        water_level_face: np.ndarray,
        water_depth_face: np.ndarray,
        velocity_x_face: np.ndarray,
        velocity_y_face: np.ndarray,
        chezy_face: np.ndarray,
        dry_wet_threshold: float,
    ):
        """
        Initialize the SimulationData object.

        Args:
        x_node (np.ndarray):
            X-coordinates of the nodes.
        y_node (np.ndarray):
            Y-coordinates of the nodes.
        n_nodes (np.ndarray):
            Number of nodes in each face.
        face_node (np.ma.masked_array):
            Face-node connectivity array.
        bed_elevation_location (np.ndarray):
            Determines whether the bed elevation is associated with nodes
            or faces in the computational mesh.
        bed_elevation_values (np.ndarray):
            Bed elevation values for each node in the simulation data.
        water_level_face (np.ndarray):
            Water levels at the faces.
        water_depth_face (np.ndarray):
            Water depths at the faces.
        velocity_x_face (np.ndarray):
            X-component of the velocity at the faces.
        velocity_y_face (np.ndarray):
            Y-component of the velocity at the faces.
        chezy_face (np.ndarray):
            Chezy roughness values at the faces.
        dry_wet_threshold (float):
            Threshold depth for detecting drying and flooding.
        """
        self.x_node = x_node
        self.y_node = y_node
        self.n_nodes = n_nodes
        self.face_node = face_node
        self.bed_elevation_location = bed_elevation_location
        self.bed_elevation_values = bed_elevation_values
        self.water_level_face = water_level_face
        self.water_depth_face = water_depth_face
        self.velocity_x_face = velocity_x_face
        self.velocity_y_face = velocity_y_face
        self.chezy_face = chezy_face
        self.dry_wet_threshold = dry_wet_threshold

    @classmethod
    def read(cls, file_name: str, indent: str = "") -> "BaseSimulationData":
        """Read a default set of quantities from a UGRID netCDF file.

        Supported files are coming from D-Flow FM (or similar).

        Args:
            file_name (str):
                Name of the simulation output file to be read.
            indent (str):
                String to use for each line as indentation (default empty).

        Raises:
            SimulationFilesError:
                If the file is not recognized as a D-Flow FM map-file.

        Returns:
            BaseSimulationData (Tuple[BaseSimulationData, float]):
                Dictionary containing the data read from the simulation output file.

        Examples:
            ```python
            >>> from dfastbe.io.data_models import BaseSimulationData
            >>> sim_data = BaseSimulationData.read("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc") # doctest: +ELLIPSIS
            No message ... read_drywet
            >>> print(sim_data.x_node[0:3])
            [194949.796875 194966.515625 194982.8125  ]

            ```
        """
        name = Path(file_name).name
        if name.endswith("map.nc"):
            log_text("read_grid", indent=indent)
            x_node = _read_fm_map(file_name, "x", location="node")
            y_node = _read_fm_map(file_name, "y", location="node")
            f_nc = _read_fm_map(file_name, "face_node_connectivity")
            if f_nc.mask.shape == ():
                # all faces have the same number of nodes
                n_nodes = np.ones(f_nc.data.shape[0], dtype=int) * f_nc.data.shape[1]
            else:
                # varying number of nodes
                n_nodes = f_nc.mask.shape[1] - f_nc.mask.sum(axis=1)
            f_nc.data[f_nc.mask] = 0

            face_node = f_nc
            log_text("read_bathymetry", indent=indent)
            bed_elevation_location = "node"
            bed_elevation_values = _read_fm_map(file_name, "altitude", location="node")
            log_text("read_water_level", indent=indent)
            water_level_face = _read_fm_map(file_name, "Water level")
            log_text("read_water_depth", indent=indent)
            water_depth_face = np.maximum(
                _read_fm_map(file_name, "sea_floor_depth_below_sea_surface"), 0.0
            )
            log_text("read_velocity", indent=indent)
            velocity_x_face = _read_fm_map(file_name, "sea_water_x_velocity")
            velocity_y_face = _read_fm_map(file_name, "sea_water_y_velocity")
            log_text("read_chezy", indent=indent)
            chezy_face = _read_fm_map(file_name, "Chezy roughness")

            log_text("read_drywet", indent=indent)
            root_group = netCDF4.Dataset(file_name)
            try:
                file_source = root_group.converted_from
                if file_source == "SIMONA":
                    dry_wet_threshold = 0.1
                else:
                    dry_wet_threshold = 0.01
            except AttributeError:
                dry_wet_threshold = 0.01

        elif name.startswith("SDS"):
            raise SimulationFilesError(
                f"WAQUA output files not yet supported. Unable to process {name}"
            )
        elif name.startswith("trim"):
            raise SimulationFilesError(
                f"Delft3D map files not yet supported. Unable to process {name}"
            )
        else:
            raise SimulationFilesError(f"Unable to determine file type for {name}")

        return cls(
            x_node=x_node,
            y_node=y_node,
            n_nodes=n_nodes,
            face_node=face_node,
            bed_elevation_location=bed_elevation_location,
            bed_elevation_values=bed_elevation_values,
            water_level_face=water_level_face,
            water_depth_face=water_depth_face,
            velocity_x_face=velocity_x_face,
            velocity_y_face=velocity_y_face,
            chezy_face=chezy_face,
            dry_wet_threshold=dry_wet_threshold,
        )

    def clip(self, river_center_line: LineString, max_distance: float):
        """Clip the simulation mesh.

        Clipping data to the area of interest,
        that is sufficiently close to the reference line.

        Args:
            river_center_line (np.ndarray):
                Reference line.
            max_distance (float):
                Maximum distance between the reference line and a point in the area of
                interest defined based on the search lines for the banks and the search
                distance.

        Notes:
            The function uses the Shapely library to create a buffer around the river
            profile and checks if the nodes are within that buffer. If they are not,
            they are removed from the simulation data.

        Examples:
            ```python
            >>> from dfastbe.io.data_models import BaseSimulationData
            >>> sim_data = BaseSimulationData.read("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc")
            No message found for read_grid
            No message found for read_bathymetry
            No message found for read_water_level
            No message found for read_water_depth
            No message found for read_velocity
            No message found for read_chezy
            No message found for read_drywet
            >>> river_center_line = LineString([
            ...     [194949.796875, 361366.90625],
            ...     [194966.515625, 361399.46875],
            ...     [194982.8125, 361431.03125]
            ... ])
            >>> max_distance = 10.0
            >>> sim_data.clip(river_center_line, max_distance)
            >>> print(sim_data.x_node)
            [194949.796875 194966.515625 194982.8125  ]

            ```
        """
        xy_buffer = river_center_line.buffer(max_distance + max_distance)
        bbox = xy_buffer.envelope.exterior
        x_min = bbox.coords[0][0]
        x_max = bbox.coords[1][0]
        y_min = bbox.coords[0][1]
        y_max = bbox.coords[2][1]

        prepare(xy_buffer)
        x = self.x_node
        y = self.y_node
        nnodes = x.shape
        keep = (x > x_min) & (x < x_max) & (y > y_min) & (y < y_max)
        for i in range(x.size):
            if keep[i] and not xy_buffer.contains(Point((x[i], y[i]))):
                keep[i] = False

        fnc = self.face_node
        keep_face = keep[fnc].all(axis=1)
        renum = np.zeros(nnodes, dtype=int)
        renum[keep] = range(sum(keep))
        self.face_node = renum[fnc[keep_face]]

        self.x_node = x[keep]
        self.y_node = y[keep]
        if self.bed_elevation_location == "node":
            self.bed_elevation_values = self.bed_elevation_values[keep]
        else:
            self.bed_elevation_values = self.bed_elevation_values[keep_face]

        self.n_nodes = self.n_nodes[keep_face]
        self.water_level_face = self.water_level_face[keep_face]
        self.water_depth_face = self.water_depth_face[keep_face]
        self.velocity_x_face = self.velocity_x_face[keep_face]
        self.velocity_y_face = self.velocity_y_face[keep_face]
        self.chezy_face = self.chezy_face[keep_face]

__init__(x_node: np.ndarray, y_node: np.ndarray, n_nodes: np.ndarray, face_node: np.ma.masked_array, bed_elevation_location: np.ndarray, bed_elevation_values: np.ndarray, water_level_face: np.ndarray, water_depth_face: np.ndarray, velocity_x_face: np.ndarray, velocity_y_face: np.ndarray, chezy_face: np.ndarray, dry_wet_threshold: float) #

Initialize the SimulationData object.

x_node (np.ndarray): X-coordinates of the nodes. y_node (np.ndarray): Y-coordinates of the nodes. n_nodes (np.ndarray): Number of nodes in each face. face_node (np.ma.masked_array): Face-node connectivity array. bed_elevation_location (np.ndarray): Determines whether the bed elevation is associated with nodes or faces in the computational mesh. bed_elevation_values (np.ndarray): Bed elevation values for each node in the simulation data. water_level_face (np.ndarray): Water levels at the faces. water_depth_face (np.ndarray): Water depths at the faces. velocity_x_face (np.ndarray): X-component of the velocity at the faces. velocity_y_face (np.ndarray): Y-component of the velocity at the faces. chezy_face (np.ndarray): Chezy roughness values at the faces. dry_wet_threshold (float): Threshold depth for detecting drying and flooding.

Source code in src/dfastbe/io/data_models.py
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
def __init__(
    self,
    x_node: np.ndarray,
    y_node: np.ndarray,
    n_nodes: np.ndarray,
    face_node: np.ma.masked_array,
    bed_elevation_location: np.ndarray,
    bed_elevation_values: np.ndarray,
    water_level_face: np.ndarray,
    water_depth_face: np.ndarray,
    velocity_x_face: np.ndarray,
    velocity_y_face: np.ndarray,
    chezy_face: np.ndarray,
    dry_wet_threshold: float,
):
    """
    Initialize the SimulationData object.

    Args:
    x_node (np.ndarray):
        X-coordinates of the nodes.
    y_node (np.ndarray):
        Y-coordinates of the nodes.
    n_nodes (np.ndarray):
        Number of nodes in each face.
    face_node (np.ma.masked_array):
        Face-node connectivity array.
    bed_elevation_location (np.ndarray):
        Determines whether the bed elevation is associated with nodes
        or faces in the computational mesh.
    bed_elevation_values (np.ndarray):
        Bed elevation values for each node in the simulation data.
    water_level_face (np.ndarray):
        Water levels at the faces.
    water_depth_face (np.ndarray):
        Water depths at the faces.
    velocity_x_face (np.ndarray):
        X-component of the velocity at the faces.
    velocity_y_face (np.ndarray):
        Y-component of the velocity at the faces.
    chezy_face (np.ndarray):
        Chezy roughness values at the faces.
    dry_wet_threshold (float):
        Threshold depth for detecting drying and flooding.
    """
    self.x_node = x_node
    self.y_node = y_node
    self.n_nodes = n_nodes
    self.face_node = face_node
    self.bed_elevation_location = bed_elevation_location
    self.bed_elevation_values = bed_elevation_values
    self.water_level_face = water_level_face
    self.water_depth_face = water_depth_face
    self.velocity_x_face = velocity_x_face
    self.velocity_y_face = velocity_y_face
    self.chezy_face = chezy_face
    self.dry_wet_threshold = dry_wet_threshold

clip(river_center_line: LineString, max_distance: float) #

Clip the simulation mesh.

Clipping data to the area of interest, that is sufficiently close to the reference line.

Parameters:

Name Type Description Default
river_center_line ndarray

Reference line.

required
max_distance float

Maximum distance between the reference line and a point in the area of interest defined based on the search lines for the banks and the search distance.

required
Notes

The function uses the Shapely library to create a buffer around the river profile and checks if the nodes are within that buffer. If they are not, they are removed from the simulation data.

Examples:

>>> from dfastbe.io.data_models import BaseSimulationData
>>> sim_data = BaseSimulationData.read("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc")
No message found for read_grid
No message found for read_bathymetry
No message found for read_water_level
No message found for read_water_depth
No message found for read_velocity
No message found for read_chezy
No message found for read_drywet
>>> river_center_line = LineString([
...     [194949.796875, 361366.90625],
...     [194966.515625, 361399.46875],
...     [194982.8125, 361431.03125]
... ])
>>> max_distance = 10.0
>>> sim_data.clip(river_center_line, max_distance)
>>> print(sim_data.x_node)
[194949.796875 194966.515625 194982.8125  ]
Source code in src/dfastbe/io/data_models.py
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
def clip(self, river_center_line: LineString, max_distance: float):
    """Clip the simulation mesh.

    Clipping data to the area of interest,
    that is sufficiently close to the reference line.

    Args:
        river_center_line (np.ndarray):
            Reference line.
        max_distance (float):
            Maximum distance between the reference line and a point in the area of
            interest defined based on the search lines for the banks and the search
            distance.

    Notes:
        The function uses the Shapely library to create a buffer around the river
        profile and checks if the nodes are within that buffer. If they are not,
        they are removed from the simulation data.

    Examples:
        ```python
        >>> from dfastbe.io.data_models import BaseSimulationData
        >>> sim_data = BaseSimulationData.read("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc")
        No message found for read_grid
        No message found for read_bathymetry
        No message found for read_water_level
        No message found for read_water_depth
        No message found for read_velocity
        No message found for read_chezy
        No message found for read_drywet
        >>> river_center_line = LineString([
        ...     [194949.796875, 361366.90625],
        ...     [194966.515625, 361399.46875],
        ...     [194982.8125, 361431.03125]
        ... ])
        >>> max_distance = 10.0
        >>> sim_data.clip(river_center_line, max_distance)
        >>> print(sim_data.x_node)
        [194949.796875 194966.515625 194982.8125  ]

        ```
    """
    xy_buffer = river_center_line.buffer(max_distance + max_distance)
    bbox = xy_buffer.envelope.exterior
    x_min = bbox.coords[0][0]
    x_max = bbox.coords[1][0]
    y_min = bbox.coords[0][1]
    y_max = bbox.coords[2][1]

    prepare(xy_buffer)
    x = self.x_node
    y = self.y_node
    nnodes = x.shape
    keep = (x > x_min) & (x < x_max) & (y > y_min) & (y < y_max)
    for i in range(x.size):
        if keep[i] and not xy_buffer.contains(Point((x[i], y[i]))):
            keep[i] = False

    fnc = self.face_node
    keep_face = keep[fnc].all(axis=1)
    renum = np.zeros(nnodes, dtype=int)
    renum[keep] = range(sum(keep))
    self.face_node = renum[fnc[keep_face]]

    self.x_node = x[keep]
    self.y_node = y[keep]
    if self.bed_elevation_location == "node":
        self.bed_elevation_values = self.bed_elevation_values[keep]
    else:
        self.bed_elevation_values = self.bed_elevation_values[keep_face]

    self.n_nodes = self.n_nodes[keep_face]
    self.water_level_face = self.water_level_face[keep_face]
    self.water_depth_face = self.water_depth_face[keep_face]
    self.velocity_x_face = self.velocity_x_face[keep_face]
    self.velocity_y_face = self.velocity_y_face[keep_face]
    self.chezy_face = self.chezy_face[keep_face]

read(file_name: str, indent: str = '') -> BaseSimulationData classmethod #

Read a default set of quantities from a UGRID netCDF file.

Supported files are coming from D-Flow FM (or similar).

Parameters:

Name Type Description Default
file_name str

Name of the simulation output file to be read.

required
indent str

String to use for each line as indentation (default empty).

''

Raises:

Type Description
SimulationFilesError

If the file is not recognized as a D-Flow FM map-file.

Returns:

Name Type Description
BaseSimulationData Tuple[BaseSimulationData, float]

Dictionary containing the data read from the simulation output file.

Examples:

>>> from dfastbe.io.data_models import BaseSimulationData
>>> sim_data = BaseSimulationData.read("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc") # doctest: +ELLIPSIS
No message ... read_drywet
>>> print(sim_data.x_node[0:3])
[194949.796875 194966.515625 194982.8125  ]
Source code in src/dfastbe/io/data_models.py
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
@classmethod
def read(cls, file_name: str, indent: str = "") -> "BaseSimulationData":
    """Read a default set of quantities from a UGRID netCDF file.

    Supported files are coming from D-Flow FM (or similar).

    Args:
        file_name (str):
            Name of the simulation output file to be read.
        indent (str):
            String to use for each line as indentation (default empty).

    Raises:
        SimulationFilesError:
            If the file is not recognized as a D-Flow FM map-file.

    Returns:
        BaseSimulationData (Tuple[BaseSimulationData, float]):
            Dictionary containing the data read from the simulation output file.

    Examples:
        ```python
        >>> from dfastbe.io.data_models import BaseSimulationData
        >>> sim_data = BaseSimulationData.read("tests/data/erosion/inputs/sim0075/SDS-j19_map.nc") # doctest: +ELLIPSIS
        No message ... read_drywet
        >>> print(sim_data.x_node[0:3])
        [194949.796875 194966.515625 194982.8125  ]

        ```
    """
    name = Path(file_name).name
    if name.endswith("map.nc"):
        log_text("read_grid", indent=indent)
        x_node = _read_fm_map(file_name, "x", location="node")
        y_node = _read_fm_map(file_name, "y", location="node")
        f_nc = _read_fm_map(file_name, "face_node_connectivity")
        if f_nc.mask.shape == ():
            # all faces have the same number of nodes
            n_nodes = np.ones(f_nc.data.shape[0], dtype=int) * f_nc.data.shape[1]
        else:
            # varying number of nodes
            n_nodes = f_nc.mask.shape[1] - f_nc.mask.sum(axis=1)
        f_nc.data[f_nc.mask] = 0

        face_node = f_nc
        log_text("read_bathymetry", indent=indent)
        bed_elevation_location = "node"
        bed_elevation_values = _read_fm_map(file_name, "altitude", location="node")
        log_text("read_water_level", indent=indent)
        water_level_face = _read_fm_map(file_name, "Water level")
        log_text("read_water_depth", indent=indent)
        water_depth_face = np.maximum(
            _read_fm_map(file_name, "sea_floor_depth_below_sea_surface"), 0.0
        )
        log_text("read_velocity", indent=indent)
        velocity_x_face = _read_fm_map(file_name, "sea_water_x_velocity")
        velocity_y_face = _read_fm_map(file_name, "sea_water_y_velocity")
        log_text("read_chezy", indent=indent)
        chezy_face = _read_fm_map(file_name, "Chezy roughness")

        log_text("read_drywet", indent=indent)
        root_group = netCDF4.Dataset(file_name)
        try:
            file_source = root_group.converted_from
            if file_source == "SIMONA":
                dry_wet_threshold = 0.1
            else:
                dry_wet_threshold = 0.01
        except AttributeError:
            dry_wet_threshold = 0.01

    elif name.startswith("SDS"):
        raise SimulationFilesError(
            f"WAQUA output files not yet supported. Unable to process {name}"
        )
    elif name.startswith("trim"):
        raise SimulationFilesError(
            f"Delft3D map files not yet supported. Unable to process {name}"
        )
    else:
        raise SimulationFilesError(f"Unable to determine file type for {name}")

    return cls(
        x_node=x_node,
        y_node=y_node,
        n_nodes=n_nodes,
        face_node=face_node,
        bed_elevation_location=bed_elevation_location,
        bed_elevation_values=bed_elevation_values,
        water_level_face=water_level_face,
        water_depth_face=water_depth_face,
        velocity_x_face=velocity_x_face,
        velocity_y_face=velocity_y_face,
        chezy_face=chezy_face,
        dry_wet_threshold=dry_wet_threshold,
    )

LineGeometry #

Center line class.

Source code in src/dfastbe/io/data_models.py
 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
class LineGeometry:
    """Center line class."""

    def __init__(self, line: LineString | np.ndarray, mask: Tuple[float, float] = None, crs: str = None):
        """Geometry Line initialization.

        Args:
            line (LineString):
                River center line as a linestring.
            mask (Tuple[float, float], optional):
                Lower and upper limit for the chainage. Defaults to None.
            crs (str, Optional):
                the coordinate reference system number as a string.

        Examples:
            ```python
            >>> line_string = LineString([(0, 0, 0), (1, 1, 1), (2, 2, 2)])
            >>> mask = (0.5, 1.5)
            >>> center_line = LineGeometry(line_string, mask)
            No message found for clip_chainage
            >>> np.array(center_line.values.coords)
            array([[0.5, 0.5, 0.5],
                   [1. , 1. , 1. ],
                   [1.5, 1.5, 1.5]])

            ```
        """
        self.station_bounds = mask
        self.crs = crs
        self._data = {}
        if isinstance(line, np.ndarray):
            line = LineString(line)
        if mask is None:
            self.values = line
        else:
            self.values: LineString = self.mask(line, mask)

            log_text(
                "clip_chainage", data={"low": self.station_bounds[0], "high": self.station_bounds[1]}
            )

    @property
    def data(self) -> Dict[str, np.ndarray]:
        """any data assigned to the line using the `add_data` method."""
        return self._data

    def as_array(self) -> np.ndarray:
        return np.array(self.values.coords)

    def add_data(self, data: Dict[str, np.ndarray]) -> None:
        """
        Add data to the LineGeometry object.

        Args:
            data (Dict[str, np.ndarray]):
                Dictionary of quantities to be added, each np array should have length k.
        """
        self._data = self.data | data

    def to_file(
            self, file_name: str, data: Dict[str, np.ndarray] = None,
    ) -> None:
        """
        Write a shape point file with x, y, and values.

        Args:
            file_name : str
                Name of the file to be written.
            data : Dict[str, np.ndarray]
                Dictionary of quantities to be written, each np array should have length k.
        """
        xy = self.as_array()
        geom = [Point(xy_i) for xy_i in xy]
        if data is None:
            data = self.data
        else:
            data = data | self.data
        GeoDataFrame(data, geometry=geom, crs=self.crs).to_file(file_name)

    @staticmethod
    def mask(line_string: LineString, bounds: Tuple[float, float]) -> LineString:
        """Clip a LineGeometry to the relevant reach.

        Args:
            line_string (LineString):
                river center line as a linestring.
            bounds (Tuple[float, float]):
                Lower and upper limit for the chainage.

        Returns:
            LineString: Clipped river chainage line.

        Examples:
            ```python
            >>> line_string = LineString([(0, 0, 0), (1, 1, 1), (2, 2, 2)])
            >>> bounds = (0.5, 1.5)
            >>> center_line = LineGeometry.mask(line_string, bounds)
            >>> np.array(center_line.coords)
            array([[0.5, 0.5, 0.5],
                   [1. , 1. , 1. ],
                   [1.5, 1.5, 1.5]])

            ```
        """
        line_string_coords = line_string.coords
        start_index = LineGeometry._find_mask_index(bounds[0], line_string_coords)
        end_index = LineGeometry._find_mask_index(bounds[1], line_string_coords)
        lower_bound_point, start_index = LineGeometry._handle_bound(
            start_index, bounds[0], True, line_string_coords
        )
        upper_bound_point, end_index = LineGeometry._handle_bound(
            end_index, bounds[1], False, line_string_coords
        )

        if lower_bound_point is None and upper_bound_point is None:
            return line_string
        elif lower_bound_point is None:
            return LineString(line_string_coords[: end_index + 1] + [upper_bound_point])
        elif upper_bound_point is None:
            return LineString([lower_bound_point] + line_string_coords[start_index:])
        else:
            return LineString(
                [lower_bound_point]
                + line_string_coords[start_index:end_index]
                + [upper_bound_point]
            )

    @staticmethod
    def _find_mask_index(
            station_bound: float, line_string_coords: np.ndarray
    ) -> Optional[int]:
        """Find the start and end indices for clipping the chainage line.

        Args:
            station_bound (float):
                Station bound for clipping.
            line_string_coords (np.ndarray):
                Coordinates of the line string.

        Returns:
            Optional[int]: index for clipping.
        """
        mask_index = next(
            (
                index
                for index, coord in enumerate(line_string_coords)
                if coord[2] >= station_bound
            ),
            None,
        )
        return mask_index

    @staticmethod
    def _handle_bound(
            index: Optional[int],
            station_bound: float,
            is_lower: bool,
            line_string_coords: np.ndarray,
    ) -> Tuple[Optional[Tuple[float, float, float]], Optional[int]]:
        """Handle the clipping of the stations line for a given bound.

        Args:
            index (Optional[int]):
                Index for clipping (start or end).
            station_bound (float):
                Station bound for clipping.
            is_lower (bool):
                True if handling the lower bound, False for the upper bound.
            line_string_coords (np.ndarray):
                Coordinates of the line string.

        Returns:
            Tuple[Optional[Tuple[float, float, float]], Optional[int]]:
                Adjusted bound point and updated index.
        """
        if index is None:
            bound_type = "Lower" if is_lower else "Upper"
            end_station = line_string_coords[-1][2]
            if is_lower or (station_bound - end_station > 0.1):
                raise ValueError(
                    f"{bound_type} chainage bound {station_bound} "
                    f"is larger than the maximum chainage {end_station} available"
                )
            return None, index

        if index == 0:
            bound_type = "Lower" if is_lower else "Upper"
            start_station = line_string_coords[0][2]
            if not is_lower or (start_station - station_bound > 0.1):
                raise ValueError(
                    f"{bound_type} chainage bound {station_bound} "
                    f"is smaller than the minimum chainage {start_station} available"
                )
            return None, index

        # Interpolate the point
        alpha, interpolated_point = LineGeometry._interpolate_point(
            index, station_bound, line_string_coords
        )

        # Adjust the index based on the interpolation factor
        if is_lower and alpha > 0.9:
            index += 1
        elif not is_lower and alpha < 0.1:
            index -= 1

        return interpolated_point, index

    @staticmethod
    def _interpolate_point(
            index: int, station_bound: float, line_string_coords: np.ndarray
    ) -> Tuple[float, Tuple[float, float, float]]:
        """Interpolate a point between two coordinates.

        Args:
            index (int):
                Index of the coordinate to interpolate.
            station_bound (float):
                Station bound for interpolation.
            line_string_coords (np.ndarray):
                Coordinates of the line string.

        Returns:
            float: Interpolation factor.
            Tuple[float, float, float]: Interpolated point.
        """
        alpha = (station_bound - line_string_coords[index - 1][2]) / (
                line_string_coords[index][2] - line_string_coords[index - 1][2]
        )
        interpolated_point = tuple(
            prev_coord + alpha * (next_coord - prev_coord)
            for prev_coord, next_coord in zip(
                line_string_coords[index - 1], line_string_coords[index]
            )
        )
        return alpha, interpolated_point

    def intersect_with_line(
        self, reference_line_with_stations: np.ndarray
    ) -> np.ndarray:
        """
        Project chainage(stations) values from a reference line onto a target line by spatial proximity and interpolation.

        Project chainage values from source line L1 onto another line L2.

        The chainage values are giving along a line L1 (xykm_numpy). For each node
        of the line L2 (line_xy) on which we would like to know the chainage, first
        the closest node (discrete set of nodes) on L1 is determined and
        subsequently the exact chainage is obtained by determining the closest point
        (continuous line) on L1 for which the chainage is determined using by means
        of interpolation.

        Args:
            reference_line_with_stations (np.ndarray):
                Mx3 array with x, y, and chainage values for the reference line.

        Returns:
            line_km : np.ndarray
                Array containing the chainage for every coordinate specified in line_xy.
        """
        coords = self.as_array()
        # pre-allocates the array for the mapped chainage values
        projected_stations = np.zeros(coords.shape[0])

        # get an array with only the x,y coordinates of line L1
        ref_coords = reference_line_with_stations[:, :2]
        last_index = reference_line_with_stations.shape[0] - 1

        # for each node rp on line L2 get the chainage ...
        for i, station_i in enumerate(coords):
            # find the node on L1 closest to rp
            # get the distance to all the nodes on the reference line, and find the closest one
            closest_ind = np.argmin(((station_i - ref_coords) ** 2).sum(axis=1))
            closest_coords = ref_coords[closest_ind]

            # determine the distance between that node and rp
            squared_distance = ((station_i - closest_coords) ** 2).sum()

            # chainage value of that node
            station = reference_line_with_stations[closest_ind, 2]

            # if we didn't get the first node
            if closest_ind > 0:
                # project rp onto the line segment before this node
                closest_coord_minus_1 = ref_coords[closest_ind - 1]
                alpha = (
                                (closest_coord_minus_1[0] - closest_coords[0]) * (station_i[0] - closest_coords[0])
                                + (closest_coord_minus_1[1] - closest_coords[1]) * (station_i[1] - closest_coords[1])
                        ) / ((closest_coord_minus_1[0] - closest_coords[0]) ** 2 + (closest_coord_minus_1[1] - closest_coords[1]) ** 2)
                # if there is a closest point not coinciding with the nodes ...
                if 0 < alpha < 1:
                    dist2link = (station_i[0] - closest_coords[0] - alpha * (closest_coord_minus_1[0] - closest_coords[0])) ** 2 + (
                            station_i[1] - closest_coords[1] - alpha * (closest_coord_minus_1[1] - closest_coords[1])
                    ) ** 2
                    # if it's actually closer than the node ...
                    if dist2link < squared_distance:
                        # update the closest point information
                        squared_distance = dist2link
                        station = reference_line_with_stations[closest_ind, 2] + alpha * (
                                reference_line_with_stations[closest_ind - 1, 2] - reference_line_with_stations[closest_ind, 2]
                        )

            # if we didn't get the last node
            if closest_ind < last_index:
                # project rp onto the line segment after this node
                closest_coord_minus_1 = ref_coords[closest_ind + 1]
                alpha = (
                                (closest_coord_minus_1[0] - closest_coords[0]) * (station_i[0] - closest_coords[0])
                                + (closest_coord_minus_1[1] - closest_coords[1]) * (station_i[1] - closest_coords[1])
                        ) / ((closest_coord_minus_1[0] - closest_coords[0]) ** 2 + (closest_coord_minus_1[1] - closest_coords[1]) ** 2)
                # if there is a closest point not coinciding with the nodes ...
                if alpha > 0 and alpha < 1:
                    dist2link = (station_i[0] - closest_coords[0] - alpha * (closest_coord_minus_1[0] - closest_coords[0])) ** 2 + (
                            station_i[1] - closest_coords[1] - alpha * (closest_coord_minus_1[1] - closest_coords[1])
                    ) ** 2
                    # if it's actually closer than the previous value ...
                    if dist2link < squared_distance:
                        # update the closest point information
                        # squared_distance = dist2link
                        station = reference_line_with_stations[closest_ind, 2] + alpha * (
                                reference_line_with_stations[closest_ind + 1, 2] - reference_line_with_stations[closest_ind, 2]
                        )
            # store the chainage value, loop ... and return
            projected_stations[i] = station
        return projected_stations

data: Dict[str, np.ndarray] property #

any data assigned to the line using the add_data method.

__init__(line: LineString | np.ndarray, mask: Tuple[float, float] = None, crs: str = None) #

Geometry Line initialization.

Parameters:

Name Type Description Default
line LineString

River center line as a linestring.

required
mask Tuple[float, float]

Lower and upper limit for the chainage. Defaults to None.

None
crs (str, Optional)

the coordinate reference system number as a string.

None

Examples:

>>> line_string = LineString([(0, 0, 0), (1, 1, 1), (2, 2, 2)])
>>> mask = (0.5, 1.5)
>>> center_line = LineGeometry(line_string, mask)
No message found for clip_chainage
>>> np.array(center_line.values.coords)
array([[0.5, 0.5, 0.5],
       [1. , 1. , 1. ],
       [1.5, 1.5, 1.5]])
Source code in src/dfastbe/io/data_models.py
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
def __init__(self, line: LineString | np.ndarray, mask: Tuple[float, float] = None, crs: str = None):
    """Geometry Line initialization.

    Args:
        line (LineString):
            River center line as a linestring.
        mask (Tuple[float, float], optional):
            Lower and upper limit for the chainage. Defaults to None.
        crs (str, Optional):
            the coordinate reference system number as a string.

    Examples:
        ```python
        >>> line_string = LineString([(0, 0, 0), (1, 1, 1), (2, 2, 2)])
        >>> mask = (0.5, 1.5)
        >>> center_line = LineGeometry(line_string, mask)
        No message found for clip_chainage
        >>> np.array(center_line.values.coords)
        array([[0.5, 0.5, 0.5],
               [1. , 1. , 1. ],
               [1.5, 1.5, 1.5]])

        ```
    """
    self.station_bounds = mask
    self.crs = crs
    self._data = {}
    if isinstance(line, np.ndarray):
        line = LineString(line)
    if mask is None:
        self.values = line
    else:
        self.values: LineString = self.mask(line, mask)

        log_text(
            "clip_chainage", data={"low": self.station_bounds[0], "high": self.station_bounds[1]}
        )

add_data(data: Dict[str, np.ndarray]) -> None #

Add data to the LineGeometry object.

Parameters:

Name Type Description Default
data Dict[str, ndarray]

Dictionary of quantities to be added, each np array should have length k.

required
Source code in src/dfastbe/io/data_models.py
91
92
93
94
95
96
97
98
99
def add_data(self, data: Dict[str, np.ndarray]) -> None:
    """
    Add data to the LineGeometry object.

    Args:
        data (Dict[str, np.ndarray]):
            Dictionary of quantities to be added, each np array should have length k.
    """
    self._data = self.data | data

intersect_with_line(reference_line_with_stations: np.ndarray) -> np.ndarray #

Project chainage(stations) values from a reference line onto a target line by spatial proximity and interpolation.

Project chainage values from source line L1 onto another line L2.

The chainage values are giving along a line L1 (xykm_numpy). For each node of the line L2 (line_xy) on which we would like to know the chainage, first the closest node (discrete set of nodes) on L1 is determined and subsequently the exact chainage is obtained by determining the closest point (continuous line) on L1 for which the chainage is determined using by means of interpolation.

Parameters:

Name Type Description Default
reference_line_with_stations ndarray

Mx3 array with x, y, and chainage values for the reference line.

required

Returns:

Name Type Description
line_km ndarray

np.ndarray Array containing the chainage for every coordinate specified in line_xy.

Source code in src/dfastbe/io/data_models.py
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
def intersect_with_line(
    self, reference_line_with_stations: np.ndarray
) -> np.ndarray:
    """
    Project chainage(stations) values from a reference line onto a target line by spatial proximity and interpolation.

    Project chainage values from source line L1 onto another line L2.

    The chainage values are giving along a line L1 (xykm_numpy). For each node
    of the line L2 (line_xy) on which we would like to know the chainage, first
    the closest node (discrete set of nodes) on L1 is determined and
    subsequently the exact chainage is obtained by determining the closest point
    (continuous line) on L1 for which the chainage is determined using by means
    of interpolation.

    Args:
        reference_line_with_stations (np.ndarray):
            Mx3 array with x, y, and chainage values for the reference line.

    Returns:
        line_km : np.ndarray
            Array containing the chainage for every coordinate specified in line_xy.
    """
    coords = self.as_array()
    # pre-allocates the array for the mapped chainage values
    projected_stations = np.zeros(coords.shape[0])

    # get an array with only the x,y coordinates of line L1
    ref_coords = reference_line_with_stations[:, :2]
    last_index = reference_line_with_stations.shape[0] - 1

    # for each node rp on line L2 get the chainage ...
    for i, station_i in enumerate(coords):
        # find the node on L1 closest to rp
        # get the distance to all the nodes on the reference line, and find the closest one
        closest_ind = np.argmin(((station_i - ref_coords) ** 2).sum(axis=1))
        closest_coords = ref_coords[closest_ind]

        # determine the distance between that node and rp
        squared_distance = ((station_i - closest_coords) ** 2).sum()

        # chainage value of that node
        station = reference_line_with_stations[closest_ind, 2]

        # if we didn't get the first node
        if closest_ind > 0:
            # project rp onto the line segment before this node
            closest_coord_minus_1 = ref_coords[closest_ind - 1]
            alpha = (
                            (closest_coord_minus_1[0] - closest_coords[0]) * (station_i[0] - closest_coords[0])
                            + (closest_coord_minus_1[1] - closest_coords[1]) * (station_i[1] - closest_coords[1])
                    ) / ((closest_coord_minus_1[0] - closest_coords[0]) ** 2 + (closest_coord_minus_1[1] - closest_coords[1]) ** 2)
            # if there is a closest point not coinciding with the nodes ...
            if 0 < alpha < 1:
                dist2link = (station_i[0] - closest_coords[0] - alpha * (closest_coord_minus_1[0] - closest_coords[0])) ** 2 + (
                        station_i[1] - closest_coords[1] - alpha * (closest_coord_minus_1[1] - closest_coords[1])
                ) ** 2
                # if it's actually closer than the node ...
                if dist2link < squared_distance:
                    # update the closest point information
                    squared_distance = dist2link
                    station = reference_line_with_stations[closest_ind, 2] + alpha * (
                            reference_line_with_stations[closest_ind - 1, 2] - reference_line_with_stations[closest_ind, 2]
                    )

        # if we didn't get the last node
        if closest_ind < last_index:
            # project rp onto the line segment after this node
            closest_coord_minus_1 = ref_coords[closest_ind + 1]
            alpha = (
                            (closest_coord_minus_1[0] - closest_coords[0]) * (station_i[0] - closest_coords[0])
                            + (closest_coord_minus_1[1] - closest_coords[1]) * (station_i[1] - closest_coords[1])
                    ) / ((closest_coord_minus_1[0] - closest_coords[0]) ** 2 + (closest_coord_minus_1[1] - closest_coords[1]) ** 2)
            # if there is a closest point not coinciding with the nodes ...
            if alpha > 0 and alpha < 1:
                dist2link = (station_i[0] - closest_coords[0] - alpha * (closest_coord_minus_1[0] - closest_coords[0])) ** 2 + (
                        station_i[1] - closest_coords[1] - alpha * (closest_coord_minus_1[1] - closest_coords[1])
                ) ** 2
                # if it's actually closer than the previous value ...
                if dist2link < squared_distance:
                    # update the closest point information
                    # squared_distance = dist2link
                    station = reference_line_with_stations[closest_ind, 2] + alpha * (
                            reference_line_with_stations[closest_ind + 1, 2] - reference_line_with_stations[closest_ind, 2]
                    )
        # store the chainage value, loop ... and return
        projected_stations[i] = station
    return projected_stations

mask(line_string: LineString, bounds: Tuple[float, float]) -> LineString staticmethod #

Clip a LineGeometry to the relevant reach.

Parameters:

Name Type Description Default
line_string LineString

river center line as a linestring.

required
bounds Tuple[float, float]

Lower and upper limit for the chainage.

required

Returns:

Name Type Description
LineString LineString

Clipped river chainage line.

Examples:

>>> line_string = LineString([(0, 0, 0), (1, 1, 1), (2, 2, 2)])
>>> bounds = (0.5, 1.5)
>>> center_line = LineGeometry.mask(line_string, bounds)
>>> np.array(center_line.coords)
array([[0.5, 0.5, 0.5],
       [1. , 1. , 1. ],
       [1.5, 1.5, 1.5]])
Source code in src/dfastbe/io/data_models.py
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
@staticmethod
def mask(line_string: LineString, bounds: Tuple[float, float]) -> LineString:
    """Clip a LineGeometry to the relevant reach.

    Args:
        line_string (LineString):
            river center line as a linestring.
        bounds (Tuple[float, float]):
            Lower and upper limit for the chainage.

    Returns:
        LineString: Clipped river chainage line.

    Examples:
        ```python
        >>> line_string = LineString([(0, 0, 0), (1, 1, 1), (2, 2, 2)])
        >>> bounds = (0.5, 1.5)
        >>> center_line = LineGeometry.mask(line_string, bounds)
        >>> np.array(center_line.coords)
        array([[0.5, 0.5, 0.5],
               [1. , 1. , 1. ],
               [1.5, 1.5, 1.5]])

        ```
    """
    line_string_coords = line_string.coords
    start_index = LineGeometry._find_mask_index(bounds[0], line_string_coords)
    end_index = LineGeometry._find_mask_index(bounds[1], line_string_coords)
    lower_bound_point, start_index = LineGeometry._handle_bound(
        start_index, bounds[0], True, line_string_coords
    )
    upper_bound_point, end_index = LineGeometry._handle_bound(
        end_index, bounds[1], False, line_string_coords
    )

    if lower_bound_point is None and upper_bound_point is None:
        return line_string
    elif lower_bound_point is None:
        return LineString(line_string_coords[: end_index + 1] + [upper_bound_point])
    elif upper_bound_point is None:
        return LineString([lower_bound_point] + line_string_coords[start_index:])
    else:
        return LineString(
            [lower_bound_point]
            + line_string_coords[start_index:end_index]
            + [upper_bound_point]
        )

to_file(file_name: str, data: Dict[str, np.ndarray] = None) -> None #

Write a shape point file with x, y, and values.

Parameters:

Name Type Description Default
file_name

str Name of the file to be written.

required
data

Dict[str, np.ndarray] Dictionary of quantities to be written, each np array should have length k.

None
Source code in src/dfastbe/io/data_models.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def to_file(
        self, file_name: str, data: Dict[str, np.ndarray] = None,
) -> None:
    """
    Write a shape point file with x, y, and values.

    Args:
        file_name : str
            Name of the file to be written.
        data : Dict[str, np.ndarray]
            Dictionary of quantities to be written, each np array should have length k.
    """
    xy = self.as_array()
    geom = [Point(xy_i) for xy_i in xy]
    if data is None:
        data = self.data
    else:
        data = data | self.data
    GeoDataFrame(data, geometry=geom, crs=self.crs).to_file(file_name)

The data models component provides classes for representing various types of data used in the I/O operations.

File Utilities#

dfastbe.io.file_utils #

Copyright (C) 2020 Stichting Deltares.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 2.1.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, see http://www.gnu.org/licenses/.

contact: delft3d.support@deltares.nl Stichting Deltares P.O. Box 177 2600 MH Delft, The Netherlands

All indications and logos of, and references to, "Delft3D" and "Deltares" are registered trademarks of Stichting Deltares, and remain the property of Stichting Deltares. All rights reserved.

INFORMATION This file is part of D-FAST Bank Erosion: https://github.com/Deltares/D-FAST_Bank_Erosion

absolute_path(rootdir: str, path: str) -> str #

Convert a relative path to an absolute path.

Parameters:

Name Type Description Default
rootdir str

Any relative paths should be given relative to this location.

required
path str

A relative or absolute location.

required

Returns:

Name Type Description
str str

An absolute location.

Source code in src/dfastbe/io/file_utils.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def absolute_path(rootdir: str, path: str) -> str:
    """
    Convert a relative path to an absolute path.

    Args:
        rootdir (str): Any relative paths should be given relative to this location.
        path (str): A relative or absolute location.

    Returns:
        str: An absolute location.
    """
    if not path:
        return path
    root_path = Path(rootdir).resolve()
    target_path = Path(path)

    if target_path.is_absolute():
        return str(target_path)

    resolved_path = (root_path / target_path).resolve()
    return str(resolved_path)

relative_path(rootdir: str, file: str) -> str #

Convert an absolute path to a relative path.

Parameters:

Name Type Description Default
rootdir str

Any relative paths will be given relative to this location.

required
file str

An absolute location.

required

Returns:

Name Type Description
str str

A relative location if possible, otherwise the absolute location.

Source code in src/dfastbe/io/file_utils.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def relative_path(rootdir: str, file: str) -> str:
    """
    Convert an absolute path to a relative path.

    Args:
        rootdir (str): Any relative paths will be given relative to this location.
        file (str): An absolute location.

    Returns:
        str: A relative location if possible, otherwise the absolute location.
    """
    if not file:
        return file

    root_path = Path(rootdir).resolve()
    file_path = Path(file).resolve()

    try:
        return str(file_path.relative_to(root_path))
    except ValueError:
        return str(file_path)

The file utilities component provides functions for file operations, such as reading and writing files.

Logging#

dfastbe.io.logger #

Copyright (C) 2020 Stichting Deltares.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 2.1.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, see http://www.gnu.org/licenses/.

contact: delft3d.support@deltares.nl Stichting Deltares P.O. Box 177 2600 MH Delft, The Netherlands

All indications and logos of, and references to, "Delft3D" and "Deltares" are registered trademarks of Stichting Deltares, and remain the property of Stichting Deltares. All rights reserved.

INFORMATION This file is part of D-FAST Bank Erosion: https://github.com/Deltares/D-FAST_Bank_Erosion

get_text(key: str) -> List[str] #

Query the global dictionary of texts via a string key.

Query the global dictionary PROGTEXTS by means of a string key and return the list of strings contained in the dictionary. If the dictionary doesn't include the key, a default string is returned.

Parameters#

key : str The key string used to query the dictionary.

Returns#

text : List[str] The list of strings returned contain the text stored in the dictionary for the key. If the key isn't available in the dictionary, the routine returns the default string "No message found for "

Source code in src/dfastbe/io/logger.py
 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
def get_text(key: str) -> List[str]:
    """
    Query the global dictionary of texts via a string key.

    Query the global dictionary PROGTEXTS by means of a string key and return
    the list of strings contained in the dictionary. If the dictionary doesn't
    include the key, a default string is returned.

    Parameters
    ----------
    key : str
        The key string used to query the dictionary.

    Returns
    -------
    text : List[str]
        The list of strings returned contain the text stored in the dictionary
        for the key. If the key isn't available in the dictionary, the routine
        returns the default string "No message found for <key>"
    """

    global PROGTEXTS

    if key in PROGTEXTS.keys():
        str_value = PROGTEXTS[key]
    else:
        str_value = ["No message found for " + key]
    return str_value

load_program_texts(file_name: str | Path) -> None #

Load texts from a configuration file, and store globally for access.

This routine reads the text file "file_name", and detects the keywords indicated by lines starting with [ and ending with ]. The content is placed in a global dictionary PROGTEXTS which may be queried using the routine "get_text". These routines are used to implement multi-language support.

Arguments#

file_name : str The name of the file to be read and parsed.

Source code in src/dfastbe/io/logger.py
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
def load_program_texts(file_name: str | Path) -> None:
    """Load texts from a configuration file, and store globally for access.

    This routine reads the text file "file_name", and detects the keywords
    indicated by lines starting with [ and ending with ]. The content is
    placed in a global dictionary PROGTEXTS which may be queried using the
    routine "get_text". These routines are used to implement multi-language support.

    Arguments
    ---------
    file_name : str
        The name of the file to be read and parsed.
    """
    global PROGTEXTS

    all_lines = open(file_name, "r").read().splitlines()
    data: Dict[str, List[str]] = {}
    text: List[str] = []
    key = None
    for line in all_lines:
        r_line = line.strip()
        if r_line.startswith("[") and r_line.endswith("]"):
            if key is not None:
                data[key] = text
            key = r_line[1:-1]
            text = []
        else:
            text.append(line)
    if key in data.keys():
        raise ValueError(f"Duplicate entry for {key} in {file_name}.")

    if key is not None:
        data[key] = text

    PROGTEXTS = data

log_text(key: str, file: Optional[TextIO] = None, data: Dict[str, Any] = {}, repeat: int = 1, indent: str = '') -> None #

Write a text to standard out or file.

Arguments#

key : str The key for the text to show to the user. file : Optional[TextIO] The file to write to (None for writing to standard out). data : Dict[str, Any] A dictionary used for placeholder expansions (default empty). repeat : int The number of times that the same text should be repeated (default 1). indent : str String to use for each line as indentation (default empty).

Returns#

None

Source code in src/dfastbe/io/logger.py
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
def log_text(
        key: str,
        file: Optional[TextIO] = None,
        data: Dict[str, Any] = {},
        repeat: int = 1,
        indent: str = "",
) -> None:
    """
    Write a text to standard out or file.

    Arguments
    ---------
    key : str
        The key for the text to show to the user.
    file : Optional[TextIO]
        The file to write to (None for writing to standard out).
    data : Dict[str, Any]
        A dictionary used for placeholder expansions (default empty).
    repeat : int
        The number of times that the same text should be repeated (default 1).
    indent : str
        String to use for each line as indentation (default empty).

    Returns
    -------
    None
    """
    str_value = get_text(key)
    for _ in range(repeat):
        for s in str_value:
            sexp = s.format(**data)
            if file is None:
                print(indent + sexp)
            else:
                file.write(indent + sexp + "\n")

timed_logger(label: str) -> None #

Write a message with time information.

Arguments#

label : str Message string.

Source code in src/dfastbe/io/logger.py
140
141
142
143
144
145
146
147
148
149
150
def timed_logger(label: str) -> None:
    """
    Write a message with time information.

    Arguments
    ---------
    label : str
        Message string.
    """
    time, diff = _timer()
    print(time + diff + label)

The logging component handles logging information during the execution of the software.

Workflow#

The typical workflow for using the I/O module is:

  1. Read a configuration file using the ConfigFile.read method
  2. Use the configuration to load input data (hydrodynamic simulation results, bank lines, etc.)
  3. Process the data using the Bank Lines and Bank Erosion modules
  4. Save the results using the I/O module's functions

Usage Example#

from dfastbe.io.config import ConfigFile
from dfastbe.bank_erosion.bank_erosion import Erosion

# Read configuration file
config_file = ConfigFile.read("config.cfg")

# Use configuration to initialize Erosion object
erosion = Erosion(config_file)

# Run erosion calculation (which will use I/O module to load and save data)
erosion.run()

For more details on the specific classes and functions, refer to the API reference below.