-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.py
2600 lines (2071 loc) · 92.8 KB
/
output.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
from __future__ import annotations
from aenum import EnumMeta
import os.path
import warnings
from datetime import datetime, timedelta
from functools import wraps
from typing import Callable, List, NoReturn, Optional, Sequence, Tuple, Union
from itertools import product
from io import SEEK_END
import struct
import numpy as np
from aenum import Enum, extend_enum
from numpy import asarray, atleast_1d, atleast_2d, concatenate, datetime64
from numpy import integer as npint
from numpy import ndarray, stack, tile, vstack
from pandas.core.api import (
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Timestamp,
to_datetime,
IndexSlice,
)
from swmm.toolkit import output, shared_enum
from swmm.pandas.output.structure import Structure
from swmm.pandas.output.tools import arrayish, _enum_get, _enum_keys
def output_open_handler(func):
"""Checks if output file is open before running function.
Parameters
----------
func: function
method of Output class
"""
@wraps(func)
def inner_function(self, *args, **kwargs):
if not self._loaded:
self._open()
return func(self, *args, **kwargs)
return inner_function
class Output:
def __init__(self, binfile: str, preload: bool = False):
"""Base class for a SWMM binary output file.
The output object provides several options to process timeseries within binary output file.
Output files should be closed after use prevent memory leaks. Close them explicitly with
the `_close()` method or deleting the object using `del`, or use it with a context manager.
.. code-block:: python
# Using a the _close method
>>> from swmm.pandas import Output
>>> out = Output('tests/Model.out')
>>> print(out.project_size)
[3, 9, 8, 1, 3]
>>> out._close() # can also use `del out`
>>>
# Using a context manager
>>> with Output('tests/Model.out') as out:
... print(out.pollutants)
('groundwater', 'pol_rainfall', 'sewage')
Parameters
----------
binfile: str
model binary file path
Returns
-------
"""
self._period: int
"""number of reporting time steps in the """
self._report: int
"""out file reporting time step in seconds"""
self._start: datetime
"""start datetime of the output file records"""
self._end: datetime
"""end datetime of the output file records"""
self._timeIndex: DatetimeIndex
"""DatetimeIndex to use for output timeseries"""
self._project_size: List[int]
"""Array of element count values [nSubcatchments, nNodes, nLinks, nSystems(1), nPollutants]"""
self._subcatchments: Tuple[str, ...]
"""Tuple of subcatchment names in output file"""
self._links: Tuple[str, ...]
"""Tuple of link names in output file"""
self._pollutants: Tuple[str, ...]
"""Tuple of pollutant names in output file"""
self._handle = None
self._binfile: str = binfile
"""path to binary output file"""
self._delete_handle: bool = False
"""Indicates if output file was closed correctly"""
self._preload: bool = preload
self._loaded: bool = False
"""Indicates if output file was loaded correctly"""
self.subcatch_attributes = Enum(
"subcatch_attributes",
list(shared_enum.SubcatchAttribute.__members__.keys())[:-1],
start=0,
)
"""Subcatchment attribute enumeration: By default has
'rainfall',
'snow_depth',
'evap_loss',
'infil_loss',
'runoff_rate',
'gw_outflow_rate',
'gw_table_elev',
'soil_moisture'
"""
# need copies of enumes to extend them for pollutants
# basically recreate enums using the keys from shared_enum
# but drop POLLUT_CONC_0 for each
#
# I looked into using swmm.toolkit.output_metadata for this but it
# extends global enums, which could break having multiple
# output objects opened in the same python session if they
# have different pollutant names
self.node_attributes:shared_enum.NodeAttribute = Enum(
"node_attributes",
list(shared_enum.NodeAttribute.__members__.keys())[:-1],
start=0,
)
"""Node attribute enumeration: By default has
'invert_depth',
'hydraulic_head',
'ponded_volume',
'lateral_inflow',
'total_inflow',
'flooding_losses'
"""
self.link_attributes:shared_enum.LinkAttribute = Enum(
"link_attributes",
list(shared_enum.LinkAttribute.__members__.keys())[:-1],
start=0,
)
"""Link attribute enumeration: By default has
'flow_rate',
'flow_depth',
'flow_velocity',
'flow_volume',
'capacity',
"""
self.system_attributes = shared_enum.SystemAttribute
"""System attribute enumeration: By default has
'air_temp',
'rainfall',
'snow_depth',
'evap_infil_loss',
'runoff_flow',
'dry_weather_inflow',
'gw_inflow',
'rdii_inflow',
'direct_inflow',
'total_lateral_inflow',
'flood_losses',
'outfall_flows',
'volume_stored',
'evap_rate',
'ptnl_evap_rate'
"""
@staticmethod
def _elementIndex(
elementID: Union[str, int, None], indexSquence: Sequence[str], elementType: str
) -> int:
"""Validate the index of a model element passed to Output methods. Used to
convert model element names to their index in the out file.
Parameters
----------
elementID: str, int
The name or index of the model element listed in the index_dict dict.
indexSquence: one of more string
The ordered sequence against which to validate the index
(one of self.nodes, self.links, self.subcatchments).
elementType: str
The type of model element (e.g. node, link, etc.)
Only used to print the exception if an attribute cannot be found.
Returns
-------
int
The integer index of the requested element.
Raises
------
OutputException
Exception if element cannot be found in indexSequence.
"""
if isinstance(elementID, (int, npint)):
return int(elementID)
try:
return indexSquence.index(elementID)
# since this class can pull multiple attributes and elements in one function
# call it is probably better to do some pre-validation of input arguments
# before starting a potentially lengthy data pull
except ValueError:
raise ValueError(
f"{elementType} ID: {elementID} does not exist in model output."
)
@staticmethod
def _validateAttribute(
attribute: Union[int, str, Sequence[Union[int, str]], None],
validAttributes: Enum,
) -> Tuple[list, list]:
"""
Function to validate attribute arguments of element_series, element_attribute,
and element_result functions.
Parameters
----------
attribute: Union[int, str, Sequence[Union[int, str]], None]
The attribute to validate against validAttributes.
validAttributes: dict
THe dict of attributes against which to validate attribute.
Returns
-------
Tuple[list, list]
Two arrays, one of attribute names and one of attribute indicies.
"""
# this kind of logic was needed in the series and results functions.
# not sure if this is the best way, but it felt a bit DRYer to
# put it into a funciton
if isinstance(attribute, (type(None), EnumMeta)):
attributeArray = _enum_keys(validAttributes)
elif isinstance(attribute, arrayish):
attributeArray = attribute
else:
attributeArray = [attribute]
# allow mixed input of attributes
# accept string names, integers, or enums values in the same list
attributeIndexArray = []
for i, attrib in enumerate(attributeArray):
if isinstance(attrib, Enum):
attributeArray[i] = attrib.name.lower()
attributeIndexArray.append(attrib)
elif isinstance(attrib, (int, npint)):
# will raise index error if not in range
attribName = _enum_keys(validAttributes)[attrib]
attributeArray[i] = attribName
attributeIndexArray.append(_enum_get(validAttributes, attribName))
elif isinstance(attrib, str):
index = _enum_get(validAttributes, attrib)
if index is None:
raise ValueError(
f"Attribute {attrib} not in valid attribute list: {_enum_keys(validAttributes)}"
)
attributeIndexArray.append(index)
else:
raise TypeError(
f"Input type: {type(attrib)} not valid. Must be one of int, str, or Enum"
)
# attributeIndexArray = [validAttributes.get(atr, -1) for atr in attributeArray]
return attributeArray, attributeIndexArray
@staticmethod
def _validateElement(
element: Union[int, str, Sequence[Union[int, str]], None],
validElements: Sequence[str],
) -> Tuple[List[str], List[int]]:
"""
Function to validate element arguments of element_series, element_attribute,
and element_result functions.
Parameters
----------
element: Union[int, str, Sequence[Union[int, str]], None]
The element name or index or None. If None, return all elements in
validElements.
validElements: Sequence[str]
Tuple of elements against which to validate element.
Returns
-------
Tuple[list, list]
Two arrays, one of element names and one of element indicies.
"""
# this kind of logic was needed in the series and results functions
# not sure if this is the best way, but it felt a bit DRYer to
# put it into a funciton
if element is None:
elementArray = list(validElements)
elif isinstance(element, arrayish):
elementArray = element
else:
# ignore typing since types of this output list
# are reconciled in the next loop. mypy was complaining.
elementArray = [element] # type: ignore
elementIndexArray = []
# allow mixed input of elements. string names can be mixed
# with integer indicies in the same input list
for i, elem in enumerate(elementArray):
if isinstance(elem, (int, npint)):
# will raise index error if not in range
elemName = validElements[elem]
elementArray[i] = elemName
elementIndexArray.append(elem)
elif isinstance(elem, str):
elementIndexArray.append(Output._elementIndex(elem, validElements, ""))
else:
raise TypeError(
f"Input type {type(elem)} not valid. Must be one of int, str"
)
return elementArray, elementIndexArray
@staticmethod
def _datetime_from_swmm(swmm_datetime):
remaining_days = swmm_datetime % 1
days = swmm_datetime - remaining_days
seconds = remaining_days * 86400
dt = datetime(year=1899, month=12, day=30) + timedelta(
days=days, seconds=seconds
)
return dt
def _checkPollutantName(self, name: str) -> str:
"""Check pollutant name against existing attribute dicts.
Rename and and warn if existing attribute is duplicated.
Parameters
----------
name: str
The name of pollutant.
Returns
-------
str
The validated name of pollutant.
"""
elems = []
if name.lower() in _enum_keys(self.subcatch_attributes):
elems.append("subcatchment")
if name.lower() in _enum_keys(self.node_attributes):
elems.append("node")
if name.lower() in _enum_keys(self.link_attributes):
elems.append("link")
if name.lower() in _enum_keys(self.system_attributes):
elems.append("system")
if len(elems) > 0:
warnings.warn(
f"Pollutent {name} is a duplicate of existing {','.join(elems)} attribute, renaming to pol_{name}"
)
return f"pol_{name}"
return name
def _open(self) -> bool:
"""Open a binary file.
Parameters
----------
Returns
-------
bool
True if binary file was opened successfully.
"""
if not os.path.exists(self._binfile):
raise ValueError(f"Output file at: '{self._binfile}' does not exist")
if self._handle is None:
self._handle = output.init()
if not self._loaded:
self._loaded = True
output.open(self._handle, self._binfile)
self._start = self._datetime_from_swmm(output.get_start_date(self._handle))
self._report = output.get_times(self._handle, shared_enum.Time.REPORT_STEP)
self._period = output.get_times(self._handle, shared_enum.Time.NUM_PERIODS)
self._end = self._start + timedelta(seconds=self._period * self._report)
# load pollutants if not already loaded
if not hasattr(self, "_pollutants"):
# load pollutant data if it has not before
total = self.project_size[4]
self._pollutants = tuple(
self._checkPollutantName(
self._objectName(shared_enum.ElementType.POLLUT, index).lower()
)
for index in range(total)
)
for i, nom in enumerate(self._pollutants):
# extend enums to include pollutants
extend_enum(self.subcatch_attributes, nom.upper(), 8 + i)
extend_enum(self.node_attributes, nom.upper(), 6 + i)
extend_enum(self.link_attributes, nom.upper(), 5 + i)
if self._preload:
# respos = output.get_positions(self._handle)[2]
# self._close()
subs = list(
product(
["sub"],
range(len(self.subcatchments)),
range(len(self.subcatch_attributes)),
)
)
nodes = list(
product(
["node"],
range(len(self.nodes)),
range(len(self.node_attributes)),
)
)
links = list(
product(
["link"],
range(len(self.links)),
range(len(self.link_attributes)),
)
)
system = list(product(["sys"], ["sys"], range(len(self.system_attributes))))
cols = subs + nodes + links + system
cols.insert(0, ("datetime", 0, 0))
idx = MultiIndex.from_tuples(cols)
fmts = "f8" + ",f4" * (len(cols) - 1)
with open(self._binfile, "rb") as fil:
fil.seek(self._output_position, 0)
dat = np.core.rec.fromfile(fil, formats=fmts)
self.data = DataFrame(dat)
self.data.columns = idx
return True
def _close(self) -> bool:
"""Close an opened binary file.
Parameters
----------
Returns
-------
bool
True if binary file was closed successfully.
"""
if self._loaded:
output.close(self._handle)
self._loaded = False
del self._handle
self._handle = None
self._delete_handle = True
return True
###### outfile property getters ######
@property
def _output_position(self):
if not hasattr(self, "__output_position"):
with open(self._binfile, "rb") as fil:
fil.seek(-4 * 4, SEEK_END)
self.__output_position = struct.unpack("i", fil.read(4))[0]
return self.__output_position
@property # type: ignore
@output_open_handler
def report(self) -> int:
"""Return the reporting timestep in seconds.
Parameters
----------
Returns
-------
int
The reporting timestep in seconds.
"""
return self._report
@property # type: ignore
@output_open_handler
def start(self) -> datetime:
"""Return the reporting start datetime.
Parameters
----------
Returns
-------
datetime
The reporting start datetime.
"""
return self._start
@property # type: ignore
@output_open_handler
def end(self) -> datetime:
"""Return the reporting end datetime.
Returns
-------
datetime
The reporting end datetime.
"""
return self._end
@property # type: ignore
@output_open_handler
def period(self) -> int:
"""Return the number of reporting timesteps in the binary output file.
Returns
-------
int
The number of reporting timesteps.
"""
return self._period
@property # type: ignore
def project_size(self) -> List[int]:
"""Returns the number of each model element type available in out binary output file
in the following order:
[subcatchment, node, link, system, pollutant]
Parameters
----------
Returns
-------
list
A list of numbers of each model type.
[nSubcatchments, nNodes, nLinks, nSystems(1), nPollutants]
"""
if not hasattr(self, "_project_size"):
self._load_project_size()
return self._project_size
@output_open_handler
def _load_project_size(self) -> NoReturn:
"""Load model size into self._project_size"""
self._project_size = output.get_proj_size(self._handle)
@property
def pollutants(self) -> Tuple[str, ...]:
"""Return a tuple of pollutants available in SWMM binary output file.
Parameters
----------
Returns
-------
Tuple[str]
A tuple of pollutant names.
"""
# chose not to write a pollutant loader method
# because loading such is kind of imperative to the functionality
# of other data getter methods, which don't necessarily
# call pollutants method. Instead, pollutant loading logic is
# thrown in the _open() method, and this method calls open if
# pollutants are not available.
if self._pollutants is None:
self._open()
return self._pollutants
@property # type: ignore
@output_open_handler
def _unit(self) -> Tuple[int]:
"""Return SWMM binary output file unit type from `swmm.toolkit.shared_enum.UnitSystem`.
Parameters
----------
Returns
-------
Tuple[int]
Tuple of integers indicating system units, flow units, and units for each pollutant.
"""
return tuple(output.get_units(self._handle)) # type: ignore
@property
def units(self) -> List[str]:
"""Return SWMM binary output file unit type from `swmm.toolkit.shared_enum.UnitSystem`.
Parameters
----------
Returns
-------
List[str]
List of string names for system units, flow units, and units for each pollutant.
Values returned are the names from swmm.toolkit.shared_enum:
UnitSystem
FlowUnits
ConcUnits
"""
return [
shared_enum.UnitSystem(self._unit[0]).name,
shared_enum.FlowUnits(self._unit[1]).name,
] + [shared_enum.ConcUnits(i).name for i in self._unit[2:]]
@property # type: ignore
@output_open_handler
def _version(self) -> int:
"""Return SWMM version used to generate SWMM binary output file results.
Parameters
----------
Returns
-------
int
Integer representation of SWMM version used to make output file.
"""
return output.get_version(self._handle)
@output_open_handler
def _objectName(self, object_type: int, index: int) -> str:
"""Get object name from SWMM binary output file using object type and object index.
Parameters
----------
object_type: int
The object type from swmm.toolkit.shared_enum.ElementType.
index: int
The object index.
Returns
-------
str
object name
"""
return output.get_elem_name(self._handle, object_type, index)
##### timestep setters and getters #####
def _time2step(
self,
dateTime: Union[
None,
str,
int,
datetime,
Timestamp,
datetime64,
Sequence[Union[str, int, datetime, Timestamp, datetime64]],
],
ifNone: int = 0,
method: str = "nearest",
) -> List[int]:
"""Convert datetime value to SWMM timestep index. By deafult, this returns the nearest timestep to
to the requested date, so it will always return a time index available in the binary output file.
Parameters
----------
dateTime: datetime-like or string or sequence of such
datetime to convert. Must be a datetime-like object or convertable
with `pd.to_datetime`.
ifNone: int
The value to return if dateTime is None, defaults to 0.
method: str
The method name to pass to pandas `get_indexer`_, default to "nearest.
.. _get_indexer: https://pandas.pydata.org/docs/reference/api/pandas.Index.get_indexer.html
Returns
-------
Union[int, np.ndarray]
SWMM model time step or array of time steps
"""
if dateTime is None:
return [ifNone]
dt = asarray(dateTime).flatten()
# if passing swmm time step, no indexing necessary
if dt.dtype in (float, int):
return dt.astype(int).tolist()
# ensure datetime value
dt = to_datetime(dt)
return self.timeIndex.get_indexer(dt, method=method).tolist()
@property
def timeIndex(self) -> DatetimeIndex:
"""Returns DatetimeIndex of reporting timeseries in binary output file.
Parameters
----------
Returns
-------
pd.DatetimeIndex
A pandas `DatetimeIndex`_ for each reporting timestep.
.. _DatetimeIndex: https://pandas.pydata.org/docs/reference/api/pandas.DatetimeIndex.html?highlight=datetimeindex#pandas.DatetimeIndex
"""
if not hasattr(self, "_timeIndex"):
self._load_timeIndex()
return self._timeIndex
@output_open_handler
def _load_timeIndex(self) -> NoReturn:
"""Load model reporting times into self._times"""
self._timeIndex = DatetimeIndex(
[
self._start + timedelta(seconds=self._report) * step
for step in range(1, self._period + 1)
]
)
##### model element setters and getters #####
def _subcatchmentIndex(
self, subcatchment: Union[str, int, Sequence[Union[str, int]], None]
) -> Union[List[int], int]:
"""Get the swmm index for subcatchment.
Parameters
----------
subcatchment: Union[str, int, Sequence[Union[str, int]]]
The name(s) of subcatchment(s).
Returns
-------
Union[List[int], int]
The SWMM index(s) of subcatchment(s).
"""
if isinstance(subcatchment, (str, int, type(None))):
return self._elementIndex(subcatchment, self.subcatchments, "subcatchment")
elif subcatchment is not None:
return [
self._elementIndex(sub, self.subcatchments, "subcatchment")
for sub in subcatchment
]
else:
raise TypeError("Invalid type for _subcatchmentIndex argument")
@property
def subcatchments(self) -> Tuple[str, ...]:
"""Return a tuple of subcatchments available in SWMM output binary file.
Parameters
----------
Returns
-------
Tuple[str]
A tuple of model subcatchment names.
"""
if not hasattr(self, "_subcatchments"):
self._load_subcatchments()
return self._subcatchments
@output_open_handler
def _load_subcatchments(self) -> NoReturn:
"""Load model size into self._project_size"""
total = self.project_size[0]
self._subcatchments = tuple(
self._objectName(shared_enum.ElementType.SUBCATCH, index)
for index in range(total)
)
def _nodeIndex(
self, node: Union[str, int, Sequence[Union[str, int]], None]
) -> Union[List[int], int]:
"""Get the swmm index for node.
Parameters
----------
node: Union[str, int, Sequence[Union[str, int]]]
The name(s) of node(s)
Returns
-------
Union[List[int], int]
The SWMM index(s) of node(s).
"""
if isinstance(node, (str, int, type(None))):
return self._elementIndex(node, self.nodes, "node")
# elif here because mypy issues
elif node is not None:
return [self._elementIndex(nd, self.nodes, "node") for nd in node]
else:
raise TypeError("Invalid type for self._nodeIndex argument")
@property
def nodes(self) -> Tuple[str, ...]:
"""Return a tuple of nodes available in SWMM binary output file.
Parameters
----------
Returns
-------
Tuple[str]
A tuple of model node names.
"""
if not hasattr(self, "_nodes"):
self._load_nodes()
return self._nodes
@output_open_handler
def _load_nodes(self) -> NoReturn:
"""Load model nodes into self._nodes"""
total = self.project_size[1]
self._nodes = tuple(
self._objectName(shared_enum.ElementType.NODE, index)
for index in range(total)
)
def _linkIndex(
self, link: Union[str, int, Sequence[Union[str, int]], None]
) -> Union[List[int], int]:
"""Get the swmm index for link.
Parameters
----------
link: Union[str, int, Sequence[Union[str, int]]]
The name(s) of link(s)
Returns
-------
Union[List[int], int]
SWMM index(s) of link(s).
"""
if isinstance(link, (str, int, type(None))):
return self._elementIndex(link, self.links, "link")
# elif here because mypy issues
elif link is not None:
return [self._elementIndex(lnk, self.links, "link") for lnk in link]
else:
raise TypeError("Invalid type for self._linkIndex argument")
@property
def links(self) -> Tuple[str, ...]:
"""Return a tuple of links available in SWMM binary output file.
Parameters
----------
Returns
-------
Tuple[str]
A tuple of model link names.
"""
if not hasattr(self, "_links"):
self._load_links()
return self._links
@output_open_handler
def _load_links(self) -> NoReturn:
"""Load model links into self._links"""
total = self.project_size[2]
self._links = tuple(
self._objectName(shared_enum.ElementType.LINK, index)
for index in range(total)
)
####### series getters #######
def _memory_series_getter(self, type: str) -> Callable:
if type == "sys":
def getter(_handle, Attr: Enum, startIndex: int, endIndex: int) -> ndarray:
# col = f"{type};{type};{Attr.value}"
# return self.data[col][startIndex:endIndex]
return self.data.loc[
startIndex : endIndex - 1, IndexSlice[type, type, Attr.value]
].to_numpy()
else:
def getter(
_handle, elemIdx: int, Attr: Enum, startIndex: int, endIndex: int
) -> ndarray:
# col = f"{type};{elemIdx};{Attr.value}"
# return self.data[col][startIndex:endIndex]
return self.data.loc[
startIndex : endIndex - 1, IndexSlice[type, elemIdx, Attr.value]
].to_numpy()
return getter
def _model_series(
self,
elementIndexArray: List[int],
attributeIndexArray: List[Enum],
startIndex: int,
endIndex: int,
columns: Optional[str],
getterFunc: Callable,
) -> ndarray:
"""
Base series getter for any attribute. The function consilidates the logic
necessary to build long or wide timeseries dataframes for each type of swmm
model element.
Parameters
----------
elementIndexArray: List[int]
Array of SWMM model element indicies
attributeIndexArray: List[enum]
Array of attribute Enums to pull for each element
startIndex: int
SWMM simulation time index to start timeseries
endIndex: int
SWMM simulation time index to end timeseries
columns: Optional[str]