-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathcomtrade.py
1375 lines (1134 loc) · 46.2 KB
/
comtrade.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
# -*- coding: utf-8 -*-
# MIT License
# Copyright (c) 2018 David Rodrigues Parrini
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import array
import datetime as dt
import errno
import io
import math
import os
import re
import struct
import sys
from typing import Union
import warnings
try:
import numpy
_HAS_NUMPY = True
except ModuleNotFoundError:
_HAS_NUMPY = False
try:
import pandas as pd
_HAS_PANDAS = True
except ModuleNotFoundError:
_HAS_PANDAS = False
# COMTRADE standard revisions
REV_1991 = "1991"
REV_1999 = "1999"
REV_2001 = "2001"
REV_2013 = "2013"
# DAT file format types
_TYPE_ASCII = "ASCII"
_TYPE_BINARY = "BINARY"
_TYPE_BINARY32 = "BINARY32"
_TYPE_FLOAT32 = "FLOAT32"
# Special values
_TIMESTAMP_MISSING = 0xFFFFFFFF
# CFF headers
_CFF_HEADER_REXP = r"(?i)--- file type: ([a-z]+)(?:\s+([a-z0-9]+)(?:\s*\:\s*([0-9]+))?)? ---$"
# common separator character of data fields of CFG and ASCII DAT files
_SEPARATOR = ","
# timestamp regular expression
_re_date = re.compile(r"([0-9]{1,2})/([0-9]{1,2})/([0-9]{2,4})")
_re_time = re.compile(r"([0-9]{1,2}):([0-9]{2}):([0-9]{1,2})(.([0-9]{1,12}))?")
# Non-standard revision warning
_WARNING_UNKNOWN_REVISION = "Unknown standard revision \"{}\""
# Date time with nanoseconds resolution warning
_WARNING_DATETIME_NANO = "Unsupported datetime objects with nanoseconds \
resolution. Using truncated values."
# Date time with year 0, month 0 and/or day 0.
_WARNING_MIN_DATE = "Missing date values. Using minimum values: {}."
class ComtradeError(Exception):
pass
def _read_sep_values(line, expected: int = -1, default: str = ''):
values = tuple(map(lambda cell: cell.strip(), line.split(_SEPARATOR)))
if expected == -1 or len(values) == expected:
return values
return [values[i] if i < len(values) else default
for i in range(expected)]
def _preallocate_values(array_type, size, use_numpy_arrays):
type_mapping_numpy = {"f": "float32", "d": "float64", "i": "int32", "l": "int64"}
if _HAS_NUMPY and use_numpy_arrays:
return numpy.zeros(size, dtype=type_mapping_numpy[array_type])
return array.array(array_type, [0]) * size
def _prevent_null(str_value: str, value_type: type, default_value):
if len(str_value.strip()) == 0:
return default_value
else:
return value_type(str_value)
def _get_date(date_str: str) -> tuple:
m = _re_date.match(date_str)
if m is not None:
day = int(m.group(1))
month = int(m.group(2))
year = int(m.group(3))
return day, month, year
return 0, 0, 0
def _get_time(time_str: str, ignore_warnings: bool = False) -> tuple:
m = _re_time.match(time_str)
if m is not None:
hour = int(m.group(1))
minute = int(m.group(2))
second = int(m.group(3))
frac_sec_str = m.group(5)
# Pad fraction of seconds with 0s to the right
if len(frac_sec_str) <= 6:
frac_sec_str = fill_with_zeros_to_the_right(frac_sec_str, 6)
else:
frac_sec_str = fill_with_zeros_to_the_right(frac_sec_str, 9)
frac_second = int(frac_sec_str)
in_nanoseconds = len(frac_sec_str) > 6
microsecond = frac_second
if in_nanoseconds:
# Nanoseconds resolution is not supported by datetime module, so it's
# converted to integer below.
if not ignore_warnings:
warnings.warn(Warning(_WARNING_DATETIME_NANO))
microsecond = int(microsecond * 1E-3)
return hour, minute, second, microsecond, in_nanoseconds
def fill_with_zeros_to_the_right(number_str: str, width: int):
actual_len = len(number_str)
if actual_len < width:
difference = width - actual_len
fill_chars = "0" * difference
return number_str + fill_chars
return number_str
def _get_same_case(original_ext: str, other_ext: str) -> str:
"""Returns each other_ext character with the same case as original_ext's."""
same_case = ""
for i in range(len(original_ext)):
if i < len(other_ext):
if original_ext[i].isupper():
same_case += other_ext[i].upper()
else:
same_case += other_ext[i].lower()
else:
break
return same_case
def _read_timestamp(timestamp_line: str, rev_year: str, ignore_warnings: bool = False) -> tuple:
"""Process comma separated fields and returns a tuple containing the timestamp
and a boolean value indicating whether nanoseconds are used.
Can possibly return the timestamp 00/00/0000 00:00:00.000 for empty strings
or empty pairs."""
day, month, year, hour, minute, second, microsecond = (0,) * 7
nano_sec = False
if len(timestamp_line.strip()) > 0:
values = _read_sep_values(timestamp_line, 2)
if len(values) >= 2:
date_str, time_str = values[0:2]
if len(date_str.strip()) > 0:
# 1991 Format Uses mm/dd/yyyy format
if rev_year == REV_1991:
month, day, year = _get_date(date_str)
# Modern Formats Use dd/mm/yyyy format
else:
day, month, year = _get_date(date_str)
if len(time_str.strip()) > 0:
hour, minute, second, microsecond, \
nano_sec = _get_time(time_str, ignore_warnings)
using_min_data = False
if year <= 0:
year = dt.MINYEAR
using_min_data = True
if month <= 0:
month = 1
using_min_data = True
if day <= 0:
day = 1
using_min_data = True
# Timezone info unsupported
tzinfo = None
timestamp = dt.datetime(year, month, day, hour, minute, second,
microsecond, tzinfo)
if not ignore_warnings and using_min_data:
warnings.warn(Warning(_WARNING_MIN_DATE.format(str(timestamp))))
return timestamp, nano_sec
def _eof_strip(line: str) -> str:
"""Strip line of whitespace and <sub> (0x1A) control character that may appear
appended to the end of text files on some platforms."""
return _replace_sub(line).strip()
def _replace_sub(line: str) -> str:
"""Replace <sub> (0x1A) control character that may appear appended to the end
of text files on some platforms."""
return line.replace(chr(0x1A), "")
class Cfg:
"""Parses and stores Comtrade's CFG data."""
# time base units
TIME_BASE_NANO_SEC = 1E-9
TIME_BASE_MICRO_SEC = 1E-6
def __init__(self, **kwargs):
"""
Cfg object constructor.
Keyword arguments:
ignore_warnings -- whether warnings are displayed in stdout
(default: False)
"""
self._file_path = None
# implicit data
self._time_base = self.TIME_BASE_MICRO_SEC
# Default CFG data
self._station_name = ""
self._rec_dev_id = ""
self._rev_year = REV_2013
self._channels_count = 0
self._analog_channels = []
self._status_channels = []
self._analog_count = 0
self._status_count = 0
self._frequency = 0.0
self._nrates = 1
self._sample_rates = []
self._timestamp_critical = False
self._start_timestamp = dt.datetime(1900, 1, 1)
self._trigger_timestamp = dt.datetime(1900, 1, 1)
self._ft = _TYPE_ASCII
self._time_multiplier = 1.0
# 2013 standard revision information
# time_code,local_code = 0,0 means local time is UTC
self._time_code = 0
self._local_code = 0
# tmq_code,leapsec
self._tmq_code = 0
self._leap_second = 0
self._ignore_warnings = kwargs.get("ignore_warnings", False)
@property
def file_path(self) -> Union[str, None]:
"""Return the CFG file path."""
return self._file_path
@property
def station_name(self) -> str:
"""Return the recording device's station name."""
return self._station_name
@property
def rec_dev_id(self) -> str:
"""Return the recording device id."""
return self._rec_dev_id
@property
def rev_year(self) -> str:
"""Return the COMTRADE revision year."""
return self._rev_year
@property
def channels_count(self) -> int:
"""Return the number of channels, total."""
return self._channels_count
@property
def analog_channels(self) -> list:
"""Return the analog channels list with complete channel description."""
return self._analog_channels
@property
def status_channels(self) -> list:
"""Return the status channels list with complete channel description."""
return self._status_channels
@property
def analog_count(self) -> int:
"""Return the number of analog channels."""
return self._analog_count
@property
def status_count(self) -> int:
"""Return the number of status channels."""
return self._status_count
@property
def time_base(self) -> float:
"""Return the time base."""
return self._time_base
@property
def frequency(self) -> float:
"""Return the measured line frequency in Hertz."""
return self._frequency
@property
def ft(self) -> str:
"""Return the expected DAT file format."""
return self._ft
@property
def timemult(self) -> float:
"""Return the DAT time multiplier (Default = 1)."""
return self._time_multiplier
@property
def timestamp_critical(self) -> bool:
"""Returns whether the DAT file must contain non-zero
timestamp values."""
return self._timestamp_critical
@property
def start_timestamp(self) -> dt.datetime:
"""Return the recording start time stamp as a datetime object."""
return self._start_timestamp
@property
def trigger_timestamp(self) -> dt.datetime:
"""Return the trigger time stamp as a datetime object."""
return self._trigger_timestamp
@property
def nrates(self) -> int:
"""Return the number of different sample rates within the DAT file."""
return self._nrates
@property
def sample_rates(self) -> list:
"""
Return a list with pairs describing the number of samples for a given
sample rate.
"""
return self._sample_rates
# Deprecated properties - Changed "Digital" for "Status"
@property
def digital_channels(self) -> list:
"""Returns the status channels bidimensional values list."""
if not self._ignore_warnings:
warnings.warn(FutureWarning("digital_channels is deprecated, "
"use status_channels instead."))
return self._status_channels
@property
def digital_count(self) -> int:
"""Returns the number of status channels."""
if not self._ignore_warnings:
warnings.warn(FutureWarning("digital_count is deprecated, "
"use status_count instead."))
return self._status_count
def load(self, filepath, **kwargs):
"""Load and read a CFG file contents."""
self._file_path = filepath
if os.path.isfile(self._file_path):
filtered_kwargs = {
"encoding": kwargs.get("encoding", "utf-8")
}
with open(self._file_path, "r", **filtered_kwargs) as cfg:
self._read_io(cfg)
else:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),
self._file_path)
def read(self, cfg_lines):
"""Read CFG-format data of a FileIO or StringIO object."""
if type(cfg_lines) is str:
self._read_io(io.StringIO(cfg_lines))
else:
self._read_io(cfg_lines)
def _read_io(self, cfg):
"""Read CFG-format lines and stores its data."""
line_count = 0
self._nrates = 1
self._sample_rates = []
self._analog_channels = []
self._status_channels = []
# First line
line = cfg.readline()
# station, device, and comtrade standard revision information
packed = _read_sep_values(line)
if 3 == len(packed):
# only 1999 revision and above has the standard revision year
self._station_name, self._rec_dev_id, self._rev_year = packed
self._rev_year = self._rev_year.strip()
if self._rev_year not in (REV_1991, REV_1999, REV_2001, REV_2013):
if not self._ignore_warnings:
msg = _WARNING_UNKNOWN_REVISION.format(self._rev_year)
warnings.warn(Warning(msg))
else:
self._station_name, self._rec_dev_id = packed
self._rev_year = REV_1991
line_count = line_count + 1
# Second line
line = cfg.readline()
# number of channels and its type
totchn, achn, schn = _read_sep_values(line, 3, '0')
self._channels_count = int(totchn)
self._analog_count = int(achn[:-1])
self._status_count = int(schn[:-1])
self._analog_channels = [None] * self._analog_count
self._status_channels = [None] * self._status_count
line_count = line_count + 1
# Analog channel description lines
for ichn in range(self._analog_count):
line = cfg.readline()
packed = _read_sep_values(line, 13, '0')
# unpack values
n, name, ph, ccbm, uu, a, b, skew, cmin, cmax, \
primary, secondary, pors = packed
# type conversion
n = int(n)
a = float(a)
b = _prevent_null(b, float, 0.0)
skew = _prevent_null(skew, float, 0.0)
cmin = float(cmin)
cmax = float(cmax)
primary = float(primary)
secondary = float(secondary)
self.analog_channels[ichn] = AnalogChannel(n, a, b, skew,
cmin, cmax, name, uu, ph, ccbm, primary, secondary, pors)
line_count = line_count + 1
# Status channel description lines
for ichn in range(self._status_count):
line = cfg.readline()
# unpack values
packed = _read_sep_values(line, 5, '0')
n, name, ph, ccbm, y = packed
# type conversion
n = int(n)
y = _prevent_null(y, int, 0) # TODO: actually a critical data. In the future add a warning.
self.status_channels[ichn] = StatusChannel(n, name, ph, ccbm, y)
line_count = line_count + 1
# Frequency line
line = cfg.readline()
if len(line.strip()) > 0:
self._frequency = float(line.strip())
line_count = line_count + 1
# Nrates line
# number of different sample rates
line = cfg.readline()
self._nrates = int(line.strip())
if self._nrates == 0:
self._nrates = 1
self._timestamp_critical = True
else:
self._timestamp_critical = False
line_count = line_count + 1
for inrate in range(self._nrates):
line = cfg.readline()
# each sample rate
samp, endsamp = _read_sep_values(line)
samp = float(samp)
endsamp = int(endsamp)
self.sample_rates.append([samp, endsamp])
line_count = line_count + 1
# First data point time and time base
line = cfg.readline()
ts_str = line.strip()
self._start_timestamp, nanosec = _read_timestamp(
ts_str,
self.rev_year,
self._ignore_warnings
)
self._time_base = self._get_time_base(nanosec)
line_count = line_count + 1
# Event data point and time base
line = cfg.readline()
ts_str = line.strip()
self._trigger_timestamp, nanosec = _read_timestamp(
ts_str,
self.rev_year,
self._ignore_warnings
)
self._time_base = min([self.time_base, self._get_time_base(nanosec)])
line_count = line_count + 1
# DAT file type
line = cfg.readline()
self._ft = line.strip()
line_count = line_count + 1
# Timestamp multiplication factor
if self._rev_year in (REV_1999, REV_2001, REV_2013):
line = _eof_strip(cfg.readline())
if len(line) > 0:
self._time_multiplier = float(line)
else:
self._time_multiplier = 1.0
line_count = line_count + 1
# time_code and local_code
if self._rev_year == REV_2013:
line = _eof_strip(cfg.readline())
if line:
self._time_code, self._local_code = _read_sep_values(line)
line_count = line_count + 1
line = _eof_strip(cfg.readline())
# time_code and local_code
self._tmq_code, self._leap_second = _read_sep_values(line)
def _get_time_base(self, using_nanoseconds: bool):
"""
Return the time base, which is based on the fractionary part of the
seconds in a timestamp (00.XXXXX).
"""
if using_nanoseconds:
return self.TIME_BASE_NANO_SEC
else:
return self.TIME_BASE_MICRO_SEC
class Comtrade:
"""Parses and stores Comtrade data."""
# extensions
EXT_CFG = "cfg"
EXT_DAT = "dat"
EXT_INF = "inf"
EXT_HDR = "hdr"
# format specific
ASCII_SEPARATOR = ","
def __init__(self, **kwargs):
"""
Comtrade object constructor.
Keyword arguments:
ignore_warnings -- whether warnings are displayed in stdout
(default: False).
"""
self.file_path = ""
self._cfg = Cfg(**kwargs)
# Default CFG data
self._analog_channel_ids = []
self._analog_phases = []
self._status_channel_ids = []
self._status_phases = []
self._timestamp_critical = False
# Data types
self._use_numpy_arrays = kwargs.get("use_numpy_arrays", False)
self._use_double_precision = kwargs.get("use_double_precision", False)
# DAT file data
self._time_values = _preallocate_values(
"d" if self._use_double_precision else "f",
0,
self._use_numpy_arrays,
)
self._analog_values = []
self._status_values = []
# Additional CFF data (or additional comtrade files)
self._hdr = None
self._inf = None
if "ignore_warnings" in kwargs:
self.ignore_warnings = kwargs["ignore_warnings"]
else:
self.ignore_warnings = False
@property
def station_name(self) -> str:
"""Return the recording device's station name."""
return self._cfg.station_name
@property
def rec_dev_id(self) -> str:
"""Return the recording device id."""
return self._cfg.rec_dev_id
@property
def rev_year(self) -> str:
"""Return the COMTRADE revision year."""
return self._cfg.rev_year
@property
def cfg(self) -> Cfg:
"""Return the underlying CFG class instance."""
return self._cfg
@property
def hdr(self):
"""Return the HDR file contents."""
return self._hdr
@property
def inf(self):
"""Return the INF file contents."""
return self._inf
@property
def analog_channel_ids(self) -> list:
"""Returns the analog channels name list."""
return self._analog_channel_ids
@property
def analog_phases(self) -> list:
"""Returns the analog phase name list."""
return self._analog_phases
@property
def status_channel_ids(self) -> list:
"""Returns the status channels name list."""
return self._status_channel_ids
@property
def status_phases(self) -> list:
"""Returns the status phase name list."""
return self._status_phases
@property
def time(self) -> list:
"""Return the time values list."""
return self._time_values
@property
def analog(self) -> list:
"""Return the analog channel values bidimensional list."""
return self._analog_values
@property
def status(self) -> list:
"""Return the status channel values bidimensional list."""
return self._status_values
@property
def total_samples(self) -> int:
"""Return the total number of samples (per channel)."""
return self._total_samples
@property
def frequency(self) -> float:
"""Return the measured line frequency in Hertz."""
return self._cfg.frequency
@property
def start_timestamp(self):
"""Return the recording start time stamp as a datetime object."""
return self._cfg.start_timestamp
@property
def trigger_timestamp(self):
"""Return the trigger time stamp as a datetime object."""
return self._cfg.trigger_timestamp
@property
def channels_count(self) -> int:
"""Return the number of channels, total."""
return self._cfg.channels_count
@property
def analog_count(self) -> int:
"""Return the number of analog channels."""
return self._cfg.analog_count
@property
def status_count(self) -> int:
"""Return the number of status channels."""
return self._cfg.status_count
@property
def trigger_time(self) -> float:
"""Return relative trigger time in seconds."""
stt = self._cfg.start_timestamp
trg = self._cfg.trigger_timestamp
tdiff = trg - stt
tsec = (tdiff.days * 60 * 60 * 24) + tdiff.seconds + (tdiff.microseconds * 1E-6)
return tsec
@property
def time_base(self) -> float:
"""Return the time base."""
return self._cfg.time_base
@property
def ft(self) -> str:
"""Return the expected DAT file format."""
return self._cfg.ft
# Deprecated properties - Changed "Digital" for "Status"
@property
def digital_channel_ids(self) -> list:
"""Returns the status channels name list."""
if not self.ignore_warnings:
warnings.warn(FutureWarning("digital_channel_ids is deprecated, use status_channel_ids instead."))
return self._status_channel_ids
@property
def digital(self) -> list:
"""Returns the status channels bidimensional values list."""
if not self.ignore_warnings:
warnings.warn(FutureWarning("digital is deprecated, use status instead."))
return self._status_values
@property
def digital_count(self) -> int:
"""Returns the number of status channels."""
if not self.ignore_warnings:
warnings.warn(FutureWarning("digital_count is deprecated, use status_count instead."))
return self._cfg.status_count
def _get_dat_reader(self):
# case-insensitive comparison of file format
ft_upper = self.ft.upper()
dat_kwargs = {"use_numpy_arrays": self._use_numpy_arrays,
"use_double_precision": self._use_double_precision,
"rev_year": self.rev_year}
if ft_upper == _TYPE_ASCII:
dat = _AsciiDatReader(**dat_kwargs)
elif ft_upper == _TYPE_BINARY:
dat = _BinaryDatReader(**dat_kwargs)
elif ft_upper == _TYPE_BINARY32:
dat = _Binary32DatReader(**dat_kwargs)
elif ft_upper == _TYPE_FLOAT32:
dat = _Float32DatReader(**dat_kwargs)
else:
raise ComtradeError("Not supported data file format: {}".format(self.ft))
return dat
def read(self, cfg_lines, dat_lines_or_bytes) -> None:
"""
Read CFG and DAT files contents. Expects FileIO or StringIO objects.
"""
self._cfg.read(cfg_lines)
# channel ids
self._cfg_extract_channels_ids(self._cfg)
# channel phases
self._cfg_extract_phases(self._cfg)
dat = self._get_dat_reader()
dat.read(dat_lines_or_bytes, self._cfg)
# copy .dat object information
self._dat_extract_data(dat)
def _cfg_extract_channels_ids(self, cfg) -> None:
self._analog_channel_ids = [channel.name for channel in cfg.analog_channels]
self._status_channel_ids = [channel.name for channel in cfg.status_channels]
def _cfg_extract_phases(self, cfg) -> None:
self._analog_phases = [channel.ph for channel in cfg.analog_channels]
self._status_phases = [channel.ph for channel in cfg.status_channels]
def _dat_extract_data(self, dat) -> None:
self._time_values = dat.time
self._analog_values = dat.analog
self._status_values = dat.status
self._total_samples = dat.total_samples
def to_dataframe(self, **kwargs) -> "pd.DataFrame":
"""Return a pandas DataFrame object with comtrade data."""
if _HAS_PANDAS:
index_type = kwargs.get("index_type", "time")
data = {
"time": self.time,
}
data.update({self.analog_channel_ids[i]: self.analog[i] for i in range(self.analog_count)})
data.update({self.status_channel_ids[i]: self.status[i] for i in range(self.status_count)})
df = pd.DataFrame(data)
if index_type == "time":
df.set_index("time", inplace=True)
elif index_type == "sample":
pass
return df
raise ComtradeError("pandas package is not installed.")
def load(self, cfg_file, dat_file=None, **kwargs) -> "Comtrade":
"""
Load CFG, DAT, INF, and HDR files. Each must be a FileIO or StringIO
object. dat_file, inf_file, and hdr_file are optional (Default: None).
cfg_file is the cfg file path, including its extension.
dat_file is optional, and may be set if the DAT file name differs from
the CFG file name.
Keyword arguments:
inf_file -- optional INF file path (Default = None)
hdr_file -- optional HDR file path (Default = None)
"""
inf_file = kwargs.get("inf_file", None)
hdr_file = kwargs.get("hdr_file", None)
# which extension: CFG or CFF?
file_ext = cfg_file[-3:]
file_ext_upper = file_ext.upper()
if file_ext_upper == "CFF":
# check if the CFF file exists
self._load_cff(cfg_file)
elif file_ext_upper == "CFG":
basename = cfg_file[:-3]
# if not informed, infer dat_file with cfg_file
if dat_file is None:
dat_file = cfg_file[:-3] + _get_same_case(file_ext, self.EXT_DAT)
if inf_file is None:
inf_file = basename + _get_same_case(file_ext, self.EXT_INF)
if hdr_file is None:
hdr_file = basename + _get_same_case(file_ext, self.EXT_HDR)
# load both cfg and dat
file_kwargs = {}
if "encoding" in kwargs:
file_kwargs["encoding"] = kwargs["encoding"]
self._load_cfg(cfg_file, **file_kwargs)
self._load_dat(dat_file)
# Load additional inf and hdr files, if they exist.
self._load_inf(inf_file, **file_kwargs)
self._load_hdr(hdr_file, **file_kwargs)
else:
raise ComtradeError(r"Expected CFG file path, instead got \"{}\".".format(cfg_file))
return self
def _load_cfg(self, cfg_filepath, **kwargs):
self._cfg.load(cfg_filepath, **kwargs)
# channel ids
self._cfg_extract_channels_ids(self._cfg)
# channel phases
self._cfg_extract_phases(self._cfg)
def _load_dat(self, dat_filepath):
dat = self._get_dat_reader()
dat.load(dat_filepath, self._cfg)
# copy .dat object information
self._dat_extract_data(dat)
def _load_inf(self, inf_file, **kwargs):
if os.path.exists(inf_file):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
with open(inf_file, 'r', **kwargs) as file:
self._inf = _replace_sub(file.read())
if len(self._inf) == 0:
self._inf = None
else:
self._inf = None
def _load_hdr(self, hdr_file, **kwargs):
if os.path.exists(hdr_file):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
with open(hdr_file, 'r', **kwargs) as file:
self._hdr = _replace_sub(file.read())
if len(self._hdr) == 0:
self._hdr = None
else:
self._hdr = None
@staticmethod
def _read_mixed_text_bin_data_as_text(cff_file) -> str:
chunk_delimiter = b"\n"
current_chunk = []
while True:
current_value = cff_file.read(1)
if not current_value:
break
if current_value != chunk_delimiter:
current_chunk.append(current_value)
else:
yield b"".join(current_chunk).decode("utf-8", errors="ignore").strip()
current_chunk = []
def _load_cff(self, cff_file_path: str, **kwargs):
# stores each file type lines
cfg_lines = []
dat_lines = []
hdr_lines = []
inf_lines = []
header_re = re.compile(_CFF_HEADER_REXP)
with open(cff_file_path, "rb") as cff_file:
# file type: CFG, HDR, INF, DAT
ftype = None
# file format: ASCII, BINARY, BINARY32, FLOAT32
fformat = None
line_number = 0
last_match = None
for current_line in self._read_mixed_text_bin_data_as_text(cff_file):
line_number += 1
mobj = header_re.match(current_line.strip().upper())
if mobj is not None:
last_match = mobj
groups = last_match.groups()
ftype = groups[0]
if groups[1] is not None:
fformat = groups[1]
fbytes_obj = groups[2]
if ftype == "DAT" and fformat != _TYPE_ASCII:
break
elif last_match is not None and ftype == "CFG":
cfg_lines.append(current_line.strip())
elif last_match is not None and ftype == "HDR":
hdr_lines.append(current_line.strip())
elif last_match is not None and ftype == "INF":
inf_lines.append(current_line.strip())
elif last_match is not None and ftype == "DAT" and fformat == _TYPE_ASCII:
dat_lines.append(current_line.strip())
if fformat == _TYPE_ASCII:
# process ASCII CFF data
self.read("\n".join(cfg_lines), "\n".join(dat_lines))
else:
# read remaining data as .dat values.
dat_bytes = cff_file.read()
self.read("\n".join(cfg_lines), dat_bytes)
# stores additional data
self._hdr = "\n".join(hdr_lines)
self._inf = "\n".join(inf_lines)
def cfg_summary(self):
"""Returns the CFG attributes summary string."""
header_line = "Channels (Analog,Digital,Total): {}A + {}D = {}"
sample_line = "Sample rate of {} Hz to the sample #{}"
interval_line = "From {} to {} with time mult. = {}"
format_line = "{} format"
lines = [header_line.format(self.analog_count, self.status_count,
self.channels_count),
"Line frequency: {} Hz".format(self.frequency)]
for i in range(self._cfg.nrates):
rate, points = self._cfg.sample_rates[i]
lines.append(sample_line.format(rate, points))
lines.append(interval_line.format(self.start_timestamp,
self.trigger_timestamp,
self._cfg.timemult))
lines.append(format_line.format(self.ft))
return "\n".join(lines)
class Channel:
"""Holds common channel description data."""
def __init__(self, n=1, name='', ph='', ccbm=''):
"""Channel abstract class constructor."""
self.n = n
self.name = name
self.ph = ph
self.ccbm = ccbm
def __str__(self):