Skip to content

HmsDss

DSS file operations for HEC-HMS results.

hms_commander.HmsDss

DSS file operations for HMS input/output.

Uses hms-commander's standalone DSS implementation powered by HEC Monolith libraries. Provides HMS-specific convenience methods for working with precipitation, discharge, and other hydrologic time series.

All methods are static - no instantiation required.

Backends

HmsDss.backend selects how DSS files are read and written (the environment variable HMS_COMMANDER_DSS_BACKEND overrides it):

  • "java" (default): HEC Monolith through pyjnius.
  • "native": the optional ras_commander_fast_dss engine; no Java.
  • "shadow": reads return the native result and are compared with Java (grids return Java's grid); writes run on Java and are repeated natively on a temporary copy. Differences are logged; the comparison never raises.

See docs/user_guide/dss_native_backend.md.

Dependencies
  • Java backend: pyjnius, Java 8+ (JRE or JDK), HEC Monolith libraries (auto-downloaded on first use)
  • Native backend: the optional ras-commander-fast-dss engine (pip install ras-commander-fast-dss or pip install "hms-commander[dss]")
Example

from hms_commander import HmsDss catalog = HmsDss.get_catalog("results.dss") ts = HmsDss.read_timeseries("results.dss", "/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/") print(f"Units: {ts.attrs['units']}")

Source code in hms_commander/dss/hms_dss.py
  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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
class HmsDss:
    """
    DSS file operations for HMS input/output.

    Uses hms-commander's standalone DSS implementation powered by HEC Monolith
    libraries. Provides HMS-specific convenience methods for working with
    precipitation, discharge, and other hydrologic time series.

    All methods are static - no instantiation required.

    Backends:
        ``HmsDss.backend`` selects how DSS files are read and written (the
        environment variable ``HMS_COMMANDER_DSS_BACKEND`` overrides it):

        - ``"java"`` (default): HEC Monolith through pyjnius.
        - ``"native"``: the optional ``ras_commander_fast_dss`` engine; no Java.
        - ``"shadow"``: reads return the native result and are compared with
          Java (grids return Java's grid); writes run on Java and are repeated
          natively on a temporary copy. Differences are logged; the comparison
          never raises.

        See ``docs/user_guide/dss_native_backend.md``.

    Dependencies:
        - Java backend: pyjnius, Java 8+ (JRE or JDK), HEC Monolith libraries
          (auto-downloaded on first use)
        - Native backend: the optional ``ras-commander-fast-dss`` engine
          (``pip install ras-commander-fast-dss`` or ``pip install "hms-commander[dss]"``)

    Example:
        >>> from hms_commander import HmsDss
        >>> catalog = HmsDss.get_catalog("results.dss")
        >>> ts = HmsDss.read_timeseries("results.dss", "/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/")
        >>> print(f"Units: {ts.attrs['units']}")
    """

    #: DSS backend: ``"java"`` (default when None), ``"native"`` or ``"shadow"``.
    #: The environment variable ``HMS_COMMANDER_DSS_BACKEND`` overrides it.
    backend: Optional[str] = None

    #: Shadow writes copy an existing target file up to this size (MB) to repeat the
    #: write natively; larger files skip the comparison. The environment variable
    #: ``HMS_COMMANDER_DSS_SHADOW_COPY_LIMIT_MB`` overrides it.
    shadow_copy_limit_mb: float = _backend.SHADOW_COPY_LIMIT_MB_DEFAULT

    # Common HMS DSS path patterns (C-part matching)
    # HMS uses formats like FLOW, FLOW-OBSERVED, FLOW-DIRECT, FLOW-BASE, etc.
    HMS_RESULT_PATTERNS = {
        'flow': r'/FLOW[^/]*/|/FLOW/',             # Matches FLOW, FLOW-DIRECT, FLOW-COMBINE, etc.
        'flow-total': r'/FLOW/',                    # Only total FLOW
        'flow-observed': r'/FLOW-OBSERVED/',
        'flow-direct': r'/FLOW-DIRECT/',
        'flow-base': r'/FLOW-BASE/',
        'flow-combine': r'/FLOW-COMBINE/',
        'precipitation': r'/PRECIP[^/]*/|/PRECIP/', # Matches PRECIP, PRECIP-INC, PRECIP-CUM
        'precip-inc': r'/PRECIP-INC/',
        'precip-cum': r'/PRECIP-CUM/',
        'precip-excess': r'/PRECIP-EXCESS/',
        'precip-loss': r'/PRECIP-LOSS/',
        'stage': r'/STAGE/',
        'storage': r'/STORAGE[^/]*/|/STORAGE/',
        'storage-gw': r'/STORAGE-GW/',
        'storage-soil': r'/STORAGE-SOIL/',
        'elevation': r'/ELEV/',
        'outflow': r'/OUTFLOW[^/]*/|/OUTFLOW/',
        'inflow': r'/INFLOW[^/]*/|/INFLOW/',
        'excess': r'/EXCESS[^/]*/|/EXCESS/',
        'baseflow': r'/BASEFLOW/',
        'infiltration': r'/INFILTRATION/',
        'et': r'/ET[^/]*/|/ET/',
    }

    @staticmethod
    @log_call
    def get_backend() -> str:
        """
        DSS backend for the next call: ``"java"``, ``"native"`` or ``"shadow"``.

        ``HMS_COMMANDER_DSS_BACKEND`` overrides ``HmsDss.backend``. ``shadow``
        without the engine runs Java only and logs one warning.

        Raises:
            ValueError: If the backend name is invalid
            ImportError: If ``native`` is requested and ras_commander_fast_dss is
                not installed (or fails to load)

        Example:
            >>> HmsDss.backend = "native"
            >>> HmsDss.get_backend()
            'native'
        """
        return DssCore.get_backend()

    @staticmethod
    @log_call
    def get_capabilities() -> pd.DataFrame:
        """
        Backend support per DSS operation.

        Returns:
            DataFrame with columns ``operation``, ``java``, ``native``, ``shadow``
            and ``note``. Values: ``yes``; ``gated`` (needs a qualified or
            writer-capable engine). ``attrs`` report ``requested_backend``,
            ``native_available``, ``native_writes_available``,
            ``native_grid_qualified``, ``native_gridded_import_available``,
            ``native_write_sync_available`` (the writers take ``sync=``) and
            ``engine_features``.
        """
        df = pd.DataFrame(list(_backend.CAPABILITIES),
                          columns=["operation", "java", "native", "shadow", "note"])
        try:
            requested = _backend.requested_backend(HmsDss.backend)
        except ValueError as exc:
            requested = f"invalid: {exc}"
        df.attrs.update(
            requested_backend=requested,
            native_available=_backend.native_available(),
            native_writes_available=_backend.native_writes_available(),
            native_grid_qualified=_backend.native_grid_qualified(),
            native_gridded_import_available=_backend.native_gridded_import_available(),
            native_write_sync_available=_backend.native_sync_available(),
            engine_features=sorted(_backend.engine_features()),
        )
        return df

    @staticmethod
    @log_call
    def get_shadow_summary(reset: bool = False) -> Dict[str, int]:
        """
        Counts of shadow comparisons as ``{"operation|outcome|label": n}``.

        Args:
            reset: Clear the counters and records after reading them
        """
        result = _backend.summary()
        if reset:
            _backend.reset_shadow_stats()
        return result

    @staticmethod
    @log_call
    def is_available() -> bool:
        """
        Check if full DSS functionality is available.

        Returns:
            True if the selected backend can run: ``native`` needs the
            ras_commander_fast_dss engine; ``java`` needs pyjnius; ``shadow``
            needs the engine (it falls back to ``java`` without it)

        Example:
            >>> if HmsDss.is_available():
            ...     catalog = HmsDss.get_catalog("file.dss")
            ... else:
            ...     print("Install pyjnius: pip install pyjnius")
        """
        if not DSS_AVAILABLE:
            return False
        return DssCore.is_available()

    @staticmethod
    @log_call
    def get_catalog(
        dss_file: Union[str, Path]
    ) -> List[str]:
        """
        Get catalog of all paths in a DSS file.

        Args:
            dss_file: Path to the DSS file

        Returns:
            List of DSS pathnames

        Example:
            >>> paths = HmsDss.get_catalog("results.dss")
            >>> for path in paths:
            ...     print(path)
        """
        dss_file = Path(dss_file)

        if not dss_file.exists():
            raise FileNotFoundError(f"DSS file not found: {dss_file}")

        if not DSS_AVAILABLE:
            raise ImportError(
                "DSS functionality requires pyjnius.\n"
                "Install with: pip install pyjnius\n"
                "Also requires Java 8+ (JRE or JDK)"
            )

        return DssCore.get_catalog(dss_file)

    @staticmethod
    @log_call
    def read_timeseries(
        dss_file: Union[str, Path],
        pathname: str,
        start_date: Optional[Any] = None,
        end_date: Optional[Any] = None
    ) -> pd.DataFrame:
        """
        Read a time series from a DSS file.

        Args:
            dss_file: Path to the DSS file
            pathname: DSS pathname to read
            start_date: Optional inclusive lower bound on the returned stamps
            end_date: Optional inclusive upper bound on the returned stamps

        Returns:
            DataFrame with:
            - DatetimeIndex for time series operations
            - 'datetime' column for plotting (same as index)
            - 'value' column with time series data
            - Metadata via df.attrs: pathname, units, type, interval

        Example:
            >>> ts = HmsDss.read_timeseries(
            ...     "results.dss",
            ...     "/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/"
            ... )
            >>> print(ts.head())
            >>> print(f"Units: {ts.attrs['units']}")
            >>>
            >>> # Plotting options:
            >>> ax.plot(ts['datetime'], ts['value'])    # Using datetime column
            >>> ax.plot(ts.index, ts['value'])          # Using DatetimeIndex
            >>> ts.plot(y='value')                      # Pandas automatic
        """
        dss_file = Path(dss_file)

        if not dss_file.exists():
            raise FileNotFoundError(f"DSS file not found: {dss_file}")

        if not DSS_AVAILABLE:
            raise ImportError(
                "DSS functionality requires pyjnius.\n"
                "Install with: pip install pyjnius"
            )

        return DssCore.read_timeseries(dss_file, pathname, start_date, end_date)

    @staticmethod
    @log_call
    def read_multiple_timeseries(
        dss_file: Union[str, Path],
        pathnames: List[str]
    ) -> Dict[str, pd.DataFrame]:
        """
        Read multiple time series from a DSS file.

        Args:
            dss_file: Path to the DSS file
            pathnames: List of DSS pathnames to read

        Returns:
            Dictionary mapping pathnames to DataFrames (None on failure)

        Example:
            >>> paths = ["/BASIN/SUB1/FLOW//15MIN/RUN1/", "/BASIN/SUB2/FLOW//15MIN/RUN1/"]
            >>> data = HmsDss.read_multiple_timeseries("results.dss", paths)
            >>> for path, df in data.items():
            ...     if df is not None:
            ...         print(f"{path}: {len(df)} points")
        """
        dss_file = Path(dss_file)

        if not DSS_AVAILABLE:
            raise ImportError("DSS functionality requires pyjnius.")

        return DssCore.read_multiple_timeseries(dss_file, pathnames)

    @staticmethod
    @log_call
    def extract_hms_results(
        dss_file: Union[str, Path],
        element_names: Optional[List[str]] = None,
        result_type: str = "flow",
        run_name: Optional[str] = None,
    ) -> Dict[str, pd.DataFrame]:
        """
        Extract HMS simulation results from a DSS file.

        This is a convenience method that filters results by element name
        and result type.

        Args:
            dss_file: Path to the DSS file
            element_names: List of element names to extract (all if None)
            result_type: Type of result ("flow", "precipitation", "stage", etc.)
            run_name: Optional F-part run name filter

        Returns:
            Dictionary mapping element names to result DataFrames

        Example:
            >>> results = HmsDss.extract_hms_results(
            ...     "results.dss",
            ...     element_names=["Outlet", "Junction-1"],
            ...     result_type="flow"
            ... )
            >>> for name, df in results.items():
            ...     print(f"{name}: peak = {df['value'].max():.2f}")
        """
        dss_file = Path(dss_file)

        if not DSS_AVAILABLE:
            raise ImportError("DSS functionality requires pyjnius.")

        catalog = HmsDss.get_catalog(dss_file)
        matching_paths = select_result_paths(
            catalog,
            result_type=result_type,
            element_names=element_names,
            run_name=run_name,
            exclude_tables=True,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )

        # Read matching time series
        results = {}
        for path in matching_paths:
            parts = parse_pathname(path)
            element_name = parts["element_name"]
            try:
                df = HmsDss.read_timeseries(dss_file, path)
                results[element_name] = df
            except Exception as e:
                logger.warning(f"Could not read {path}: {e}")

        logger.info(f"Extracted {len(results)} result time series")
        return results

    @staticmethod
    @log_call
    def get_info(
        dss_file: Union[str, Path]
    ) -> Dict[str, Any]:
        """
        Get summary information about a DSS file.

        Args:
            dss_file: Path to the DSS file

        Returns:
            Dictionary with file information including path count and data types

        Example:
            >>> info = HmsDss.get_info("results.dss")
            >>> print(f"Total paths: {info['num_paths']}")
            >>> print(f"Data types: {info['path_types']}")
        """
        dss_file = Path(dss_file)

        info = {
            'file_path': str(dss_file),
            'file_exists': dss_file.exists(),
            'file_size_mb': None,
            'num_paths': None,
            'path_types': {},
            'dss_available': DSS_AVAILABLE
        }

        if dss_file.exists():
            info['file_size_mb'] = round(dss_file.stat().st_size / (1024 * 1024), 2)

            if DSS_AVAILABLE:
                try:
                    catalog = HmsDss.get_catalog(dss_file)
                    info['num_paths'] = len(catalog)

                    # Categorize paths by C-part
                    for path in catalog:
                        parts = path.split('/')
                        if len(parts) >= 4:
                            data_type = parts[3]  # C part
                            info['path_types'][data_type] = info['path_types'].get(data_type, 0) + 1

                except Exception as e:
                    logger.warning(f"Could not read DSS catalog: {e}")

        return info

    @staticmethod
    @log_call
    def list_flow_results(
        dss_file: Union[str, Path]
    ) -> List[str]:
        """
        List all flow result pathnames in a DSS file.

        Args:
            dss_file: Path to the DSS file

        Returns:
            List of flow result pathnames

        Example:
            >>> flows = HmsDss.list_flow_results("results.dss")
            >>> for path in flows:
            ...     parts = HmsDss.parse_dss_pathname(path)
            ...     print(f"{parts['element_name']}: {path}")
        """
        catalog = HmsDss.get_catalog(dss_file)
        return select_result_paths(
            catalog,
            result_type="flow",
            exclude_tables=False,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )

    @staticmethod
    @log_call
    def list_precipitation_data(
        dss_file: Union[str, Path]
    ) -> List[str]:
        """
        List all precipitation data pathnames in a DSS file.

        Args:
            dss_file: Path to the DSS file

        Returns:
            List of precipitation pathnames
        """
        catalog = HmsDss.get_catalog(dss_file)
        return select_result_paths(
            catalog,
            result_type="precipitation",
            exclude_tables=False,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )

    @staticmethod
    @log_call
    def list_stage_results(
        dss_file: Union[str, Path]
    ) -> List[str]:
        """
        List all stage result pathnames in a DSS file.

        Args:
            dss_file: Path to the DSS file

        Returns:
            List of stage result pathnames
        """
        catalog = HmsDss.get_catalog(dss_file)
        return select_result_paths(
            catalog,
            result_type="stage",
            exclude_tables=False,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )

    @staticmethod
    @log_call
    def list_storage_results(
        dss_file: Union[str, Path]
    ) -> List[str]:
        """
        List all storage result pathnames in a DSS file.

        Args:
            dss_file: Path to the DSS file

        Returns:
            List of storage result pathnames
        """
        catalog = HmsDss.get_catalog(dss_file)
        return select_result_paths(
            catalog,
            result_type="storage",
            exclude_tables=False,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )

    @staticmethod
    @log_call
    def parse_dss_pathname(pathname: str) -> Dict[str, str]:
        """
        Parse a DSS pathname into its component parts.

        DSS pathnames have format: /A/B/C/D/E/F/
        - A: Basin/Project identifier
        - B: Location/Element name
        - C: Data type (FLOW, PRECIP, etc.)
        - D: Date/Time block
        - E: Time interval
        - F: Version/Run identifier

        Args:
            pathname: DSS pathname string

        Returns:
            Dictionary with pathname components including convenience fields

        Example:
            >>> parts = HmsDss.parse_dss_pathname("/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/")
            >>> print(parts['element_name'])  # 'OUTLET'
            >>> print(parts['data_type'])     # 'FLOW'
            >>> print(parts['run_name'])      # 'RUN1'
        """
        return parse_pathname(pathname)

    @staticmethod
    @log_call
    def create_dss_pathname(
        basin: str,
        element: str,
        data_type: str,
        interval: str,
        run_name: str = "",
        date_block: str = ""
    ) -> str:
        """
        Create a DSS pathname from components.

        Args:
            basin: Basin/Project name (A part)
            element: Element name (B part)
            data_type: Data type like FLOW, PRECIP (C part)
            interval: Time interval like 15MIN, 1HOUR (E part)
            run_name: Run identifier (F part)
            date_block: Date block (D part, usually empty)

        Returns:
            Formatted DSS pathname

        Example:
            >>> path = HmsDss.create_dss_pathname(
            ...     "MYBASIN", "OUTLET", "FLOW", "15MIN", "RUN1"
            ... )
            >>> print(path)  # '/MYBASIN/OUTLET/FLOW//15MIN/RUN:RUN1/'
        """
        return create_pathname(basin, element, data_type, interval, run_name, date_block)

    @staticmethod
    @log_call
    def filter_catalog(
        catalog: List[str],
        pattern: Optional[str] = None,
        data_type: Optional[str] = None,
        element: Optional[str] = None
    ) -> List[str]:
        """
        Filter DSS catalog by pattern or components.

        Args:
            catalog: List of DSS pathnames
            pattern: Regex pattern to match against full pathname
            data_type: Filter by C-part (e.g., "FLOW", "PRECIP")
            element: Filter by B-part (element/location name)

        Returns:
            Filtered list of pathnames

        Example:
            >>> paths = HmsDss.get_catalog("file.dss")
            >>> flow_paths = HmsDss.filter_catalog(paths, data_type="FLOW")
            >>> outlet_flows = HmsDss.filter_catalog(flow_paths, element="OUTLET")
        """
        return filter_catalog(catalog, pattern, data_type, element)

    @staticmethod
    @log_call
    def get_peak_flows(
        dss_file: Union[str, Path],
        element_names: Optional[List[str]] = None
    ) -> pd.DataFrame:
        """
        Extract peak flow values for all elements.

        Note:
            For large DSS files with many elements (100+), consider using
            get_peak_flows_batched() instead to avoid memory issues. That method
            processes elements in batches with garbage collection between batches.

        Uses the total-flow records (C-part ``FLOW``) only. Component and
        derived records such as ``FLOW-BASE`` or ``FLOW-CUMULATIVE`` (a volume)
        are not peak flows.

        Args:
            dss_file: Path to the DSS file
            element_names: Optional list of element names to filter

        Returns:
            DataFrame with columns: element, peak_flow, peak_time, units

        Example:
            >>> peaks = HmsDss.get_peak_flows("results.dss")
            >>> print(peaks.sort_values('peak_flow', ascending=False))

        See Also:
            get_peak_flows_batched: Memory-efficient version for large files
        """
        results = HmsDss.extract_hms_results(dss_file, element_names, result_type="flow-total")

        records = []
        for element_name, df in results.items():
            if df is not None and not df.empty:
                peak_idx = df['value'].idxmax()
                records.append({
                    'element': element_name,
                    'peak_flow': df.loc[peak_idx, 'value'],
                    'peak_time': peak_idx,
                    'units': df.attrs.get('units', '')
                })

        return pd.DataFrame(records)

    @staticmethod
    @log_call
    def get_peak_flows_batched(
        dss_file: Union[str, Path],
        element_names: Optional[List[str]] = None,
        run_name: Optional[str] = None,
        batch_size: int = 50,
        progress: bool = True
    ) -> pd.DataFrame:
        """
        Extract peak flows in batches to avoid memory issues.

        Processes N elements at a time, garbage collects between batches,
        preventing memory exhaustion for large DSS files.

        Args:
            dss_file: Path to DSS file
            element_names: Optional filter for specific elements
            run_name: Optional filter for specific run (e.g., "1%(100YR)RUN")
            batch_size: Elements to process per batch (default: 50)
            progress: Show progress logging (default: True)

        Returns:
            DataFrame with columns:
                - element: Element name
                - peak_flow: Peak flow value (cfs)
                - peak_time: Time of peak (datetime)
                - units: Engineering units
                - dss_path: Full DSS pathname

        Memory: O(batch_size) instead of O(total_elements)

        Example:
            >>> # Safe for 1000+ elements
            >>> peaks = HmsDss.get_peak_flows_batched(
            ...     "results.dss",
            ...     run_name="1%(100YR)RUN",
            ...     batch_size=100  # Adjust for available memory
            ... )
        """
        dss_file = Path(dss_file)

        if not dss_file.exists():
            raise FileNotFoundError(f"DSS file not found: {dss_file}")

        if not DSS_AVAILABLE:
            raise ImportError(
                "DSS functionality requires pyjnius.\n"
                "Install with: pip install pyjnius\n"
                "Also requires Java 8+ (JRE or JDK)"
            )

        catalog = HmsDss.get_catalog(dss_file)
        flow_paths = select_result_paths(
            catalog,
            result_type="flow-total",
            element_names=element_names,
            run_name=run_name,
            exclude_tables=True,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )

        total_paths = len(flow_paths)
        if total_paths == 0:
            logger.info("No flow paths found in DSS file")
            return pd.DataFrame(columns=['element', 'peak_flow', 'peak_time', 'units', 'dss_path'])

        if progress:
            logger.info(f"Extracting peaks from {total_paths} paths...")

        records = []
        total_batches = (total_paths + batch_size - 1) // batch_size  # Ceiling division

        for i in range(0, total_paths, batch_size):
            batch_num = i // batch_size + 1
            batch_paths = flow_paths[i:i + batch_size]

            if progress:
                logger.info(f"Batch {batch_num}/{total_batches}: processing {len(batch_paths)} paths...")

            # Process each path in the batch
            for path in batch_paths:
                try:
                    parts = HmsDss.parse_dss_pathname(path)

                    # Use peak-only extraction (350x more memory efficient)
                    peak_info = DssCore.get_peak_value(dss_file, path)

                    if peak_info is not None:
                        records.append({
                            'element': parts['element_name'],
                            'peak_flow': peak_info['peak_flow'],
                            'peak_time': peak_info['peak_time'],
                            'units': peak_info['units'],
                            'dss_path': path
                        })

                except Exception as e:
                    logger.warning(f"Could not read {path}: {e}")

            # Garbage collect after each batch to free memory
            gc.collect()

        # Create DataFrame from records
        result_df = pd.DataFrame(records)

        # Sort by peak_flow descending
        if not result_df.empty:
            result_df = result_df.sort_values('peak_flow', ascending=False).reset_index(drop=True)

        if progress:
            logger.info(f"Extracted peak flows for {len(result_df)} elements")
        return result_df

    @staticmethod
    @log_call
    def get_total_precipitation(
        dss_file: Union[str, Path],
        element_names: Optional[List[str]] = None
    ) -> pd.DataFrame:
        """
        Calculate total precipitation for all elements.

        Sums the interval precipitation depth (C-part ``PRECIP-INC``, with
        ``PRECIP`` as a legacy fallback), one row per element and run.
        Cumulative series (``PRECIP-CUM``), losses, excess and spatial
        standard deviation are different quantities and are not summed.

        Args:
            dss_file: Path to the DSS file
            element_names: Optional list of element names to filter

        Returns:
            DataFrame with columns: element, total_precip, units, num_intervals

        Example:
            >>> precip = HmsDss.get_total_precipitation("results.dss")
            >>> print(precip)
        """
        catalog = HmsDss.get_catalog(dss_file)
        paths = select_interval_precip_paths(
            select_result_paths(
                catalog,
                result_type="precipitation",
                element_names=element_names,
                exclude_tables=True,
                result_patterns=HmsDss.HMS_RESULT_PATTERNS,
            )
        )

        records = []
        for path in paths:
            try:
                df = HmsDss.read_timeseries(dss_file, path)
            except Exception as e:
                logger.warning(f"Could not read {path}: {e}")
                continue
            if df is not None and not df.empty:
                records.append({
                    'element': parse_pathname(path)['element_name'],
                    'total_precip': df['value'].sum(),
                    'units': df.attrs.get('units', ''),
                    'num_intervals': len(df)
                })

        return pd.DataFrame(records)

    @staticmethod
    @log_call
    def write_paired_data(
        dss_file: Union[str, Path],
        pathname: str,
        x_values: Any,
        y_values: Any = None,
        x_units: Optional[str] = None,
        y_units: Optional[str] = None,
        x_type: Optional[str] = None,
        y_type: Optional[str] = None,
        labels: Optional[Sequence[str]] = None,
        create_if_missing: bool = True,
        *,
        x_precision: Optional[int] = None,
        y_precision: Optional[int] = None,
        value_type: str = "auto",
        dss_version: Optional[int] = None,
        sync: Optional[Any] = None,
        x_label: Optional[str] = None,
        y_label: Optional[str] = None,
    ) -> bool:
        """
        Write one paired-data record with one or more curves.

        Used for Atlas 14 temporal distributions, rating curves and other X-Y
        relationships. The arguments are those of
        ``ras_commander.RasDss.write_paired_data``; ``DssCore.write_paired_data`` documents
        each one, the backends and the refusals. A failed write raises. ``x_label`` and
        ``y_label`` are the earlier names of ``x_type`` and ``y_type``. ``sync`` is the
        native writer's flush policy, passed to the engine unchanged; ``None`` (default)
        leaves the installed engine's own default (see ``DssCore.write_timeseries``).

        Returns:
            True when the record is written and in the file catalog

        Example:
            >>> x = np.linspace(0, 24, 49)  # Hours
            >>> y = np.linspace(0, 1, 49)   # Cumulative fraction
            >>> HmsDss.write_paired_data(
            ...     "temporal.dss", "//TX_R3/FIRST-QUARTILE/24HR//50%/", x, y,
            ...     x_units="HOURS", y_units="FRACTION", x_type="TIME", y_type="CUMULATIVE",
            ... )
            True
        """
        return DssCore.write_paired_data(
            dss_file, pathname, x_values, y_values, x_units, y_units, x_type, y_type, labels,
            create_if_missing, x_precision=x_precision, y_precision=y_precision,
            value_type=value_type, dss_version=dss_version, x_label=x_label, y_label=y_label,
            sync=sync,
        )

    @staticmethod
    @log_call
    def write_multiple_paired_data(
        dss_file: Union[str, Path],
        paired_data_records: List[Dict],
        *,
        sync: Optional[Any] = None,
    ) -> Dict[str, bool]:
        """
        Write multiple paired data records to DSS file.

        More efficient than calling write_paired_data repeatedly as it
        keeps the DSS file open for all writes.

        Args:
            dss_file: Path to DSS file
            paired_data_records: List of dicts with keys:
                - pathname: DSS pathname
                - x_values: numpy array of X values
                - y_values: numpy array of Y values
                - x_units: (optional) X units
                - y_units: (optional) Y units
                - x_label: (optional) X label
                - y_label: (optional) Y label

        Returns:
            Dict mapping pathname to success status. True means the record was
            written and found in the file catalog.

        Raises:
            ValueError: If a pathname does not have exactly six parts, or two
                records share a pathname. Nothing is written in either case.
            RuntimeError: If a write reported no error but its record is not
                in the file catalog afterwards

        Example:
            >>> records = [
            ...     {"pathname": "//TX_R3/FIRST-QUARTILE/24HR//50%/",
            ...      "x_values": hours, "y_values": fractions_50},
            ...     {"pathname": "//TX_R3/FIRST-QUARTILE/24HR//90%/",
            ...      "x_values": hours, "y_values": fractions_90},
            ... ]
            >>> results = HmsDss.write_multiple_paired_data("temporal.dss", records)
            >>> print(f"Wrote {sum(results.values())} records")
        """
        import numpy as np
        dss_file = Path(dss_file)

        if not DSS_AVAILABLE:
            raise ImportError(
                "DSS functionality requires pyjnius.\n"
                "Install with: pip install pyjnius"
            )

        # Convert values to numpy arrays if needed
        for record in paired_data_records:
            record['x_values'] = np.asarray(record['x_values'])
            record['y_values'] = np.asarray(record['y_values'])

        return DssCore.write_multiple_paired_data(dss_file, paired_data_records, sync=sync)

    @staticmethod
    @log_call
    def import_atlas14_temporal(
        dss_file: Union[str, Path],
        temporal_distributions: Dict[str, 'pd.DataFrame'],
        region_code: str,
        duration_hours: int = 24,
        *,
        sync: Optional[Any] = None,
    ) -> Dict[str, bool]:
        """
        Import Atlas 14 temporal distributions to DSS file.

        Convenience method specifically for Atlas 14 temporal data.
        Writes one paired-data record per quartile and probability column with
        the pathname ``//{region_code}/{QUARTILE}/{duration}HR//{probability}/``.
        For example, the 50% curve of the first quartile for region ``TX_R3``
        is ``//TX_R3/FIRST-QUARTILE/24HR//50%/``.

        Units are ``HOURS``/``FRACTION`` and the axis types ``TIME`` and
        ``CUMULATIVE``. A DSS6 file stores at most 8 characters per type, so on
        DSS6 the Y type is ``CUMULATI``: the value HEC Monolith stores there for
        ``CUMULATIVE``. Both backends write the same record. New files are DSS7.

        Args:
            dss_file: Output DSS file path
            temporal_distributions: Dict mapping quartile names to DataFrames
                Each DataFrame should have:
                - Index: hours (0, 0.5, 1.0, ... 24.0)
                - Columns: probability strings ("90%", "80%", ..., "10%")
                - Values: cumulative percentages (0-100)
            region_code: Atlas 14 region code (e.g., "TX_R3")
            duration_hours: Storm duration in hours (default: 24)
            sync: Flush policy of the native writer, passed to
                ras-commander-fast-dss unchanged; ``None`` (default) leaves the
                installed engine's own default. The ``java`` backend does not use
                it. See ``DssCore.write_timeseries``.

        Returns:
            Dict mapping pathname to success status

        Raises:
            ValueError: If a generated pathname is invalid (for example a
                region code that contains ``/``) or two columns produce the
                same pathname
            RuntimeError: If a write reported no error but its record is not
                in the file catalog afterwards

        Example:
            >>> # Parse temporal CSV
            >>> temporal = parse_temporal_csv(csv_content)
            >>>
            >>> # Import to DSS
            >>> results = HmsDss.import_atlas14_temporal(
            ...     "TX_R3_24H.dss",
            ...     temporal,
            ...     region_code="TX_R3",
            ...     duration_hours=24
            ... )
            >>> print(f"Imported {sum(results.values())}/45 distributions")
        """
        import numpy as np

        dss_file = Path(dss_file)

        if not DSS_AVAILABLE:
            raise ImportError("DSS functionality requires pyjnius.")

        # Map quartile names to DSS-compatible names
        quartile_dss_names = {
            "First Quartile": "FIRST-QUARTILE",
            "Second Quartile": "SECOND-QUARTILE",
            "Third Quartile": "THIRD-QUARTILE",
            "Fourth Quartile": "FOURTH-QUARTILE",
            "All Cases": "ALL-CASES"
        }

        duration_str = f"{duration_hours}HR"
        records = []
        # DSS6 stores at most 8 characters per type; "CUMULATI" is what HEC
        # Monolith stores for "CUMULATIVE" there (the native writer refuses a
        # longer string rather than truncate it).
        y_type = "CUMULATIVE"
        if dss_file.exists() and DssCore.get_file_version(dss_file) == 6:
            y_type = "CUMULATIVE"[:DssCore.DSS6_TEXT_LIMIT]

        for quartile_name, df in temporal_distributions.items():
            dss_quartile = quartile_dss_names.get(quartile_name)
            if dss_quartile is None:
                logger.warning(f"Unknown quartile: {quartile_name}, skipping")
                continue

            x_values = np.array(df.index)  # Hours

            for prob_col in df.columns:
                # A=blank, B=region, C=quartile, D=duration, E=blank,
                # F=probability. Seven slashes: heclib drops any extra part,
                # which would put every probability on one record.
                pathname = f"//{region_code}/{dss_quartile}/{duration_str}//{prob_col}/"

                # Convert percentage to fraction
                y_values = df[prob_col].values / 100.0

                records.append({
                    'pathname': pathname,
                    'x_values': x_values,
                    'y_values': y_values,
                    'x_units': 'HOURS',
                    'y_units': 'FRACTION',
                    'x_label': 'TIME',
                    'y_label': y_type
                })

        logger.info(f"Importing {len(records)} temporal distributions to {dss_file}")
        return DssCore.write_multiple_paired_data(dss_file, records, sync=sync)

    @staticmethod
    @log_call
    def read_paired_data(
        dss_file: Union[str, Path],
        pathname: str
    ) -> Optional[Dict[str, Any]]:
        """
        Read paired data (X-Y curve) from DSS file.

        This is used for reading rating curves, diversion tables,
        storage-flow relationships, and other X-Y paired data.

        Args:
            dss_file: Path to DSS file
            pathname: DSS pathname for paired data (e.g., "//ELEMENT/FLOW-DIVERSION///TABLE/")

        Returns:
            Dictionary with:
                - x_values: numpy array of X values
                - y_values: numpy array of Y values
                - x_units: X axis units
                - y_units: Y axis units
                - x_label: X axis label
                - y_label: Y axis label
                - pathname: Original pathname
            Returns None if read fails

        Example:
            >>> data = HmsDss.read_paired_data(
            ...     "paired_data.dss",
            ...     "//T1011300_0000_D/FLOW-DIVERSION///TABLE/"
            ... )
            >>> print(f"Inflow values: {data['x_values']}")
            >>> print(f"Diversion values: {data['y_values']}")
        """
        dss_file = Path(dss_file)

        if not dss_file.exists():
            raise FileNotFoundError(f"DSS file not found: {dss_file}")

        if not DSS_AVAILABLE:
            raise ImportError(
                "DSS functionality requires pyjnius.\n"
                "Install with: pip install pyjnius\n"
                "Also requires Java 8+ (JRE or JDK)"
            )

        return DssCore.read_paired_data(dss_file, pathname)

    @staticmethod
    @log_call
    def get_file_version(dss_file: Union[str, Path]) -> int:
        """
        HEC-DSS version of an existing file: 6 or 7.

        Args:
            dss_file: Path to an existing DSS file

        Returns:
            6 or 7

        Raises:
            FileNotFoundError: If the file does not exist
            ValueError: If the file is not a DSS6 or DSS7 file

        Example:
            >>> HmsDss.get_file_version("results.dss")
            6
        """
        return DssCore.get_file_version(dss_file)

    @staticmethod
    @log_call
    def read_grid(
        dss_file: Union[str, Path],
        pathname: str
    ) -> Dict[str, Any]:
        """
        Read one grid record (HRAP, Albers/SHG or specified) from a DSS file.

        Args:
            dss_file: Path to the DSS file
            pathname: Full grid pathname, including its D and E parts

        Returns:
            Dictionary with ``data`` (float32, shape ``(ny, nx)``, row 0 south,
            missing cells NaN), ``pathname``, ``dss_file``, ``shape``, ``units``,
            ``data_type``, ``grid_type``, ``cell_size``, ``lower_left_cell``,
            ``cell_zero``, ``origin``, ``crs``, ``start_time`` and ``end_time``.
            See ``DssCore.read_grid``.

        Raises:
            FileNotFoundError: If the file does not exist
            ValueError: If the record does not exist or is not a grid
            DssCapabilityError: With the native backend, when the engine does not
                advertise qualified grid CRS strings

        Example:
            >>> paths = HmsDss.get_catalog("hrap.dss")
            >>> grid = HmsDss.read_grid("hrap.dss", paths[0])
            >>> print(grid["grid_type"], grid["shape"], grid["units"])
        """
        return DssCore.read_grid(dss_file, pathname)

    @staticmethod
    @log_call
    def write_timeseries(
        dss_file: Union[str, Path],
        pathname: str,
        times: Union[Sequence[Any], pd.DatetimeIndex, np.ndarray],
        values: Union[Sequence[float], np.ndarray, pd.Series],
        units: str = "CFS",
        data_type: str = "INST-VAL",
        dss_version: Optional[int] = None,
        *,
        sync: Optional[Any] = None,
    ) -> Path:
        """
        Write a regular-interval time series (for example an observed flow gage).

        Args:
            dss_file: Path to the DSS file (created as DSS7 unless ``dss_version``
                is 6)
            pathname: ``/A/B/C/D/E/F/`` with a regular E part (``15MIN``, ``1HOUR``,
                ``1DAY``, ...); D may be empty
            times: One naive end-of-period stamp per value, whole minutes, strictly
                increasing and regular for the E part
            values: Numeric values; ``NaN`` is stored as HEC's missing value
            units: HEC units (default ``CFS``)
            data_type: ``INST-VAL`` (default), ``PER-AVER``, ``PER-CUM`` or ``INST-CUM``
            dss_version: 6 or 7 for a new file; for an existing file it must match
            sync: Flush policy of the native writer, passed to
                ras-commander-fast-dss unchanged; ``None`` (default) leaves the
                installed engine's own default. The ``java`` backend does not use
                it. See ``DssCore.write_timeseries``.

        Returns:
            Path to the DSS file

        Raises:
            ValueError: Invalid pathname, times or values, or a version mismatch

        Example:
            >>> import pandas as pd
            >>> times = pd.date_range("2020-01-01 01:00", periods=3, freq="h")
            >>> HmsDss.write_timeseries("obs.dss", "//GAGE 1/FLOW//1HOUR/OBS/",
            ...                         times, [10.0, 12.5, 11.0])
        """
        return DssCore.write_timeseries(dss_file, pathname, times, values, units,
                                        data_type, dss_version, sync=sync)

    # ------------------------------------------------------------------
    # Engine-only operations (ras-commander-fast-dss on every backend)
    # ------------------------------------------------------------------

    @staticmethod
    def _existing_file(dss_file: Union[str, Path]) -> Path:
        dss_path = Path(dss_file)
        if not dss_path.exists():
            raise FileNotFoundError(f"DSS file not found: {dss_path}")
        if not dss_path.is_file():
            raise IsADirectoryError(f"DSS path is not a file: {dss_path}")
        return dss_path.resolve()

    @staticmethod
    @log_call
    def repair(src: Union[str, Path], dest: Union[str, Path], *,
               sync: Optional[Any] = None) -> Dict[str, Any]:
        """
        Copy the readable records of a damaged DSS7 file into a new DSS7 file.

        A thin wrapper around ``ras_commander_fast_dss.repair``. It always runs on the
        native engine, whatever ``HmsDss.backend`` is; there is no Java equivalent.
        ``src`` is opened read-only and never written. The engine copies each readable
        record its discovery procedure reaches, reads the new file back, verifies
        every copied record against its source, and then publishes ``dest``.

        **A partial recovery is still published.** Always check ``result["complete"]``
        and ``result["not_copied"]``. ``complete`` covers only what the discovery
        procedure reached; it is not an integrity certificate for ``src``. A warning
        is logged when ``complete`` is False.

        Args:
            src: Existing DSS7 file to recover from
            dest: New file to create. It must not exist; nothing is replaced.
            sync: Flush policy, passed to the engine unchanged; ``None`` (default)
                leaves the installed engine's own default. In ras-commander-fast-dss
                0.1.2 the new file is built under a temporary name and flushed once
                before it is verified and published (``"end"``, the default, and
                ``"step"``); ``"none"`` does not flush it.

        Returns:
            The engine's result dict unchanged, including ``records_copied``,
            ``not_copied`` (``(pathname, reason)`` pairs), ``ledger``,
            ``src_listed_records``, ``src_interrupted_write`` and ``complete``

        Raises:
            FileNotFoundError: If ``src`` does not exist
            FileExistsError: If ``dest`` already exists
            ImportError: If ras-commander-fast-dss is not installed
            DssCapabilityError: If the installed engine has no ``repair``

        Example:
            >>> result = HmsDss.repair("damaged.dss", "recovered.dss")
            >>> if not result["complete"]:
            ...     for pathname, reason in result["not_copied"]:
            ...         print(pathname, reason)
        """
        src_path = HmsDss._existing_file(src)
        dest_path = Path(dest)
        if dest_path.exists():
            raise FileExistsError(f"repair destination already exists: {dest_path}")
        function = _backend.require_engine_function("repair", _backend.NATIVE_REPAIR_FEATURE)
        result = dict(function(src_path, dest_path,
                               **_backend.engine_sync_kwargs(function, sync, "repair")))
        if not result.get("complete", False):
            logger.warning(
                "DSS repair of %s into %s is incomplete: %d record(s) not copied; "
                "check result['not_copied']",
                src_path, dest_path, len(result.get("not_copied") or ()),
            )
        return result

    @staticmethod
    @log_call
    def read_paired_data_all(
        dss_file: Union[str, Path],
        pathname: str,
        *,
        ignore_d_part: bool = True,
        dtype: str = "stored",
    ) -> Any:
        """
        Read one paired-data record with every curve.

        ``read_paired_data`` returns the HMS dict, which holds curve 0 only. This
        method is a thin wrapper around ``ras_commander_fast_dss.read_paired_data``
        and returns its ``PairedData`` unchanged. It always runs on the native
        engine, whatever ``HmsDss.backend`` is.

        Args:
            dss_file: Existing DSS file. It is never created or modified.
            pathname: Pathname of the paired-data record
            ignore_d_part: Match a record whose D part differs when the exact
                pathname is not found (default True)
            dtype: ``"stored"`` (default) keeps the stored width; ``"float64"``
                converts

        Returns:
            The engine's ``PairedData``: ``ordinates``, ``values`` (shape
            ``(n_curves, n_ordinates)``), ``n_curves``, ``curve(i)``, ``labels``, ``units_independent``,
            ``units_dependent``, ``type_independent``, ``type_dependent``,
            ``x_precision``, ``y_precision`` and ``to_dataframe()``

        Raises:
            FileNotFoundError: If ``dss_file`` does not exist
            ImportError: If ras-commander-fast-dss is not installed
            ValueError: No record for ``pathname`` (the engine's
                ``DssPathnameNotFoundError``)
            RuntimeError: The record is not paired data (the engine's
                ``DssUnsupportedRecordError``)

        Example:
            >>> pd_all = HmsDss.read_paired_data_all("tables.dss", "//DAM/ELEV-STOR-AREA///TABLE/")
            >>> frame = pd_all.to_dataframe()      # index: ordinates; one column per curve
        """
        dss_path = HmsDss._existing_file(dss_file)
        function = _backend.require_engine_function("read_paired_data")
        return function(dss_path, pathname, ignore_d_part=ignore_d_part, dtype=dtype)

    @staticmethod
    @log_call
    def read_profile(
        dss_file: Union[str, Path],
        pathname: str,
        start_date: Optional[Any] = None,
        end_date: Optional[Any] = None,
        *,
        raw: bool = False,
        trim_missing: bool = True,
    ) -> Any:
        """
        Read a regular-interval profile dataset (DSS7 record types 102 and 107).

        A thin wrapper around ``ras_commander_fast_dss.read_profile``; it always runs
        on the native engine, whatever ``HmsDss.backend`` is.

        Args:
            dss_file: Existing DSS file. It is never created or modified.
            pathname: ``/A/B/C/D/E/F/`` with any D part: the whole dataset is read
            start_date: Optional inclusive window start
            end_date: Optional inclusive window end
            raw: Keep HEC missing markers as stored instead of ``NaN``
            trim_missing: Remove leading and trailing rows whose every depth is
                missing (default)

        Returns:
            The engine's ``Profile`` unchanged: ``times``, ``depths``, ``values``
            (``n_times`` by ``n_depths``), ``depth_units``, ``value_units``,
            ``quality`` and ``to_dataframe()``

        Raises:
            FileNotFoundError: If ``dss_file`` does not exist
            ImportError: If ras-commander-fast-dss is not installed
            ValueError: No data for ``pathname``
            RuntimeError: The record is not a regular profile (a scalar time series,
                an irregular profile 112/117, any DSS6 record)

        Example:
            >>> profile = HmsDss.read_profile("lake.dss", "/LAKE/DAM/TEMP-WATER//1Day/OBS/")
            >>> frame = profile.to_dataframe()
        """
        dss_path = HmsDss._existing_file(dss_file)
        function = _backend.require_engine_function("read_profile")
        return function(dss_path, pathname, start_date, end_date,
                        raw=raw, trim_missing=trim_missing)

    @staticmethod
    @log_call
    def write_profile(
        dss_file: Union[str, Path],
        pathname: str,
        depths: Any,
        values: Any,
        *,
        start: Any,
        depth_units: str,
        value_units: str,
        data_type: str,
        sync: Optional[Any] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Store a regular-interval profile (values by time and depth) in a DSS7 file.

        A thin wrapper around ``ras_commander_fast_dss.write_profile``; it always runs
        on the native engine, whatever ``HmsDss.backend`` is. Profiles exist only in
        DSS7.

        Args:
            dss_file: DSS7 file. A missing file is created as DSS7, and removed
                again if the write fails.
            pathname: ``/A/B/C/D/E/F/``; E is a standard regular interval and D is
                replaced for each block
            depths: The depth axis, 1-D, ``n_depths`` values
            values: 2-D, shape ``(n_times, n_depths)``. Never flattened or reshaped.
            start: Time of the first row; the rows follow at the E-part interval
            depth_units: Units of the depth axis
            value_units: Units of the values
            data_type: HEC data type (``INST-VAL``, ``PER-AVER``, ...)
            sync: Flush policy, passed to the engine unchanged; ``None`` (default)
                leaves the installed engine's own default
            **kwargs: Other ``ras_commander_fast_dss.write_profile`` options, passed
                unchanged (``quality``, ``time_zone``, ``precision``,
                ``value_type``, ``raw``, ``allow_undetectable_readers``)

        Returns:
            The engine's report dict unchanged

        Raises:
            ValueError: An existing file is not DSS7, or the engine refuses the input
            ImportError: If ras-commander-fast-dss is not installed
            DssCapabilityError: The installed engine does not advertise
                ``write_profile``

        Example:
            >>> HmsDss.write_profile(
            ...     "lake.dss", "/LAKE/DAM/TEMP-WATER//1Day/OBS/",
            ...     depths=[0.0, 5.0, 10.0], values=temperatures,
            ...     start="01JAN2024 2400", depth_units="ft", value_units="DEG F",
            ...     data_type="INST-VAL",
            ... )
        """
        function = _backend.require_engine_function(
            "write_profile", _backend.NATIVE_PROFILE_WRITE_FEATURE)
        dc = _backend.require_native_writes()
        target, version, existed, created = DssCore._native_write_target(dss_file, 7)
        with DssCore._native_new_file(dc, target, version, existed, created):
            return function(
                str(target), pathname, depths, values, start=start,
                depth_units=depth_units, value_units=value_units, data_type=data_type,
                **_backend.native_sync_kwargs(sync), **kwargs,
            )

    @staticmethod
    @log_call
    def read_location(dss_file: Union[str, Path], pathname: str) -> Any:
        """
        Read a DSS7 location record (``/A/B/Location Info////``).

        A thin wrapper around ``ras_commander_fast_dss.read_location``; it always runs
        on the native engine. Use ``read_associated_location`` for the location of a
        data record.

        Args:
            dss_file: Existing DSS7 file. It is never created or modified.
            pathname: Pathname of the location record

        Returns:
            The engine's ``Location`` unchanged (``x``, ``y``, ``z``, coordinate
            system, units and datum codes and names, ``time_zone``,
            ``supplemental``; ``to_dict()``)

        Raises:
            FileNotFoundError: If ``dss_file`` does not exist
            ImportError: If ras-commander-fast-dss is not installed
            ValueError: The record does not exist
            RuntimeError: The record is not a location record, or the file is DSS6
        """
        dss_path = HmsDss._existing_file(dss_file)
        return _backend.require_engine_function("read_location")(dss_path, pathname)

    @staticmethod
    @log_call
    def read_associated_location(dss_file: Union[str, Path], pathname: str) -> Optional[Any]:
        """
        Return the location stored for a data record, or None when there is none.

        A thin wrapper around ``ras_commander_fast_dss.read_associated_location``; it
        always runs on the native engine. DSS7: the location record built from the A
        and B parts of ``pathname``. DSS6: the coordinates in the time-series
        record's own header.

        Args:
            dss_file: Existing DSS file. It is never created or modified.
            pathname: Pathname of the data record (any D part)

        Returns:
            The engine's ``Location``, or None

        Raises:
            FileNotFoundError: If ``dss_file`` does not exist
            ImportError: If ras-commander-fast-dss is not installed
        """
        dss_path = HmsDss._existing_file(dss_file)
        return _backend.require_engine_function("read_associated_location")(dss_path, pathname)

    @staticmethod
    @log_call
    def write_location(
        dss_file: Union[str, Path],
        pathname: str,
        *,
        sync: Optional[Any] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Store location data (coordinates, datums, supplemental text) for a pathname.

        A thin wrapper around ``ras_commander_fast_dss.write_location``; it always runs
        on the native engine, whatever ``HmsDss.backend`` is. DSS7 stores the record
        ``/A/B/Location Info////``. DSS6 rewrites the header of every block of the
        time series named by ``pathname``, which must exist.

        Args:
            dss_file: Existing DSS6 or DSS7 file. This method does not create files.
            pathname: DSS7: any pathname of the location (A and B are used). DSS6: a
                time-series pathname.
            sync: Flush policy, passed to the engine unchanged; ``None`` (default)
                leaves the installed engine's own default
            **kwargs: The ``ras_commander_fast_dss.write_location`` fields, passed
                unchanged: ``x``, ``y``, ``z``, ``coordinate_system``,
                ``coordinate_id``, ``horizontal_units``, ``horizontal_datum``,
                ``vertical_units``, ``vertical_datum``, ``time_zone`` (DSS7),
                ``supplemental``, ``keep_existing``. Supplemental text is
                informational: a datum named in it is never applied to values.

        Returns:
            The engine's report dict unchanged

        Raises:
            FileNotFoundError: If ``dss_file`` does not exist
            ImportError: If ras-commander-fast-dss is not installed
            DssCapabilityError: The installed engine does not advertise
                ``write_location``

        Example:
            >>> HmsDss.write_location("gages.dss", "//GAGE 1/FLOW//1HOUR/OBS/",
            ...                       x=-90.07, y=29.95, z=3.2)
        """
        dss_path = HmsDss._existing_file(dss_file)
        function = _backend.require_engine_function(
            "write_location", _backend.NATIVE_LOCATION_WRITE_FEATURE)
        return function(str(dss_path), pathname,
                        **_backend.native_sync_kwargs(sync), **kwargs)

get_backend() staticmethod

DSS backend for the next call: "java", "native" or "shadow".

HMS_COMMANDER_DSS_BACKEND overrides HmsDss.backend. shadow without the engine runs Java only and logs one warning.

Raises:

Type Description
ValueError

If the backend name is invalid

ImportError

If native is requested and ras_commander_fast_dss is not installed (or fails to load)

Example

HmsDss.backend = "native" HmsDss.get_backend() 'native'

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_backend() -> str:
    """
    DSS backend for the next call: ``"java"``, ``"native"`` or ``"shadow"``.

    ``HMS_COMMANDER_DSS_BACKEND`` overrides ``HmsDss.backend``. ``shadow``
    without the engine runs Java only and logs one warning.

    Raises:
        ValueError: If the backend name is invalid
        ImportError: If ``native`` is requested and ras_commander_fast_dss is
            not installed (or fails to load)

    Example:
        >>> HmsDss.backend = "native"
        >>> HmsDss.get_backend()
        'native'
    """
    return DssCore.get_backend()

get_capabilities() staticmethod

Backend support per DSS operation.

Returns:

Type Description
DataFrame

DataFrame with columns operation, java, native, shadow

DataFrame

and note. Values: yes; gated (needs a qualified or

DataFrame

writer-capable engine). attrs report requested_backend,

DataFrame

native_available, native_writes_available,

DataFrame

native_grid_qualified, native_gridded_import_available,

DataFrame

native_write_sync_available (the writers take sync=) and

DataFrame

engine_features.

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_capabilities() -> pd.DataFrame:
    """
    Backend support per DSS operation.

    Returns:
        DataFrame with columns ``operation``, ``java``, ``native``, ``shadow``
        and ``note``. Values: ``yes``; ``gated`` (needs a qualified or
        writer-capable engine). ``attrs`` report ``requested_backend``,
        ``native_available``, ``native_writes_available``,
        ``native_grid_qualified``, ``native_gridded_import_available``,
        ``native_write_sync_available`` (the writers take ``sync=``) and
        ``engine_features``.
    """
    df = pd.DataFrame(list(_backend.CAPABILITIES),
                      columns=["operation", "java", "native", "shadow", "note"])
    try:
        requested = _backend.requested_backend(HmsDss.backend)
    except ValueError as exc:
        requested = f"invalid: {exc}"
    df.attrs.update(
        requested_backend=requested,
        native_available=_backend.native_available(),
        native_writes_available=_backend.native_writes_available(),
        native_grid_qualified=_backend.native_grid_qualified(),
        native_gridded_import_available=_backend.native_gridded_import_available(),
        native_write_sync_available=_backend.native_sync_available(),
        engine_features=sorted(_backend.engine_features()),
    )
    return df

get_shadow_summary(reset=False) staticmethod

Counts of shadow comparisons as {"operation|outcome|label": n}.

Parameters:

Name Type Description Default
reset bool

Clear the counters and records after reading them

False
Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_shadow_summary(reset: bool = False) -> Dict[str, int]:
    """
    Counts of shadow comparisons as ``{"operation|outcome|label": n}``.

    Args:
        reset: Clear the counters and records after reading them
    """
    result = _backend.summary()
    if reset:
        _backend.reset_shadow_stats()
    return result

is_available() staticmethod

Check if full DSS functionality is available.

Returns:

Type Description
bool

True if the selected backend can run: native needs the

bool

ras_commander_fast_dss engine; java needs pyjnius; shadow

bool

needs the engine (it falls back to java without it)

Example

if HmsDss.is_available(): ... catalog = HmsDss.get_catalog("file.dss") ... else: ... print("Install pyjnius: pip install pyjnius")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def is_available() -> bool:
    """
    Check if full DSS functionality is available.

    Returns:
        True if the selected backend can run: ``native`` needs the
        ras_commander_fast_dss engine; ``java`` needs pyjnius; ``shadow``
        needs the engine (it falls back to ``java`` without it)

    Example:
        >>> if HmsDss.is_available():
        ...     catalog = HmsDss.get_catalog("file.dss")
        ... else:
        ...     print("Install pyjnius: pip install pyjnius")
    """
    if not DSS_AVAILABLE:
        return False
    return DssCore.is_available()

get_catalog(dss_file) staticmethod

Get catalog of all paths in a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required

Returns:

Type Description
List[str]

List of DSS pathnames

Example

paths = HmsDss.get_catalog("results.dss") for path in paths: ... print(path)

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_catalog(
    dss_file: Union[str, Path]
) -> List[str]:
    """
    Get catalog of all paths in a DSS file.

    Args:
        dss_file: Path to the DSS file

    Returns:
        List of DSS pathnames

    Example:
        >>> paths = HmsDss.get_catalog("results.dss")
        >>> for path in paths:
        ...     print(path)
    """
    dss_file = Path(dss_file)

    if not dss_file.exists():
        raise FileNotFoundError(f"DSS file not found: {dss_file}")

    if not DSS_AVAILABLE:
        raise ImportError(
            "DSS functionality requires pyjnius.\n"
            "Install with: pip install pyjnius\n"
            "Also requires Java 8+ (JRE or JDK)"
        )

    return DssCore.get_catalog(dss_file)

read_timeseries(dss_file, pathname, start_date=None, end_date=None) staticmethod

Read a time series from a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required
pathname str

DSS pathname to read

required
start_date Optional[Any]

Optional inclusive lower bound on the returned stamps

None
end_date Optional[Any]

Optional inclusive upper bound on the returned stamps

None

Returns:

Type Description
DataFrame

DataFrame with:

DataFrame
  • DatetimeIndex for time series operations
DataFrame
  • 'datetime' column for plotting (same as index)
DataFrame
  • 'value' column with time series data
DataFrame
  • Metadata via df.attrs: pathname, units, type, interval
Example

ts = HmsDss.read_timeseries( ... "results.dss", ... "/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/" ... ) print(ts.head()) print(f"Units: {ts.attrs['units']}")

Plotting options:

ax.plot(ts['datetime'], ts['value']) # Using datetime column ax.plot(ts.index, ts['value']) # Using DatetimeIndex ts.plot(y='value') # Pandas automatic

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_timeseries(
    dss_file: Union[str, Path],
    pathname: str,
    start_date: Optional[Any] = None,
    end_date: Optional[Any] = None
) -> pd.DataFrame:
    """
    Read a time series from a DSS file.

    Args:
        dss_file: Path to the DSS file
        pathname: DSS pathname to read
        start_date: Optional inclusive lower bound on the returned stamps
        end_date: Optional inclusive upper bound on the returned stamps

    Returns:
        DataFrame with:
        - DatetimeIndex for time series operations
        - 'datetime' column for plotting (same as index)
        - 'value' column with time series data
        - Metadata via df.attrs: pathname, units, type, interval

    Example:
        >>> ts = HmsDss.read_timeseries(
        ...     "results.dss",
        ...     "/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/"
        ... )
        >>> print(ts.head())
        >>> print(f"Units: {ts.attrs['units']}")
        >>>
        >>> # Plotting options:
        >>> ax.plot(ts['datetime'], ts['value'])    # Using datetime column
        >>> ax.plot(ts.index, ts['value'])          # Using DatetimeIndex
        >>> ts.plot(y='value')                      # Pandas automatic
    """
    dss_file = Path(dss_file)

    if not dss_file.exists():
        raise FileNotFoundError(f"DSS file not found: {dss_file}")

    if not DSS_AVAILABLE:
        raise ImportError(
            "DSS functionality requires pyjnius.\n"
            "Install with: pip install pyjnius"
        )

    return DssCore.read_timeseries(dss_file, pathname, start_date, end_date)

read_multiple_timeseries(dss_file, pathnames) staticmethod

Read multiple time series from a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required
pathnames List[str]

List of DSS pathnames to read

required

Returns:

Type Description
Dict[str, DataFrame]

Dictionary mapping pathnames to DataFrames (None on failure)

Example

paths = ["/BASIN/SUB1/FLOW//15MIN/RUN1/", "/BASIN/SUB2/FLOW//15MIN/RUN1/"] data = HmsDss.read_multiple_timeseries("results.dss", paths) for path, df in data.items(): ... if df is not None: ... print(f"{path}: {len(df)} points")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_multiple_timeseries(
    dss_file: Union[str, Path],
    pathnames: List[str]
) -> Dict[str, pd.DataFrame]:
    """
    Read multiple time series from a DSS file.

    Args:
        dss_file: Path to the DSS file
        pathnames: List of DSS pathnames to read

    Returns:
        Dictionary mapping pathnames to DataFrames (None on failure)

    Example:
        >>> paths = ["/BASIN/SUB1/FLOW//15MIN/RUN1/", "/BASIN/SUB2/FLOW//15MIN/RUN1/"]
        >>> data = HmsDss.read_multiple_timeseries("results.dss", paths)
        >>> for path, df in data.items():
        ...     if df is not None:
        ...         print(f"{path}: {len(df)} points")
    """
    dss_file = Path(dss_file)

    if not DSS_AVAILABLE:
        raise ImportError("DSS functionality requires pyjnius.")

    return DssCore.read_multiple_timeseries(dss_file, pathnames)

extract_hms_results(dss_file, element_names=None, result_type='flow', run_name=None) staticmethod

Extract HMS simulation results from a DSS file.

This is a convenience method that filters results by element name and result type.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required
element_names Optional[List[str]]

List of element names to extract (all if None)

None
result_type str

Type of result ("flow", "precipitation", "stage", etc.)

'flow'
run_name Optional[str]

Optional F-part run name filter

None

Returns:

Type Description
Dict[str, DataFrame]

Dictionary mapping element names to result DataFrames

Example

results = HmsDss.extract_hms_results( ... "results.dss", ... element_names=["Outlet", "Junction-1"], ... result_type="flow" ... ) for name, df in results.items(): ... print(f"{name}: peak = {df['value'].max():.2f}")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def extract_hms_results(
    dss_file: Union[str, Path],
    element_names: Optional[List[str]] = None,
    result_type: str = "flow",
    run_name: Optional[str] = None,
) -> Dict[str, pd.DataFrame]:
    """
    Extract HMS simulation results from a DSS file.

    This is a convenience method that filters results by element name
    and result type.

    Args:
        dss_file: Path to the DSS file
        element_names: List of element names to extract (all if None)
        result_type: Type of result ("flow", "precipitation", "stage", etc.)
        run_name: Optional F-part run name filter

    Returns:
        Dictionary mapping element names to result DataFrames

    Example:
        >>> results = HmsDss.extract_hms_results(
        ...     "results.dss",
        ...     element_names=["Outlet", "Junction-1"],
        ...     result_type="flow"
        ... )
        >>> for name, df in results.items():
        ...     print(f"{name}: peak = {df['value'].max():.2f}")
    """
    dss_file = Path(dss_file)

    if not DSS_AVAILABLE:
        raise ImportError("DSS functionality requires pyjnius.")

    catalog = HmsDss.get_catalog(dss_file)
    matching_paths = select_result_paths(
        catalog,
        result_type=result_type,
        element_names=element_names,
        run_name=run_name,
        exclude_tables=True,
        result_patterns=HmsDss.HMS_RESULT_PATTERNS,
    )

    # Read matching time series
    results = {}
    for path in matching_paths:
        parts = parse_pathname(path)
        element_name = parts["element_name"]
        try:
            df = HmsDss.read_timeseries(dss_file, path)
            results[element_name] = df
        except Exception as e:
            logger.warning(f"Could not read {path}: {e}")

    logger.info(f"Extracted {len(results)} result time series")
    return results

get_info(dss_file) staticmethod

Get summary information about a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required

Returns:

Type Description
Dict[str, Any]

Dictionary with file information including path count and data types

Example

info = HmsDss.get_info("results.dss") print(f"Total paths: {info['num_paths']}") print(f"Data types: {info['path_types']}")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_info(
    dss_file: Union[str, Path]
) -> Dict[str, Any]:
    """
    Get summary information about a DSS file.

    Args:
        dss_file: Path to the DSS file

    Returns:
        Dictionary with file information including path count and data types

    Example:
        >>> info = HmsDss.get_info("results.dss")
        >>> print(f"Total paths: {info['num_paths']}")
        >>> print(f"Data types: {info['path_types']}")
    """
    dss_file = Path(dss_file)

    info = {
        'file_path': str(dss_file),
        'file_exists': dss_file.exists(),
        'file_size_mb': None,
        'num_paths': None,
        'path_types': {},
        'dss_available': DSS_AVAILABLE
    }

    if dss_file.exists():
        info['file_size_mb'] = round(dss_file.stat().st_size / (1024 * 1024), 2)

        if DSS_AVAILABLE:
            try:
                catalog = HmsDss.get_catalog(dss_file)
                info['num_paths'] = len(catalog)

                # Categorize paths by C-part
                for path in catalog:
                    parts = path.split('/')
                    if len(parts) >= 4:
                        data_type = parts[3]  # C part
                        info['path_types'][data_type] = info['path_types'].get(data_type, 0) + 1

            except Exception as e:
                logger.warning(f"Could not read DSS catalog: {e}")

    return info

list_flow_results(dss_file) staticmethod

List all flow result pathnames in a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required

Returns:

Type Description
List[str]

List of flow result pathnames

Example

flows = HmsDss.list_flow_results("results.dss") for path in flows: ... parts = HmsDss.parse_dss_pathname(path) ... print(f"{parts['element_name']}: {path}")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def list_flow_results(
    dss_file: Union[str, Path]
) -> List[str]:
    """
    List all flow result pathnames in a DSS file.

    Args:
        dss_file: Path to the DSS file

    Returns:
        List of flow result pathnames

    Example:
        >>> flows = HmsDss.list_flow_results("results.dss")
        >>> for path in flows:
        ...     parts = HmsDss.parse_dss_pathname(path)
        ...     print(f"{parts['element_name']}: {path}")
    """
    catalog = HmsDss.get_catalog(dss_file)
    return select_result_paths(
        catalog,
        result_type="flow",
        exclude_tables=False,
        result_patterns=HmsDss.HMS_RESULT_PATTERNS,
    )

list_precipitation_data(dss_file) staticmethod

List all precipitation data pathnames in a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required

Returns:

Type Description
List[str]

List of precipitation pathnames

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def list_precipitation_data(
    dss_file: Union[str, Path]
) -> List[str]:
    """
    List all precipitation data pathnames in a DSS file.

    Args:
        dss_file: Path to the DSS file

    Returns:
        List of precipitation pathnames
    """
    catalog = HmsDss.get_catalog(dss_file)
    return select_result_paths(
        catalog,
        result_type="precipitation",
        exclude_tables=False,
        result_patterns=HmsDss.HMS_RESULT_PATTERNS,
    )

list_stage_results(dss_file) staticmethod

List all stage result pathnames in a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required

Returns:

Type Description
List[str]

List of stage result pathnames

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def list_stage_results(
    dss_file: Union[str, Path]
) -> List[str]:
    """
    List all stage result pathnames in a DSS file.

    Args:
        dss_file: Path to the DSS file

    Returns:
        List of stage result pathnames
    """
    catalog = HmsDss.get_catalog(dss_file)
    return select_result_paths(
        catalog,
        result_type="stage",
        exclude_tables=False,
        result_patterns=HmsDss.HMS_RESULT_PATTERNS,
    )

list_storage_results(dss_file) staticmethod

List all storage result pathnames in a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required

Returns:

Type Description
List[str]

List of storage result pathnames

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def list_storage_results(
    dss_file: Union[str, Path]
) -> List[str]:
    """
    List all storage result pathnames in a DSS file.

    Args:
        dss_file: Path to the DSS file

    Returns:
        List of storage result pathnames
    """
    catalog = HmsDss.get_catalog(dss_file)
    return select_result_paths(
        catalog,
        result_type="storage",
        exclude_tables=False,
        result_patterns=HmsDss.HMS_RESULT_PATTERNS,
    )

parse_dss_pathname(pathname) staticmethod

Parse a DSS pathname into its component parts.

DSS pathnames have format: /A/B/C/D/E/F/ - A: Basin/Project identifier - B: Location/Element name - C: Data type (FLOW, PRECIP, etc.) - D: Date/Time block - E: Time interval - F: Version/Run identifier

Parameters:

Name Type Description Default
pathname str

DSS pathname string

required

Returns:

Type Description
Dict[str, str]

Dictionary with pathname components including convenience fields

Example

parts = HmsDss.parse_dss_pathname("/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/") print(parts['element_name']) # 'OUTLET' print(parts['data_type']) # 'FLOW' print(parts['run_name']) # 'RUN1'

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def parse_dss_pathname(pathname: str) -> Dict[str, str]:
    """
    Parse a DSS pathname into its component parts.

    DSS pathnames have format: /A/B/C/D/E/F/
    - A: Basin/Project identifier
    - B: Location/Element name
    - C: Data type (FLOW, PRECIP, etc.)
    - D: Date/Time block
    - E: Time interval
    - F: Version/Run identifier

    Args:
        pathname: DSS pathname string

    Returns:
        Dictionary with pathname components including convenience fields

    Example:
        >>> parts = HmsDss.parse_dss_pathname("/BASIN/OUTLET/FLOW//15MIN/RUN:RUN1/")
        >>> print(parts['element_name'])  # 'OUTLET'
        >>> print(parts['data_type'])     # 'FLOW'
        >>> print(parts['run_name'])      # 'RUN1'
    """
    return parse_pathname(pathname)

create_dss_pathname(basin, element, data_type, interval, run_name='', date_block='') staticmethod

Create a DSS pathname from components.

Parameters:

Name Type Description Default
basin str

Basin/Project name (A part)

required
element str

Element name (B part)

required
data_type str

Data type like FLOW, PRECIP (C part)

required
interval str

Time interval like 15MIN, 1HOUR (E part)

required
run_name str

Run identifier (F part)

''
date_block str

Date block (D part, usually empty)

''

Returns:

Type Description
str

Formatted DSS pathname

Example

path = HmsDss.create_dss_pathname( ... "MYBASIN", "OUTLET", "FLOW", "15MIN", "RUN1" ... ) print(path) # '/MYBASIN/OUTLET/FLOW//15MIN/RUN:RUN1/'

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def create_dss_pathname(
    basin: str,
    element: str,
    data_type: str,
    interval: str,
    run_name: str = "",
    date_block: str = ""
) -> str:
    """
    Create a DSS pathname from components.

    Args:
        basin: Basin/Project name (A part)
        element: Element name (B part)
        data_type: Data type like FLOW, PRECIP (C part)
        interval: Time interval like 15MIN, 1HOUR (E part)
        run_name: Run identifier (F part)
        date_block: Date block (D part, usually empty)

    Returns:
        Formatted DSS pathname

    Example:
        >>> path = HmsDss.create_dss_pathname(
        ...     "MYBASIN", "OUTLET", "FLOW", "15MIN", "RUN1"
        ... )
        >>> print(path)  # '/MYBASIN/OUTLET/FLOW//15MIN/RUN:RUN1/'
    """
    return create_pathname(basin, element, data_type, interval, run_name, date_block)

filter_catalog(catalog, pattern=None, data_type=None, element=None) staticmethod

Filter DSS catalog by pattern or components.

Parameters:

Name Type Description Default
catalog List[str]

List of DSS pathnames

required
pattern Optional[str]

Regex pattern to match against full pathname

None
data_type Optional[str]

Filter by C-part (e.g., "FLOW", "PRECIP")

None
element Optional[str]

Filter by B-part (element/location name)

None

Returns:

Type Description
List[str]

Filtered list of pathnames

Example

paths = HmsDss.get_catalog("file.dss") flow_paths = HmsDss.filter_catalog(paths, data_type="FLOW") outlet_flows = HmsDss.filter_catalog(flow_paths, element="OUTLET")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def filter_catalog(
    catalog: List[str],
    pattern: Optional[str] = None,
    data_type: Optional[str] = None,
    element: Optional[str] = None
) -> List[str]:
    """
    Filter DSS catalog by pattern or components.

    Args:
        catalog: List of DSS pathnames
        pattern: Regex pattern to match against full pathname
        data_type: Filter by C-part (e.g., "FLOW", "PRECIP")
        element: Filter by B-part (element/location name)

    Returns:
        Filtered list of pathnames

    Example:
        >>> paths = HmsDss.get_catalog("file.dss")
        >>> flow_paths = HmsDss.filter_catalog(paths, data_type="FLOW")
        >>> outlet_flows = HmsDss.filter_catalog(flow_paths, element="OUTLET")
    """
    return filter_catalog(catalog, pattern, data_type, element)

get_peak_flows(dss_file, element_names=None) staticmethod

Extract peak flow values for all elements.

Note

For large DSS files with many elements (100+), consider using get_peak_flows_batched() instead to avoid memory issues. That method processes elements in batches with garbage collection between batches.

Uses the total-flow records (C-part FLOW) only. Component and derived records such as FLOW-BASE or FLOW-CUMULATIVE (a volume) are not peak flows.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required
element_names Optional[List[str]]

Optional list of element names to filter

None

Returns:

Type Description
DataFrame

DataFrame with columns: element, peak_flow, peak_time, units

Example

peaks = HmsDss.get_peak_flows("results.dss") print(peaks.sort_values('peak_flow', ascending=False))

See Also

get_peak_flows_batched: Memory-efficient version for large files

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_peak_flows(
    dss_file: Union[str, Path],
    element_names: Optional[List[str]] = None
) -> pd.DataFrame:
    """
    Extract peak flow values for all elements.

    Note:
        For large DSS files with many elements (100+), consider using
        get_peak_flows_batched() instead to avoid memory issues. That method
        processes elements in batches with garbage collection between batches.

    Uses the total-flow records (C-part ``FLOW``) only. Component and
    derived records such as ``FLOW-BASE`` or ``FLOW-CUMULATIVE`` (a volume)
    are not peak flows.

    Args:
        dss_file: Path to the DSS file
        element_names: Optional list of element names to filter

    Returns:
        DataFrame with columns: element, peak_flow, peak_time, units

    Example:
        >>> peaks = HmsDss.get_peak_flows("results.dss")
        >>> print(peaks.sort_values('peak_flow', ascending=False))

    See Also:
        get_peak_flows_batched: Memory-efficient version for large files
    """
    results = HmsDss.extract_hms_results(dss_file, element_names, result_type="flow-total")

    records = []
    for element_name, df in results.items():
        if df is not None and not df.empty:
            peak_idx = df['value'].idxmax()
            records.append({
                'element': element_name,
                'peak_flow': df.loc[peak_idx, 'value'],
                'peak_time': peak_idx,
                'units': df.attrs.get('units', '')
            })

    return pd.DataFrame(records)

get_peak_flows_batched(dss_file, element_names=None, run_name=None, batch_size=50, progress=True) staticmethod

Extract peak flows in batches to avoid memory issues.

Processes N elements at a time, garbage collects between batches, preventing memory exhaustion for large DSS files.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to DSS file

required
element_names Optional[List[str]]

Optional filter for specific elements

None
run_name Optional[str]

Optional filter for specific run (e.g., "1%(100YR)RUN")

None
batch_size int

Elements to process per batch (default: 50)

50
progress bool

Show progress logging (default: True)

True

Returns:

Type Description
DataFrame

DataFrame with columns: - element: Element name - peak_flow: Peak flow value (cfs) - peak_time: Time of peak (datetime) - units: Engineering units - dss_path: Full DSS pathname

Memory: O(batch_size) instead of O(total_elements)

Example

Safe for 1000+ elements

peaks = HmsDss.get_peak_flows_batched( ... "results.dss", ... run_name="1%(100YR)RUN", ... batch_size=100 # Adjust for available memory ... )

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_peak_flows_batched(
    dss_file: Union[str, Path],
    element_names: Optional[List[str]] = None,
    run_name: Optional[str] = None,
    batch_size: int = 50,
    progress: bool = True
) -> pd.DataFrame:
    """
    Extract peak flows in batches to avoid memory issues.

    Processes N elements at a time, garbage collects between batches,
    preventing memory exhaustion for large DSS files.

    Args:
        dss_file: Path to DSS file
        element_names: Optional filter for specific elements
        run_name: Optional filter for specific run (e.g., "1%(100YR)RUN")
        batch_size: Elements to process per batch (default: 50)
        progress: Show progress logging (default: True)

    Returns:
        DataFrame with columns:
            - element: Element name
            - peak_flow: Peak flow value (cfs)
            - peak_time: Time of peak (datetime)
            - units: Engineering units
            - dss_path: Full DSS pathname

    Memory: O(batch_size) instead of O(total_elements)

    Example:
        >>> # Safe for 1000+ elements
        >>> peaks = HmsDss.get_peak_flows_batched(
        ...     "results.dss",
        ...     run_name="1%(100YR)RUN",
        ...     batch_size=100  # Adjust for available memory
        ... )
    """
    dss_file = Path(dss_file)

    if not dss_file.exists():
        raise FileNotFoundError(f"DSS file not found: {dss_file}")

    if not DSS_AVAILABLE:
        raise ImportError(
            "DSS functionality requires pyjnius.\n"
            "Install with: pip install pyjnius\n"
            "Also requires Java 8+ (JRE or JDK)"
        )

    catalog = HmsDss.get_catalog(dss_file)
    flow_paths = select_result_paths(
        catalog,
        result_type="flow-total",
        element_names=element_names,
        run_name=run_name,
        exclude_tables=True,
        result_patterns=HmsDss.HMS_RESULT_PATTERNS,
    )

    total_paths = len(flow_paths)
    if total_paths == 0:
        logger.info("No flow paths found in DSS file")
        return pd.DataFrame(columns=['element', 'peak_flow', 'peak_time', 'units', 'dss_path'])

    if progress:
        logger.info(f"Extracting peaks from {total_paths} paths...")

    records = []
    total_batches = (total_paths + batch_size - 1) // batch_size  # Ceiling division

    for i in range(0, total_paths, batch_size):
        batch_num = i // batch_size + 1
        batch_paths = flow_paths[i:i + batch_size]

        if progress:
            logger.info(f"Batch {batch_num}/{total_batches}: processing {len(batch_paths)} paths...")

        # Process each path in the batch
        for path in batch_paths:
            try:
                parts = HmsDss.parse_dss_pathname(path)

                # Use peak-only extraction (350x more memory efficient)
                peak_info = DssCore.get_peak_value(dss_file, path)

                if peak_info is not None:
                    records.append({
                        'element': parts['element_name'],
                        'peak_flow': peak_info['peak_flow'],
                        'peak_time': peak_info['peak_time'],
                        'units': peak_info['units'],
                        'dss_path': path
                    })

            except Exception as e:
                logger.warning(f"Could not read {path}: {e}")

        # Garbage collect after each batch to free memory
        gc.collect()

    # Create DataFrame from records
    result_df = pd.DataFrame(records)

    # Sort by peak_flow descending
    if not result_df.empty:
        result_df = result_df.sort_values('peak_flow', ascending=False).reset_index(drop=True)

    if progress:
        logger.info(f"Extracted peak flows for {len(result_df)} elements")
    return result_df

get_total_precipitation(dss_file, element_names=None) staticmethod

Calculate total precipitation for all elements.

Sums the interval precipitation depth (C-part PRECIP-INC, with PRECIP as a legacy fallback), one row per element and run. Cumulative series (PRECIP-CUM), losses, excess and spatial standard deviation are different quantities and are not summed.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required
element_names Optional[List[str]]

Optional list of element names to filter

None

Returns:

Type Description
DataFrame

DataFrame with columns: element, total_precip, units, num_intervals

Example

precip = HmsDss.get_total_precipitation("results.dss") print(precip)

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_total_precipitation(
    dss_file: Union[str, Path],
    element_names: Optional[List[str]] = None
) -> pd.DataFrame:
    """
    Calculate total precipitation for all elements.

    Sums the interval precipitation depth (C-part ``PRECIP-INC``, with
    ``PRECIP`` as a legacy fallback), one row per element and run.
    Cumulative series (``PRECIP-CUM``), losses, excess and spatial
    standard deviation are different quantities and are not summed.

    Args:
        dss_file: Path to the DSS file
        element_names: Optional list of element names to filter

    Returns:
        DataFrame with columns: element, total_precip, units, num_intervals

    Example:
        >>> precip = HmsDss.get_total_precipitation("results.dss")
        >>> print(precip)
    """
    catalog = HmsDss.get_catalog(dss_file)
    paths = select_interval_precip_paths(
        select_result_paths(
            catalog,
            result_type="precipitation",
            element_names=element_names,
            exclude_tables=True,
            result_patterns=HmsDss.HMS_RESULT_PATTERNS,
        )
    )

    records = []
    for path in paths:
        try:
            df = HmsDss.read_timeseries(dss_file, path)
        except Exception as e:
            logger.warning(f"Could not read {path}: {e}")
            continue
        if df is not None and not df.empty:
            records.append({
                'element': parse_pathname(path)['element_name'],
                'total_precip': df['value'].sum(),
                'units': df.attrs.get('units', ''),
                'num_intervals': len(df)
            })

    return pd.DataFrame(records)

write_paired_data(dss_file, pathname, x_values, y_values=None, x_units=None, y_units=None, x_type=None, y_type=None, labels=None, create_if_missing=True, *, x_precision=None, y_precision=None, value_type='auto', dss_version=None, sync=None, x_label=None, y_label=None) staticmethod

Write one paired-data record with one or more curves.

Used for Atlas 14 temporal distributions, rating curves and other X-Y relationships. The arguments are those of ras_commander.RasDss.write_paired_data; DssCore.write_paired_data documents each one, the backends and the refusals. A failed write raises. x_label and y_label are the earlier names of x_type and y_type. sync is the native writer's flush policy, passed to the engine unchanged; None (default) leaves the installed engine's own default (see DssCore.write_timeseries).

Returns:

Type Description
bool

True when the record is written and in the file catalog

Example

x = np.linspace(0, 24, 49) # Hours y = np.linspace(0, 1, 49) # Cumulative fraction HmsDss.write_paired_data( ... "temporal.dss", "//TX_R3/FIRST-QUARTILE/24HR//50%/", x, y, ... x_units="HOURS", y_units="FRACTION", x_type="TIME", y_type="CUMULATIVE", ... ) True

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def write_paired_data(
    dss_file: Union[str, Path],
    pathname: str,
    x_values: Any,
    y_values: Any = None,
    x_units: Optional[str] = None,
    y_units: Optional[str] = None,
    x_type: Optional[str] = None,
    y_type: Optional[str] = None,
    labels: Optional[Sequence[str]] = None,
    create_if_missing: bool = True,
    *,
    x_precision: Optional[int] = None,
    y_precision: Optional[int] = None,
    value_type: str = "auto",
    dss_version: Optional[int] = None,
    sync: Optional[Any] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
) -> bool:
    """
    Write one paired-data record with one or more curves.

    Used for Atlas 14 temporal distributions, rating curves and other X-Y
    relationships. The arguments are those of
    ``ras_commander.RasDss.write_paired_data``; ``DssCore.write_paired_data`` documents
    each one, the backends and the refusals. A failed write raises. ``x_label`` and
    ``y_label`` are the earlier names of ``x_type`` and ``y_type``. ``sync`` is the
    native writer's flush policy, passed to the engine unchanged; ``None`` (default)
    leaves the installed engine's own default (see ``DssCore.write_timeseries``).

    Returns:
        True when the record is written and in the file catalog

    Example:
        >>> x = np.linspace(0, 24, 49)  # Hours
        >>> y = np.linspace(0, 1, 49)   # Cumulative fraction
        >>> HmsDss.write_paired_data(
        ...     "temporal.dss", "//TX_R3/FIRST-QUARTILE/24HR//50%/", x, y,
        ...     x_units="HOURS", y_units="FRACTION", x_type="TIME", y_type="CUMULATIVE",
        ... )
        True
    """
    return DssCore.write_paired_data(
        dss_file, pathname, x_values, y_values, x_units, y_units, x_type, y_type, labels,
        create_if_missing, x_precision=x_precision, y_precision=y_precision,
        value_type=value_type, dss_version=dss_version, x_label=x_label, y_label=y_label,
        sync=sync,
    )

write_multiple_paired_data(dss_file, paired_data_records, *, sync=None) staticmethod

Write multiple paired data records to DSS file.

More efficient than calling write_paired_data repeatedly as it keeps the DSS file open for all writes.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to DSS file

required
paired_data_records List[Dict]

List of dicts with keys: - pathname: DSS pathname - x_values: numpy array of X values - y_values: numpy array of Y values - x_units: (optional) X units - y_units: (optional) Y units - x_label: (optional) X label - y_label: (optional) Y label

required

Returns:

Type Description
Dict[str, bool]

Dict mapping pathname to success status. True means the record was

Dict[str, bool]

written and found in the file catalog.

Raises:

Type Description
ValueError

If a pathname does not have exactly six parts, or two records share a pathname. Nothing is written in either case.

RuntimeError

If a write reported no error but its record is not in the file catalog afterwards

Example

records = [ ... {"pathname": "//TX_R3/FIRST-QUARTILE/24HR//50%/", ... "x_values": hours, "y_values": fractions_50}, ... {"pathname": "//TX_R3/FIRST-QUARTILE/24HR//90%/", ... "x_values": hours, "y_values": fractions_90}, ... ] results = HmsDss.write_multiple_paired_data("temporal.dss", records) print(f"Wrote {sum(results.values())} records")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def write_multiple_paired_data(
    dss_file: Union[str, Path],
    paired_data_records: List[Dict],
    *,
    sync: Optional[Any] = None,
) -> Dict[str, bool]:
    """
    Write multiple paired data records to DSS file.

    More efficient than calling write_paired_data repeatedly as it
    keeps the DSS file open for all writes.

    Args:
        dss_file: Path to DSS file
        paired_data_records: List of dicts with keys:
            - pathname: DSS pathname
            - x_values: numpy array of X values
            - y_values: numpy array of Y values
            - x_units: (optional) X units
            - y_units: (optional) Y units
            - x_label: (optional) X label
            - y_label: (optional) Y label

    Returns:
        Dict mapping pathname to success status. True means the record was
        written and found in the file catalog.

    Raises:
        ValueError: If a pathname does not have exactly six parts, or two
            records share a pathname. Nothing is written in either case.
        RuntimeError: If a write reported no error but its record is not
            in the file catalog afterwards

    Example:
        >>> records = [
        ...     {"pathname": "//TX_R3/FIRST-QUARTILE/24HR//50%/",
        ...      "x_values": hours, "y_values": fractions_50},
        ...     {"pathname": "//TX_R3/FIRST-QUARTILE/24HR//90%/",
        ...      "x_values": hours, "y_values": fractions_90},
        ... ]
        >>> results = HmsDss.write_multiple_paired_data("temporal.dss", records)
        >>> print(f"Wrote {sum(results.values())} records")
    """
    import numpy as np
    dss_file = Path(dss_file)

    if not DSS_AVAILABLE:
        raise ImportError(
            "DSS functionality requires pyjnius.\n"
            "Install with: pip install pyjnius"
        )

    # Convert values to numpy arrays if needed
    for record in paired_data_records:
        record['x_values'] = np.asarray(record['x_values'])
        record['y_values'] = np.asarray(record['y_values'])

    return DssCore.write_multiple_paired_data(dss_file, paired_data_records, sync=sync)

import_atlas14_temporal(dss_file, temporal_distributions, region_code, duration_hours=24, *, sync=None) staticmethod

Import Atlas 14 temporal distributions to DSS file.

Convenience method specifically for Atlas 14 temporal data. Writes one paired-data record per quartile and probability column with the pathname //{region_code}/{QUARTILE}/{duration}HR//{probability}/. For example, the 50% curve of the first quartile for region TX_R3 is //TX_R3/FIRST-QUARTILE/24HR//50%/.

Units are HOURS/FRACTION and the axis types TIME and CUMULATIVE. A DSS6 file stores at most 8 characters per type, so on DSS6 the Y type is CUMULATI: the value HEC Monolith stores there for CUMULATIVE. Both backends write the same record. New files are DSS7.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Output DSS file path

required
temporal_distributions Dict[str, DataFrame]

Dict mapping quartile names to DataFrames Each DataFrame should have: - Index: hours (0, 0.5, 1.0, ... 24.0) - Columns: probability strings ("90%", "80%", ..., "10%") - Values: cumulative percentages (0-100)

required
region_code str

Atlas 14 region code (e.g., "TX_R3")

required
duration_hours int

Storm duration in hours (default: 24)

24
sync Optional[Any]

Flush policy of the native writer, passed to ras-commander-fast-dss unchanged; None (default) leaves the installed engine's own default. The java backend does not use it. See DssCore.write_timeseries.

None

Returns:

Type Description
Dict[str, bool]

Dict mapping pathname to success status

Raises:

Type Description
ValueError

If a generated pathname is invalid (for example a region code that contains /) or two columns produce the same pathname

RuntimeError

If a write reported no error but its record is not in the file catalog afterwards

Example

Parse temporal CSV

temporal = parse_temporal_csv(csv_content)

Import to DSS

results = HmsDss.import_atlas14_temporal( ... "TX_R3_24H.dss", ... temporal, ... region_code="TX_R3", ... duration_hours=24 ... ) print(f"Imported {sum(results.values())}/45 distributions")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def import_atlas14_temporal(
    dss_file: Union[str, Path],
    temporal_distributions: Dict[str, 'pd.DataFrame'],
    region_code: str,
    duration_hours: int = 24,
    *,
    sync: Optional[Any] = None,
) -> Dict[str, bool]:
    """
    Import Atlas 14 temporal distributions to DSS file.

    Convenience method specifically for Atlas 14 temporal data.
    Writes one paired-data record per quartile and probability column with
    the pathname ``//{region_code}/{QUARTILE}/{duration}HR//{probability}/``.
    For example, the 50% curve of the first quartile for region ``TX_R3``
    is ``//TX_R3/FIRST-QUARTILE/24HR//50%/``.

    Units are ``HOURS``/``FRACTION`` and the axis types ``TIME`` and
    ``CUMULATIVE``. A DSS6 file stores at most 8 characters per type, so on
    DSS6 the Y type is ``CUMULATI``: the value HEC Monolith stores there for
    ``CUMULATIVE``. Both backends write the same record. New files are DSS7.

    Args:
        dss_file: Output DSS file path
        temporal_distributions: Dict mapping quartile names to DataFrames
            Each DataFrame should have:
            - Index: hours (0, 0.5, 1.0, ... 24.0)
            - Columns: probability strings ("90%", "80%", ..., "10%")
            - Values: cumulative percentages (0-100)
        region_code: Atlas 14 region code (e.g., "TX_R3")
        duration_hours: Storm duration in hours (default: 24)
        sync: Flush policy of the native writer, passed to
            ras-commander-fast-dss unchanged; ``None`` (default) leaves the
            installed engine's own default. The ``java`` backend does not use
            it. See ``DssCore.write_timeseries``.

    Returns:
        Dict mapping pathname to success status

    Raises:
        ValueError: If a generated pathname is invalid (for example a
            region code that contains ``/``) or two columns produce the
            same pathname
        RuntimeError: If a write reported no error but its record is not
            in the file catalog afterwards

    Example:
        >>> # Parse temporal CSV
        >>> temporal = parse_temporal_csv(csv_content)
        >>>
        >>> # Import to DSS
        >>> results = HmsDss.import_atlas14_temporal(
        ...     "TX_R3_24H.dss",
        ...     temporal,
        ...     region_code="TX_R3",
        ...     duration_hours=24
        ... )
        >>> print(f"Imported {sum(results.values())}/45 distributions")
    """
    import numpy as np

    dss_file = Path(dss_file)

    if not DSS_AVAILABLE:
        raise ImportError("DSS functionality requires pyjnius.")

    # Map quartile names to DSS-compatible names
    quartile_dss_names = {
        "First Quartile": "FIRST-QUARTILE",
        "Second Quartile": "SECOND-QUARTILE",
        "Third Quartile": "THIRD-QUARTILE",
        "Fourth Quartile": "FOURTH-QUARTILE",
        "All Cases": "ALL-CASES"
    }

    duration_str = f"{duration_hours}HR"
    records = []
    # DSS6 stores at most 8 characters per type; "CUMULATI" is what HEC
    # Monolith stores for "CUMULATIVE" there (the native writer refuses a
    # longer string rather than truncate it).
    y_type = "CUMULATIVE"
    if dss_file.exists() and DssCore.get_file_version(dss_file) == 6:
        y_type = "CUMULATIVE"[:DssCore.DSS6_TEXT_LIMIT]

    for quartile_name, df in temporal_distributions.items():
        dss_quartile = quartile_dss_names.get(quartile_name)
        if dss_quartile is None:
            logger.warning(f"Unknown quartile: {quartile_name}, skipping")
            continue

        x_values = np.array(df.index)  # Hours

        for prob_col in df.columns:
            # A=blank, B=region, C=quartile, D=duration, E=blank,
            # F=probability. Seven slashes: heclib drops any extra part,
            # which would put every probability on one record.
            pathname = f"//{region_code}/{dss_quartile}/{duration_str}//{prob_col}/"

            # Convert percentage to fraction
            y_values = df[prob_col].values / 100.0

            records.append({
                'pathname': pathname,
                'x_values': x_values,
                'y_values': y_values,
                'x_units': 'HOURS',
                'y_units': 'FRACTION',
                'x_label': 'TIME',
                'y_label': y_type
            })

    logger.info(f"Importing {len(records)} temporal distributions to {dss_file}")
    return DssCore.write_multiple_paired_data(dss_file, records, sync=sync)

read_paired_data(dss_file, pathname) staticmethod

Read paired data (X-Y curve) from DSS file.

This is used for reading rating curves, diversion tables, storage-flow relationships, and other X-Y paired data.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to DSS file

required
pathname str

DSS pathname for paired data (e.g., "//ELEMENT/FLOW-DIVERSION///TABLE/")

required

Returns:

Type Description
Optional[Dict[str, Any]]

Dictionary with: - x_values: numpy array of X values - y_values: numpy array of Y values - x_units: X axis units - y_units: Y axis units - x_label: X axis label - y_label: Y axis label - pathname: Original pathname

Optional[Dict[str, Any]]

Returns None if read fails

Example

data = HmsDss.read_paired_data( ... "paired_data.dss", ... "//T1011300_0000_D/FLOW-DIVERSION///TABLE/" ... ) print(f"Inflow values: {data['x_values']}") print(f"Diversion values: {data['y_values']}")

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_paired_data(
    dss_file: Union[str, Path],
    pathname: str
) -> Optional[Dict[str, Any]]:
    """
    Read paired data (X-Y curve) from DSS file.

    This is used for reading rating curves, diversion tables,
    storage-flow relationships, and other X-Y paired data.

    Args:
        dss_file: Path to DSS file
        pathname: DSS pathname for paired data (e.g., "//ELEMENT/FLOW-DIVERSION///TABLE/")

    Returns:
        Dictionary with:
            - x_values: numpy array of X values
            - y_values: numpy array of Y values
            - x_units: X axis units
            - y_units: Y axis units
            - x_label: X axis label
            - y_label: Y axis label
            - pathname: Original pathname
        Returns None if read fails

    Example:
        >>> data = HmsDss.read_paired_data(
        ...     "paired_data.dss",
        ...     "//T1011300_0000_D/FLOW-DIVERSION///TABLE/"
        ... )
        >>> print(f"Inflow values: {data['x_values']}")
        >>> print(f"Diversion values: {data['y_values']}")
    """
    dss_file = Path(dss_file)

    if not dss_file.exists():
        raise FileNotFoundError(f"DSS file not found: {dss_file}")

    if not DSS_AVAILABLE:
        raise ImportError(
            "DSS functionality requires pyjnius.\n"
            "Install with: pip install pyjnius\n"
            "Also requires Java 8+ (JRE or JDK)"
        )

    return DssCore.read_paired_data(dss_file, pathname)

get_file_version(dss_file) staticmethod

HEC-DSS version of an existing file: 6 or 7.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to an existing DSS file

required

Returns:

Type Description
int

6 or 7

Raises:

Type Description
FileNotFoundError

If the file does not exist

ValueError

If the file is not a DSS6 or DSS7 file

Example

HmsDss.get_file_version("results.dss") 6

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def get_file_version(dss_file: Union[str, Path]) -> int:
    """
    HEC-DSS version of an existing file: 6 or 7.

    Args:
        dss_file: Path to an existing DSS file

    Returns:
        6 or 7

    Raises:
        FileNotFoundError: If the file does not exist
        ValueError: If the file is not a DSS6 or DSS7 file

    Example:
        >>> HmsDss.get_file_version("results.dss")
        6
    """
    return DssCore.get_file_version(dss_file)

read_grid(dss_file, pathname) staticmethod

Read one grid record (HRAP, Albers/SHG or specified) from a DSS file.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file

required
pathname str

Full grid pathname, including its D and E parts

required

Returns:

Type Description
Dict[str, Any]

Dictionary with data (float32, shape (ny, nx), row 0 south,

Dict[str, Any]

missing cells NaN), pathname, dss_file, shape, units,

Dict[str, Any]

data_type, grid_type, cell_size, lower_left_cell,

Dict[str, Any]

cell_zero, origin, crs, start_time and end_time.

Dict[str, Any]

See DssCore.read_grid.

Raises:

Type Description
FileNotFoundError

If the file does not exist

ValueError

If the record does not exist or is not a grid

DssCapabilityError

With the native backend, when the engine does not advertise qualified grid CRS strings

Example

paths = HmsDss.get_catalog("hrap.dss") grid = HmsDss.read_grid("hrap.dss", paths[0]) print(grid["grid_type"], grid["shape"], grid["units"])

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_grid(
    dss_file: Union[str, Path],
    pathname: str
) -> Dict[str, Any]:
    """
    Read one grid record (HRAP, Albers/SHG or specified) from a DSS file.

    Args:
        dss_file: Path to the DSS file
        pathname: Full grid pathname, including its D and E parts

    Returns:
        Dictionary with ``data`` (float32, shape ``(ny, nx)``, row 0 south,
        missing cells NaN), ``pathname``, ``dss_file``, ``shape``, ``units``,
        ``data_type``, ``grid_type``, ``cell_size``, ``lower_left_cell``,
        ``cell_zero``, ``origin``, ``crs``, ``start_time`` and ``end_time``.
        See ``DssCore.read_grid``.

    Raises:
        FileNotFoundError: If the file does not exist
        ValueError: If the record does not exist or is not a grid
        DssCapabilityError: With the native backend, when the engine does not
            advertise qualified grid CRS strings

    Example:
        >>> paths = HmsDss.get_catalog("hrap.dss")
        >>> grid = HmsDss.read_grid("hrap.dss", paths[0])
        >>> print(grid["grid_type"], grid["shape"], grid["units"])
    """
    return DssCore.read_grid(dss_file, pathname)

write_timeseries(dss_file, pathname, times, values, units='CFS', data_type='INST-VAL', dss_version=None, *, sync=None) staticmethod

Write a regular-interval time series (for example an observed flow gage).

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Path to the DSS file (created as DSS7 unless dss_version is 6)

required
pathname str

/A/B/C/D/E/F/ with a regular E part (15MIN, 1HOUR, 1DAY, ...); D may be empty

required
times Union[Sequence[Any], DatetimeIndex, ndarray]

One naive end-of-period stamp per value, whole minutes, strictly increasing and regular for the E part

required
values Union[Sequence[float], ndarray, Series]

Numeric values; NaN is stored as HEC's missing value

required
units str

HEC units (default CFS)

'CFS'
data_type str

INST-VAL (default), PER-AVER, PER-CUM or INST-CUM

'INST-VAL'
dss_version Optional[int]

6 or 7 for a new file; for an existing file it must match

None
sync Optional[Any]

Flush policy of the native writer, passed to ras-commander-fast-dss unchanged; None (default) leaves the installed engine's own default. The java backend does not use it. See DssCore.write_timeseries.

None

Returns:

Type Description
Path

Path to the DSS file

Raises:

Type Description
ValueError

Invalid pathname, times or values, or a version mismatch

Example

import pandas as pd times = pd.date_range("2020-01-01 01:00", periods=3, freq="h") HmsDss.write_timeseries("obs.dss", "//GAGE 1/FLOW//1HOUR/OBS/", ... times, [10.0, 12.5, 11.0])

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def write_timeseries(
    dss_file: Union[str, Path],
    pathname: str,
    times: Union[Sequence[Any], pd.DatetimeIndex, np.ndarray],
    values: Union[Sequence[float], np.ndarray, pd.Series],
    units: str = "CFS",
    data_type: str = "INST-VAL",
    dss_version: Optional[int] = None,
    *,
    sync: Optional[Any] = None,
) -> Path:
    """
    Write a regular-interval time series (for example an observed flow gage).

    Args:
        dss_file: Path to the DSS file (created as DSS7 unless ``dss_version``
            is 6)
        pathname: ``/A/B/C/D/E/F/`` with a regular E part (``15MIN``, ``1HOUR``,
            ``1DAY``, ...); D may be empty
        times: One naive end-of-period stamp per value, whole minutes, strictly
            increasing and regular for the E part
        values: Numeric values; ``NaN`` is stored as HEC's missing value
        units: HEC units (default ``CFS``)
        data_type: ``INST-VAL`` (default), ``PER-AVER``, ``PER-CUM`` or ``INST-CUM``
        dss_version: 6 or 7 for a new file; for an existing file it must match
        sync: Flush policy of the native writer, passed to
            ras-commander-fast-dss unchanged; ``None`` (default) leaves the
            installed engine's own default. The ``java`` backend does not use
            it. See ``DssCore.write_timeseries``.

    Returns:
        Path to the DSS file

    Raises:
        ValueError: Invalid pathname, times or values, or a version mismatch

    Example:
        >>> import pandas as pd
        >>> times = pd.date_range("2020-01-01 01:00", periods=3, freq="h")
        >>> HmsDss.write_timeseries("obs.dss", "//GAGE 1/FLOW//1HOUR/OBS/",
        ...                         times, [10.0, 12.5, 11.0])
    """
    return DssCore.write_timeseries(dss_file, pathname, times, values, units,
                                    data_type, dss_version, sync=sync)

repair(src, dest, *, sync=None) staticmethod

Copy the readable records of a damaged DSS7 file into a new DSS7 file.

A thin wrapper around ras_commander_fast_dss.repair. It always runs on the native engine, whatever HmsDss.backend is; there is no Java equivalent. src is opened read-only and never written. The engine copies each readable record its discovery procedure reaches, reads the new file back, verifies every copied record against its source, and then publishes dest.

A partial recovery is still published. Always check result["complete"] and result["not_copied"]. complete covers only what the discovery procedure reached; it is not an integrity certificate for src. A warning is logged when complete is False.

Parameters:

Name Type Description Default
src Union[str, Path]

Existing DSS7 file to recover from

required
dest Union[str, Path]

New file to create. It must not exist; nothing is replaced.

required
sync Optional[Any]

Flush policy, passed to the engine unchanged; None (default) leaves the installed engine's own default. In ras-commander-fast-dss 0.1.2 the new file is built under a temporary name and flushed once before it is verified and published ("end", the default, and "step"); "none" does not flush it.

None

Returns:

Type Description
Dict[str, Any]

The engine's result dict unchanged, including records_copied,

Dict[str, Any]

not_copied ((pathname, reason) pairs), ledger,

Dict[str, Any]

src_listed_records, src_interrupted_write and complete

Raises:

Type Description
FileNotFoundError

If src does not exist

FileExistsError

If dest already exists

ImportError

If ras-commander-fast-dss is not installed

DssCapabilityError

If the installed engine has no repair

Example

result = HmsDss.repair("damaged.dss", "recovered.dss") if not result["complete"]: ... for pathname, reason in result["not_copied"]: ... print(pathname, reason)

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def repair(src: Union[str, Path], dest: Union[str, Path], *,
           sync: Optional[Any] = None) -> Dict[str, Any]:
    """
    Copy the readable records of a damaged DSS7 file into a new DSS7 file.

    A thin wrapper around ``ras_commander_fast_dss.repair``. It always runs on the
    native engine, whatever ``HmsDss.backend`` is; there is no Java equivalent.
    ``src`` is opened read-only and never written. The engine copies each readable
    record its discovery procedure reaches, reads the new file back, verifies
    every copied record against its source, and then publishes ``dest``.

    **A partial recovery is still published.** Always check ``result["complete"]``
    and ``result["not_copied"]``. ``complete`` covers only what the discovery
    procedure reached; it is not an integrity certificate for ``src``. A warning
    is logged when ``complete`` is False.

    Args:
        src: Existing DSS7 file to recover from
        dest: New file to create. It must not exist; nothing is replaced.
        sync: Flush policy, passed to the engine unchanged; ``None`` (default)
            leaves the installed engine's own default. In ras-commander-fast-dss
            0.1.2 the new file is built under a temporary name and flushed once
            before it is verified and published (``"end"``, the default, and
            ``"step"``); ``"none"`` does not flush it.

    Returns:
        The engine's result dict unchanged, including ``records_copied``,
        ``not_copied`` (``(pathname, reason)`` pairs), ``ledger``,
        ``src_listed_records``, ``src_interrupted_write`` and ``complete``

    Raises:
        FileNotFoundError: If ``src`` does not exist
        FileExistsError: If ``dest`` already exists
        ImportError: If ras-commander-fast-dss is not installed
        DssCapabilityError: If the installed engine has no ``repair``

    Example:
        >>> result = HmsDss.repair("damaged.dss", "recovered.dss")
        >>> if not result["complete"]:
        ...     for pathname, reason in result["not_copied"]:
        ...         print(pathname, reason)
    """
    src_path = HmsDss._existing_file(src)
    dest_path = Path(dest)
    if dest_path.exists():
        raise FileExistsError(f"repair destination already exists: {dest_path}")
    function = _backend.require_engine_function("repair", _backend.NATIVE_REPAIR_FEATURE)
    result = dict(function(src_path, dest_path,
                           **_backend.engine_sync_kwargs(function, sync, "repair")))
    if not result.get("complete", False):
        logger.warning(
            "DSS repair of %s into %s is incomplete: %d record(s) not copied; "
            "check result['not_copied']",
            src_path, dest_path, len(result.get("not_copied") or ()),
        )
    return result

read_paired_data_all(dss_file, pathname, *, ignore_d_part=True, dtype='stored') staticmethod

Read one paired-data record with every curve.

read_paired_data returns the HMS dict, which holds curve 0 only. This method is a thin wrapper around ras_commander_fast_dss.read_paired_data and returns its PairedData unchanged. It always runs on the native engine, whatever HmsDss.backend is.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Existing DSS file. It is never created or modified.

required
pathname str

Pathname of the paired-data record

required
ignore_d_part bool

Match a record whose D part differs when the exact pathname is not found (default True)

True
dtype str

"stored" (default) keeps the stored width; "float64" converts

'stored'

Returns:

Type Description
Any

The engine's PairedData: ordinates, values (shape

Any

(n_curves, n_ordinates)), n_curves, curve(i), labels, units_independent,

Any

units_dependent, type_independent, type_dependent,

Any

x_precision, y_precision and to_dataframe()

Raises:

Type Description
FileNotFoundError

If dss_file does not exist

ImportError

If ras-commander-fast-dss is not installed

ValueError

No record for pathname (the engine's DssPathnameNotFoundError)

RuntimeError

The record is not paired data (the engine's DssUnsupportedRecordError)

Example

pd_all = HmsDss.read_paired_data_all("tables.dss", "//DAM/ELEV-STOR-AREA///TABLE/") frame = pd_all.to_dataframe() # index: ordinates; one column per curve

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_paired_data_all(
    dss_file: Union[str, Path],
    pathname: str,
    *,
    ignore_d_part: bool = True,
    dtype: str = "stored",
) -> Any:
    """
    Read one paired-data record with every curve.

    ``read_paired_data`` returns the HMS dict, which holds curve 0 only. This
    method is a thin wrapper around ``ras_commander_fast_dss.read_paired_data``
    and returns its ``PairedData`` unchanged. It always runs on the native
    engine, whatever ``HmsDss.backend`` is.

    Args:
        dss_file: Existing DSS file. It is never created or modified.
        pathname: Pathname of the paired-data record
        ignore_d_part: Match a record whose D part differs when the exact
            pathname is not found (default True)
        dtype: ``"stored"`` (default) keeps the stored width; ``"float64"``
            converts

    Returns:
        The engine's ``PairedData``: ``ordinates``, ``values`` (shape
        ``(n_curves, n_ordinates)``), ``n_curves``, ``curve(i)``, ``labels``, ``units_independent``,
        ``units_dependent``, ``type_independent``, ``type_dependent``,
        ``x_precision``, ``y_precision`` and ``to_dataframe()``

    Raises:
        FileNotFoundError: If ``dss_file`` does not exist
        ImportError: If ras-commander-fast-dss is not installed
        ValueError: No record for ``pathname`` (the engine's
            ``DssPathnameNotFoundError``)
        RuntimeError: The record is not paired data (the engine's
            ``DssUnsupportedRecordError``)

    Example:
        >>> pd_all = HmsDss.read_paired_data_all("tables.dss", "//DAM/ELEV-STOR-AREA///TABLE/")
        >>> frame = pd_all.to_dataframe()      # index: ordinates; one column per curve
    """
    dss_path = HmsDss._existing_file(dss_file)
    function = _backend.require_engine_function("read_paired_data")
    return function(dss_path, pathname, ignore_d_part=ignore_d_part, dtype=dtype)

read_profile(dss_file, pathname, start_date=None, end_date=None, *, raw=False, trim_missing=True) staticmethod

Read a regular-interval profile dataset (DSS7 record types 102 and 107).

A thin wrapper around ras_commander_fast_dss.read_profile; it always runs on the native engine, whatever HmsDss.backend is.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Existing DSS file. It is never created or modified.

required
pathname str

/A/B/C/D/E/F/ with any D part: the whole dataset is read

required
start_date Optional[Any]

Optional inclusive window start

None
end_date Optional[Any]

Optional inclusive window end

None
raw bool

Keep HEC missing markers as stored instead of NaN

False
trim_missing bool

Remove leading and trailing rows whose every depth is missing (default)

True

Returns:

Type Description
Any

The engine's Profile unchanged: times, depths, values

Any

(n_times by n_depths), depth_units, value_units,

Any

quality and to_dataframe()

Raises:

Type Description
FileNotFoundError

If dss_file does not exist

ImportError

If ras-commander-fast-dss is not installed

ValueError

No data for pathname

RuntimeError

The record is not a regular profile (a scalar time series, an irregular profile 112/117, any DSS6 record)

Example

profile = HmsDss.read_profile("lake.dss", "/LAKE/DAM/TEMP-WATER//1Day/OBS/") frame = profile.to_dataframe()

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_profile(
    dss_file: Union[str, Path],
    pathname: str,
    start_date: Optional[Any] = None,
    end_date: Optional[Any] = None,
    *,
    raw: bool = False,
    trim_missing: bool = True,
) -> Any:
    """
    Read a regular-interval profile dataset (DSS7 record types 102 and 107).

    A thin wrapper around ``ras_commander_fast_dss.read_profile``; it always runs
    on the native engine, whatever ``HmsDss.backend`` is.

    Args:
        dss_file: Existing DSS file. It is never created or modified.
        pathname: ``/A/B/C/D/E/F/`` with any D part: the whole dataset is read
        start_date: Optional inclusive window start
        end_date: Optional inclusive window end
        raw: Keep HEC missing markers as stored instead of ``NaN``
        trim_missing: Remove leading and trailing rows whose every depth is
            missing (default)

    Returns:
        The engine's ``Profile`` unchanged: ``times``, ``depths``, ``values``
        (``n_times`` by ``n_depths``), ``depth_units``, ``value_units``,
        ``quality`` and ``to_dataframe()``

    Raises:
        FileNotFoundError: If ``dss_file`` does not exist
        ImportError: If ras-commander-fast-dss is not installed
        ValueError: No data for ``pathname``
        RuntimeError: The record is not a regular profile (a scalar time series,
            an irregular profile 112/117, any DSS6 record)

    Example:
        >>> profile = HmsDss.read_profile("lake.dss", "/LAKE/DAM/TEMP-WATER//1Day/OBS/")
        >>> frame = profile.to_dataframe()
    """
    dss_path = HmsDss._existing_file(dss_file)
    function = _backend.require_engine_function("read_profile")
    return function(dss_path, pathname, start_date, end_date,
                    raw=raw, trim_missing=trim_missing)

write_profile(dss_file, pathname, depths, values, *, start, depth_units, value_units, data_type, sync=None, **kwargs) staticmethod

Store a regular-interval profile (values by time and depth) in a DSS7 file.

A thin wrapper around ras_commander_fast_dss.write_profile; it always runs on the native engine, whatever HmsDss.backend is. Profiles exist only in DSS7.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

DSS7 file. A missing file is created as DSS7, and removed again if the write fails.

required
pathname str

/A/B/C/D/E/F/; E is a standard regular interval and D is replaced for each block

required
depths Any

The depth axis, 1-D, n_depths values

required
values Any

2-D, shape (n_times, n_depths). Never flattened or reshaped.

required
start Any

Time of the first row; the rows follow at the E-part interval

required
depth_units str

Units of the depth axis

required
value_units str

Units of the values

required
data_type str

HEC data type (INST-VAL, PER-AVER, ...)

required
sync Optional[Any]

Flush policy, passed to the engine unchanged; None (default) leaves the installed engine's own default

None
**kwargs Any

Other ras_commander_fast_dss.write_profile options, passed unchanged (quality, time_zone, precision, value_type, raw, allow_undetectable_readers)

{}

Returns:

Type Description
Dict[str, Any]

The engine's report dict unchanged

Raises:

Type Description
ValueError

An existing file is not DSS7, or the engine refuses the input

ImportError

If ras-commander-fast-dss is not installed

DssCapabilityError

The installed engine does not advertise write_profile

Example

HmsDss.write_profile( ... "lake.dss", "/LAKE/DAM/TEMP-WATER//1Day/OBS/", ... depths=[0.0, 5.0, 10.0], values=temperatures, ... start="01JAN2024 2400", depth_units="ft", value_units="DEG F", ... data_type="INST-VAL", ... )

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def write_profile(
    dss_file: Union[str, Path],
    pathname: str,
    depths: Any,
    values: Any,
    *,
    start: Any,
    depth_units: str,
    value_units: str,
    data_type: str,
    sync: Optional[Any] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Store a regular-interval profile (values by time and depth) in a DSS7 file.

    A thin wrapper around ``ras_commander_fast_dss.write_profile``; it always runs
    on the native engine, whatever ``HmsDss.backend`` is. Profiles exist only in
    DSS7.

    Args:
        dss_file: DSS7 file. A missing file is created as DSS7, and removed
            again if the write fails.
        pathname: ``/A/B/C/D/E/F/``; E is a standard regular interval and D is
            replaced for each block
        depths: The depth axis, 1-D, ``n_depths`` values
        values: 2-D, shape ``(n_times, n_depths)``. Never flattened or reshaped.
        start: Time of the first row; the rows follow at the E-part interval
        depth_units: Units of the depth axis
        value_units: Units of the values
        data_type: HEC data type (``INST-VAL``, ``PER-AVER``, ...)
        sync: Flush policy, passed to the engine unchanged; ``None`` (default)
            leaves the installed engine's own default
        **kwargs: Other ``ras_commander_fast_dss.write_profile`` options, passed
            unchanged (``quality``, ``time_zone``, ``precision``,
            ``value_type``, ``raw``, ``allow_undetectable_readers``)

    Returns:
        The engine's report dict unchanged

    Raises:
        ValueError: An existing file is not DSS7, or the engine refuses the input
        ImportError: If ras-commander-fast-dss is not installed
        DssCapabilityError: The installed engine does not advertise
            ``write_profile``

    Example:
        >>> HmsDss.write_profile(
        ...     "lake.dss", "/LAKE/DAM/TEMP-WATER//1Day/OBS/",
        ...     depths=[0.0, 5.0, 10.0], values=temperatures,
        ...     start="01JAN2024 2400", depth_units="ft", value_units="DEG F",
        ...     data_type="INST-VAL",
        ... )
    """
    function = _backend.require_engine_function(
        "write_profile", _backend.NATIVE_PROFILE_WRITE_FEATURE)
    dc = _backend.require_native_writes()
    target, version, existed, created = DssCore._native_write_target(dss_file, 7)
    with DssCore._native_new_file(dc, target, version, existed, created):
        return function(
            str(target), pathname, depths, values, start=start,
            depth_units=depth_units, value_units=value_units, data_type=data_type,
            **_backend.native_sync_kwargs(sync), **kwargs,
        )

read_location(dss_file, pathname) staticmethod

Read a DSS7 location record (/A/B/Location Info////).

A thin wrapper around ras_commander_fast_dss.read_location; it always runs on the native engine. Use read_associated_location for the location of a data record.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Existing DSS7 file. It is never created or modified.

required
pathname str

Pathname of the location record

required

Returns:

Type Description
Any

The engine's Location unchanged (x, y, z, coordinate

Any

system, units and datum codes and names, time_zone,

Any

supplemental; to_dict())

Raises:

Type Description
FileNotFoundError

If dss_file does not exist

ImportError

If ras-commander-fast-dss is not installed

ValueError

The record does not exist

RuntimeError

The record is not a location record, or the file is DSS6

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_location(dss_file: Union[str, Path], pathname: str) -> Any:
    """
    Read a DSS7 location record (``/A/B/Location Info////``).

    A thin wrapper around ``ras_commander_fast_dss.read_location``; it always runs
    on the native engine. Use ``read_associated_location`` for the location of a
    data record.

    Args:
        dss_file: Existing DSS7 file. It is never created or modified.
        pathname: Pathname of the location record

    Returns:
        The engine's ``Location`` unchanged (``x``, ``y``, ``z``, coordinate
        system, units and datum codes and names, ``time_zone``,
        ``supplemental``; ``to_dict()``)

    Raises:
        FileNotFoundError: If ``dss_file`` does not exist
        ImportError: If ras-commander-fast-dss is not installed
        ValueError: The record does not exist
        RuntimeError: The record is not a location record, or the file is DSS6
    """
    dss_path = HmsDss._existing_file(dss_file)
    return _backend.require_engine_function("read_location")(dss_path, pathname)

read_associated_location(dss_file, pathname) staticmethod

Return the location stored for a data record, or None when there is none.

A thin wrapper around ras_commander_fast_dss.read_associated_location; it always runs on the native engine. DSS7: the location record built from the A and B parts of pathname. DSS6: the coordinates in the time-series record's own header.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Existing DSS file. It is never created or modified.

required
pathname str

Pathname of the data record (any D part)

required

Returns:

Type Description
Optional[Any]

The engine's Location, or None

Raises:

Type Description
FileNotFoundError

If dss_file does not exist

ImportError

If ras-commander-fast-dss is not installed

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def read_associated_location(dss_file: Union[str, Path], pathname: str) -> Optional[Any]:
    """
    Return the location stored for a data record, or None when there is none.

    A thin wrapper around ``ras_commander_fast_dss.read_associated_location``; it
    always runs on the native engine. DSS7: the location record built from the A
    and B parts of ``pathname``. DSS6: the coordinates in the time-series
    record's own header.

    Args:
        dss_file: Existing DSS file. It is never created or modified.
        pathname: Pathname of the data record (any D part)

    Returns:
        The engine's ``Location``, or None

    Raises:
        FileNotFoundError: If ``dss_file`` does not exist
        ImportError: If ras-commander-fast-dss is not installed
    """
    dss_path = HmsDss._existing_file(dss_file)
    return _backend.require_engine_function("read_associated_location")(dss_path, pathname)

write_location(dss_file, pathname, *, sync=None, **kwargs) staticmethod

Store location data (coordinates, datums, supplemental text) for a pathname.

A thin wrapper around ras_commander_fast_dss.write_location; it always runs on the native engine, whatever HmsDss.backend is. DSS7 stores the record /A/B/Location Info////. DSS6 rewrites the header of every block of the time series named by pathname, which must exist.

Parameters:

Name Type Description Default
dss_file Union[str, Path]

Existing DSS6 or DSS7 file. This method does not create files.

required
pathname str

DSS7: any pathname of the location (A and B are used). DSS6: a time-series pathname.

required
sync Optional[Any]

Flush policy, passed to the engine unchanged; None (default) leaves the installed engine's own default

None
**kwargs Any

The ras_commander_fast_dss.write_location fields, passed unchanged: x, y, z, coordinate_system, coordinate_id, horizontal_units, horizontal_datum, vertical_units, vertical_datum, time_zone (DSS7), supplemental, keep_existing. Supplemental text is informational: a datum named in it is never applied to values.

{}

Returns:

Type Description
Dict[str, Any]

The engine's report dict unchanged

Raises:

Type Description
FileNotFoundError

If dss_file does not exist

ImportError

If ras-commander-fast-dss is not installed

DssCapabilityError

The installed engine does not advertise write_location

Example

HmsDss.write_location("gages.dss", "//GAGE 1/FLOW//1HOUR/OBS/", ... x=-90.07, y=29.95, z=3.2)

Source code in hms_commander/dss/hms_dss.py
@staticmethod
@log_call
def write_location(
    dss_file: Union[str, Path],
    pathname: str,
    *,
    sync: Optional[Any] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Store location data (coordinates, datums, supplemental text) for a pathname.

    A thin wrapper around ``ras_commander_fast_dss.write_location``; it always runs
    on the native engine, whatever ``HmsDss.backend`` is. DSS7 stores the record
    ``/A/B/Location Info////``. DSS6 rewrites the header of every block of the
    time series named by ``pathname``, which must exist.

    Args:
        dss_file: Existing DSS6 or DSS7 file. This method does not create files.
        pathname: DSS7: any pathname of the location (A and B are used). DSS6: a
            time-series pathname.
        sync: Flush policy, passed to the engine unchanged; ``None`` (default)
            leaves the installed engine's own default
        **kwargs: The ``ras_commander_fast_dss.write_location`` fields, passed
            unchanged: ``x``, ``y``, ``z``, ``coordinate_system``,
            ``coordinate_id``, ``horizontal_units``, ``horizontal_datum``,
            ``vertical_units``, ``vertical_datum``, ``time_zone`` (DSS7),
            ``supplemental``, ``keep_existing``. Supplemental text is
            informational: a datum named in it is never applied to values.

    Returns:
        The engine's report dict unchanged

    Raises:
        FileNotFoundError: If ``dss_file`` does not exist
        ImportError: If ras-commander-fast-dss is not installed
        DssCapabilityError: The installed engine does not advertise
            ``write_location``

    Example:
        >>> HmsDss.write_location("gages.dss", "//GAGE 1/FLOW//1HOUR/OBS/",
        ...                       x=-90.07, y=29.95, z=3.2)
    """
    dss_path = HmsDss._existing_file(dss_file)
    function = _backend.require_engine_function(
        "write_location", _backend.NATIVE_LOCATION_WRITE_FEATURE)
    return function(str(dss_path), pathname,
                    **_backend.native_sync_kwargs(sync), **kwargs)