-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextractors.py
1418 lines (1158 loc) · 60.9 KB
/
extractors.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 typing import Optional, Union, List, Set, Tuple
import re
# ---
from common.logging_facilities import loge, logd, logw
# ---
import yaml
from yaml import YAMLObject
# ---
import pandas as pd
# ---
import dask
import dask.distributed
# ---
from sqlalchemy import create_engine
# ---
import sql_queries
from yaml_helper import proto_constructor
from data_io import DataSet
from tag_extractor import ExtractRunParametersTagsOperation
import tag_regular_expressions as tag_regex
from common.common_sets import BASE_TAGS_EXTRACTION_FULL, BASE_TAGS_EXTRACTION_MINIMAL
# ---
class SqlLiteReader():
r"""
A utility class to run a query over a SQLite3 database or to extract the parameters and attributes for a run from a database.
Parameters
----------
db_file : str
The path to the SQLite3 database file.
"""
def __init__(self, db_file):
self.db_file = db_file
self.connection = None
self.engine = None
def connect(self):
self.engine = create_engine("sqlite:///"+self.db_file)
self.connection = self.engine.connect()
def disconnect(self):
self.connection.close()
def execute_sql_query(self, query):
self.connect()
result = pd.read_sql_query(query, self.connection)
self.disconnect()
return result
def parameter_extractor(self):
self.connect()
result = pd.read_sql_query(sql_queries.run_param_query, self.connection)
self.disconnect()
return result
def config_extractor(self):
self.connect()
result = pd.read_sql_query(sql_queries.run_config_query, self.connection)
self.disconnect()
return result
def attribute_extractor(self):
self.connect()
result = pd.read_sql_query(sql_queries.run_attr_query, self.connection)
self.disconnect()
return result
def extract_tags(self, attributes_regex_map, iterationvars_regex_map, parameters_regex_map):
r"""
Parameters
----------
attributes_regex_map : dict
The dictionary containing the definitions for the tags to extract from the `runAttr` table.
iterationvars_regex_map : dict
The dictionary containing the definitions for the tags to extract from the `iterationvars` attribute.
parameters_regex_map : dict
The dictionary containing the definitions for the tags to extract from the `runParam` table.
Extract all tags defined in the given mappings from the `runAttr` and `runParam` tables and parse the value of the `iterationvars` attribute.
See the module `tag_regular_expressions` for the expected structure of the mappings.
"""
# Determine OMNeT++ version by checking whether a `runParam` or a `runConfig` table exists.
# OMNeT++ versions >= 6 store the parameters in the `runConfig` table, previous versions in the `runParams` table.
runParamName = self.execute_sql_query("SELECT name FROM sqlite_master WHERE name='runParam';")
runConfigName = self.execute_sql_query("SELECT name FROM sqlite_master WHERE name='runConfig';")
if len(runParamName) and runConfigName.empty:
# versions < 6
parameter_extractor = self.parameter_extractor
isOmnetv6 = False
elif runParamName.empty and len(runConfigName) == 1:
# versions >= 6
parameter_extractor = self.config_extractor
isOmnetv6 = True
else:
raise NotImplementedError(
"Neither the `runParam` nor the `runConfig` table has been found in the input database. "
"This is possibly either a corrupted database or an unknown OMNeT++ version."
)
tags = ExtractRunParametersTagsOperation.extract_attributes_and_params(parameter_extractor, self.attribute_extractor
, parameters_regex_map, attributes_regex_map, iterationvars_regex_map
, isOmnetv6=isOmnetv6
)
return tags
class DataAttributes(YAMLObject):
r"""
A class for assigning arbitrary attributes to a dataset.
The constructor accept an arbitrary number of keyword arguments and turns
them into object attributes.
Parameters
----------
source_file : str
The file name the dataset was extracted from.
source_files : List[str]
The list of file names the dataset was extracted from.
common_root : str
The root directory that was not containing regex for search files.
alias : List[str]
The alias given to the data in the dataset.
aliases : List[str]
The aliases given to the data in the dataset.
"""
def __init__(self, /, **kwargs):
self.source_files = set()
self.aliases = set()
for key in kwargs:
if key == 'source_file':
self.source_files.add(kwargs[key])
elif key == 'source_files':
for file in kwargs[key]:
self.source_files.add(kwargs[key])
elif key == 'common_root':
self.common_root = kwargs[key]
elif key == 'alias':
self.aliases.add(kwargs[key])
elif key == 'aliases':
for file in kwargs[key]:
self.aliases.add(kwargs[key])
else:
setattr(self, key, kwargs[key])
def get_source_files(self) -> Set[str]:
return self.source_files
def common_root(self) -> Set[str]:
return self.common_root
def add_source_file(self, source_file:str):
self.source_files.add(source_file)
def add_source_files(self, source_files:Set[str]):
for source_file in source_files:
self.source_files.add(source_file)
def get_aliases(self) -> Set[str]:
return self.aliases
def add_alias(self, alias:str):
self.aliases.add(alias)
def remove_source_file(self, source_file:str):
self.source_files.remove(source_file)
def __str__(self) -> str:
return str(self.__dict__)
def __repr__(self) -> str:
return str(self.__dict__)
# ----------------------------------------
class Extractor(YAMLObject):
r"""
A class for extracting and preprocessing data from a SQLite database.
This is the abstract base class.
"""
yaml_tag = '!Extractor'
def prepare(self):
r"""
Prepare and return a list or a single dask.Delayed task.
"""
return None
def set_tag_maps(self, attributes_regex_map, iterationvars_regex_map, parameters_regex_map):
setattr(self, 'attributes_regex_map', attributes_regex_map)
setattr(self, 'iterationvars_regex_map', iterationvars_regex_map)
setattr(self, 'parameters_regex_map', parameters_regex_map)
class BaseExtractor(Extractor):
yaml_tag = '!BaseExtractor'
def __init__(self, /,
input_files:list[str]
, categorical_columns:Optional[list[str]] = None
, numerical_columns:Optional[Union[dict[str, str], list[str]]] = None
, *args, **kwargs
):
self.input_files:list = list(input_files)
# categorical_columns and numerical_columns (if appropriate) are explicitly converted
# to a set to alleviate the need for an explicit tag in the YAML recipe, since pyyaml
# always interprets values in curly braces as dictionaries
if not categorical_columns:
self.categorical_columns:set[str] = set()
else:
self.categorical_columns:set[str] = set(categorical_columns)
if not numerical_columns:
self.numerical_columns:set[str] = set()
else:
if not isinstance(numerical_columns, dict):
self.numerical_columns:set[str] = set(numerical_columns)
else:
self.numerical_columns:dict[str, str] = dict(numerical_columns)
@staticmethod
def convert_columns_dtype(data:pd.DataFrame
, categorical_columns:Optional[set[str]] = None
, numerical_columns:Optional[Union[dict[str, str], set[str]]] = None):
r"""
Convert the data in the specified columns of the given DataFrame to either a
`categorical data type <https://pandas.pydata.org/docs/user_guide/categorical.html>`_ or a
`numerical data type <https://pandas.pydata.org/pandas-docs/stable/user_guide/basics.html#basics-dtypes>`_
Parameters
----------
data: pd.DataFrame
The input DataFrame whose columns are to be converted.
categorical_columns: Optional[set[str]]
The set of names of the columns to convert to a categorical data type.
numerical_columns: Optional[Union[dict[str, str], set[str]]]
The set of names of the columns to convert to a categorical data type.
The data type to convert to can also be given explicitly as a dictionary
with the column names as keys and the data type as values.
"""
if not categorical_columns:
categorical_columns = frozenset()
if not numerical_columns:
numerical_columns = frozenset()
# get the set of columns actually present in the DataFrame
actual_categorical_columns = categorical_columns.intersection(data.columns)
missing_categorical_columns = categorical_columns.difference(actual_categorical_columns)
if len(missing_categorical_columns) > 0:
logw(f"columns for conversion to categorical data types not found in DataFrame: {missing_categorical_columns}")
# if the numerical data types are explicitly given as a dictionary, use them
if isinstance(numerical_columns, dict):
numerical_columns_set = set(numerical_columns.keys())
numerical_columns_dict = numerical_columns
else:
# if the numerical data types are not explicitly given, convert to float
numerical_columns_set = numerical_columns
numerical_columns_dict = {}
for column in numerical_columns_set:
numerical_columns_dict[column] = 'float'
actual_numerical_columns = numerical_columns_set.intersection(data.columns)
missing_numerical_columns = numerical_columns_set.difference(actual_numerical_columns)
if len(missing_numerical_columns) > 0:
logw(f"columns for conversion to numerical data types not found in DataFrame: {missing_numerical_columns}")
logd(f"columns to convert to categorical data types: {actual_categorical_columns}")
def key_extractor(obj):
def is_float(string):
return string.replace('.', '').isnumeric()
def convert_numerical(num_str):
if num_str.isnumeric():
# convert to int if it's numerical
return int(num_str)
elif is_float(num_str):
# convert to float if it's numerical when a period is removed
return float(num_str)
elif num_str.isalpha():
# not a numerical
return num_str
if isinstance(obj, str):
# characters that are used as separators in e.g. variable names
separator_map = { '-':'', '_':'', ':':'', ' ':'' }
if obj.isalpha():
return obj
elif obj.isnumeric():
return int(obj)
elif is_float(obj):
return float(obj)
elif obj.translate(str.maketrans(separator_map)).isalnum():
# obj is alpha-numerical with possible extra ascii characters used as separators
# split the string into characters and numerical literals
regex = re.compile(r'[^\W\d_]+|\d+')
split_str = regex.findall(obj)
for i in range(0, len(split_str)):
split_str[i] = convert_numerical(split_str[i])
return tuple(split_str)
else:
return obj
else:
# return object as is for int, float or other
return obj
for column in actual_categorical_columns:
data[column] = data[column].astype('category')
sorted_categories = sorted(data[column].cat.categories, key=key_extractor)
data[column] = data[column].astype(pd.CategoricalDtype(categories=sorted_categories, ordered=True))
logd(f'{column=} {data[column].dtype=}')
logd(f"columns to convert to numerical data types: {actual_numerical_columns}")
for column in actual_numerical_columns:
data[column] = data[column].astype(numerical_columns_dict[column])
return data
@staticmethod
def read_sql_from_file(db_file:str
, query:str
, includeFilename:bool=False
) -> pd.DataFrame:
r"""
Extract the data from a SQLite database into a `pandas.DataFrame <https://pandas.pydata.org/docs/user_guide/dsintro.html#dataframe>`_
Parameters
----------
db_file: str
The input file name from which data is to be extracted.
query: str
The SQL query to extract data from the input file.
includeFilename: bool
Whether to include the input file name in the column `filename` of the result DataFrame.
"""
sql_reader = SqlLiteReader(db_file)
try:
data = sql_reader.execute_sql_query(query)
except Exception as e:
loge(f'>>>> ERROR: no data could be extracted from {db_file}:\n {e}')
return pd.DataFrame()
if 'rowId' in data.columns:
data = data.drop(labels=['rowId'], axis=1)
if (data.empty):
logw(f'Extractor: extraction yields no data for {db_file}')
return pd.DataFrame()
# add path to dataframe
if (includeFilename):
data["filename"] = str(db_file)
return data
class SqlExtractor(BaseExtractor):
r"""
Extract the data from files using a SQL statement.
Parameters
----------
input_files: List[str]
The list of paths to the input files, as literal path or as a regular expression.
query: str
The SQL query used to extract data from the input files.
"""
yaml_tag = '!SqlExtractor'
def __init__(self, /,
input_files:list
, query:str
, includeFilename:bool = False
, *args, **kwargs):
super().__init__(input_files=input_files, *args, **kwargs)
self.query:str = query
self.includeFilename:bool = includeFilename
def prepare(self):
data_set = DataSet(self.input_files)
# For every input file construct a `Delayed` object, a kind of a promise
# on the data and the leafs of the computation graph
result_list = []
for db_file in data_set.get_file_list():
res = dask.delayed(SqlExtractor.read_query_from_file)\
(db_file, self.query
, includeFilename=self.includeFilename
, categorical_columns = self.categorical_columns
, numerical_columns = self.numerical_columns
)
attributes = DataAttributes(source_file=db_file, common_root=data_set.get_common_root())
result_list.append((res, attributes))
return result_list
@staticmethod
def read_query_from_file(db_file
, query
, includeFilename=False
, categorical_columns:Optional[set[str]] = None
, numerical_columns:Optional[Union[dict[str, str], set[str]]] = None
):
data = BaseExtractor.read_sql_from_file(db_file, query, includeFilename)
# convert the data type of the explicitly named columns
data = BaseExtractor.convert_columns_dtype(data \
, categorical_columns = categorical_columns \
, numerical_columns = numerical_columns
)
return data
class OmnetExtractor(BaseExtractor):
r"""
A class for extracting and preprocessing data from a SQLite database.
This is the base class.
"""
yaml_tag = '!OmnetExtractor'
def __init__(self, /,
input_files:list
, categorical_columns:Optional[set[str]] = None
, numerical_columns:Optional[Union[dict[str, str], set[str]]] = None
, base_tags:Optional[List] = None
, additional_tags:Optional[list[str]] = None
, minimal_tags:bool = True
, simtimeRaw:bool = True
, moduleName:bool = True
, eventNumber:bool = True
, *args, **kwargs
):
super().__init__(input_files=input_files
, categorical_columns = categorical_columns
, numerical_columns = numerical_columns
, *args, **kwargs)
if base_tags is not None:
self.base_tags:list = base_tags
else:
if minimal_tags:
self.base_tags = BASE_TAGS_EXTRACTION_MINIMAL
else:
self.base_tags = BASE_TAGS_EXTRACTION_FULL
if additional_tags:
self.additional_tags:list = list(additional_tags)
else:
self.additional_tags:list = list()
self.minimal_tags:bool = minimal_tags
self.simtimeRaw:bool = simtimeRaw
self.moduleName:bool = moduleName
self.eventNumber:bool = eventNumber
@staticmethod
def apply_tags(data, tags, base_tags=None, additional_tags=[], minimal=True):
if base_tags:
allowed_tags = set(base_tags + additional_tags)
else:
if minimal:
allowed_tags = set(BASE_TAGS_EXTRACTION_MINIMAL + additional_tags)
else:
allowed_tags = set(BASE_TAGS_EXTRACTION + additional_tags)
applied_tags = []
# augment data with the extracted parameter tags
for tag in tags:
mapping = tag.get_mapping()
if list(mapping)[0] in allowed_tags:
data = data.assign(**mapping)
applied_tags.append(tag)
logd(f': {applied_tags=}')
return data
@staticmethod
def read_statistic_from_file(db_file, scalar, alias
, runId:bool=True
, moduleName:bool=True
, statName:bool=False
, statId:bool=False
, **kwargs):
query = sql_queries.generate_statistic_query(scalar
, runId=runId
, moduleName=moduleName
)
return OmnetExtractor.read_query_from_file(db_file, query, alias, **kwargs)
@staticmethod
def read_scalars_from_file(db_file, scalar, alias
, runId:bool=True
, moduleName:bool=True
, scalarName:bool=False
, scalarId:bool=False
, **kwargs):
query = sql_queries.generate_scalar_query(scalar, value_label=alias
, runId=runId
, moduleName=moduleName
, scalarName=scalarName, scalarId=scalarId)
return OmnetExtractor.read_query_from_file(db_file, query, alias, **kwargs)
@staticmethod
def read_signals_from_file(db_file, signal, alias
, simtimeRaw=True
, moduleName=True
, eventNumber=True
, **kwargs):
query = sql_queries.generate_signal_query(signal, value_label=alias
, moduleName=moduleName
, simtimeRaw=simtimeRaw
, eventNumber=eventNumber)
return OmnetExtractor.read_query_from_file(db_file, query, alias, **kwargs)
@staticmethod
def read_pattern_matched_signals_from_file(db_file, pattern, alias
, vectorName:bool=True
, simtimeRaw:bool=True
, moduleName:bool=True
, eventNumber:bool=True
, **kwargs):
query = sql_queries.generate_signal_like_query(pattern, value_label=alias
, vectorName=vectorName
, moduleName=moduleName
, simtimeRaw=simtimeRaw
, eventNumber=eventNumber)
return OmnetExtractor.read_query_from_file(db_file, query, alias, **kwargs)
@staticmethod
def read_pattern_matched_scalars_from_file(db_file, pattern, alias
, scalarName:bool=True
, moduleName:bool=True
, scalarId:bool=False
, runId:bool=False
, **kwargs):
query = sql_queries.generate_scalar_like_query(pattern, value_label=alias
, scalarName=scalarName
, moduleName=moduleName
, scalarId=scalarId
, runId=runId)
return OmnetExtractor.read_query_from_file(db_file, query, alias, **kwargs)
@staticmethod
def read_query_from_file(db_file, query, alias
, categorical_columns:Optional[set[str]]=None
, numerical_columns:Optional[Union[dict[str,str], set[str]]]=None
, base_tags = None, additional_tags = None
, minimal_tags=True
, simtimeRaw=True
, moduleName=True
, eventNumber=True
, includeFilename=False
, attributes_regex_map=tag_regex.attributes_regex_map
, iterationvars_regex_map=tag_regex.iterationvars_regex_map
, parameters_regex_map=tag_regex.parameters_regex_map
):
sql_reader = SqlLiteReader(db_file)
try:
tags = sql_reader.extract_tags(attributes_regex_map, iterationvars_regex_map, parameters_regex_map)
except Exception as e:
loge(f'>>>> ERROR: no tags could be extracted from {db_file}:\n {e}')
return pd.DataFrame()
data = BaseExtractor.read_sql_from_file(db_file
, query \
, includeFilename
)
data = OmnetExtractor.apply_tags(data, tags, base_tags=base_tags, additional_tags=additional_tags, minimal=minimal_tags)
# convert the data type of the explicitly named columns
data = BaseExtractor.convert_columns_dtype(data \
, categorical_columns = categorical_columns \
, numerical_columns = numerical_columns
)
return data
class RawStatisticExtractor(OmnetExtractor):
r"""
Extract the data for a signal from the `statistic` table of the input files specified.
Parameters
----------
input_files: List[str]
the list of paths to the input files, as literal path or as a regular expression
signal: str
the name of the signal which is to be extracted
alias: str
the name given to the column with the extracted signal data
runId: str
whether to extract the `runId` column as well
statName: str
whether to extract the `statName` column as well
statId: str
whether to extract the `statId` column as well
"""
yaml_tag = '!RawStatisticExtractor'
def __init__(self, /,
input_files:list
, signal:str
, alias:str
, runId:bool=True
, statName:bool=False
, statId:bool=False
, *args, **kwargs):
super().__init__(input_files=input_files, *args, **kwargs)
self.signal:str = signal
self.alias:str = alias
self.statName:bool = statName
self.statId:bool = statId
self.runId:bool = runId
def prepare(self):
data_set = DataSet(self.input_files)
# For every input file construct a `Delayed` object, a kind of a promise
# on the data and the leafs of the computation graph
result_list = []
for db_file in data_set.get_file_list():
res = dask.delayed(OmnetExtractor.read_statistic_from_file)\
(db_file, self.signal, self.alias
, moduleName = self.moduleName
, statName = self.statName
, statId = self.statId
, runId = self.runId
, categorical_columns = self.categorical_columns
, numerical_columns = self.numerical_columns
, base_tags = self.base_tags
, additional_tags = self.additional_tags
, minimal_tags = self.minimal_tags
, attributes_regex_map = self.attributes_regex_map
, iterationvars_regex_map = self.iterationvars_regex_map
, parameters_regex_map = self.parameters_regex_map
)
attributes = DataAttributes(source_file=db_file, alias=self.alias, common_root=data_set.get_common_root())
result_list.append((res, attributes))
return result_list
class RawScalarExtractor(OmnetExtractor):
r"""
Extract the data for a signal from the `scalar` table of the input files specified.
Parameters
----------
input_files: List[str]
the list of paths to the input files, as literal path or as a regular expression
signal: str
the name of the signal which is to be extracted
alias: str
the name given to the column with the extracted signal data
runId: str
whether to extract the `runId` column as well
scalarName: str
whether to extract the `scalarName` column as well
scalarId: str
whether to extract the `scalarId` column as well
"""
yaml_tag = '!RawScalarExtractor'
def __init__(self, /,
input_files:list
, signal:str
, alias:str
, runId:bool=True
, scalarName:bool=False
, scalarId:bool=False
, *args, **kwargs
):
super().__init__(input_files=input_files, *args, **kwargs)
self.signal:str = signal
self.alias:str = alias
self.runId:bool = runId
self.scalarName:bool = scalarName
self.scalarId:bool = scalarId
def prepare(self):
data_set = DataSet(self.input_files)
# For every input file construct a `Delayed` object, a kind of a promise
# on the data and the leafs of the computation graph
result_list = []
for db_file in data_set.get_file_list():
res = dask.delayed(OmnetExtractor.read_scalars_from_file)\
(db_file, self.signal, self.alias
, moduleName = self.moduleName
, scalarName = self.scalarName
, scalarId = self.scalarId
, runId = self.runId
, categorical_columns = self.categorical_columns
, numerical_columns = self.numerical_columns
, base_tags = self.base_tags
, additional_tags = self.additional_tags
, minimal_tags = self.minimal_tags
, attributes_regex_map = self.attributes_regex_map
, iterationvars_regex_map = self.iterationvars_regex_map
, parameters_regex_map = self.parameters_regex_map
)
attributes = DataAttributes(source_file=db_file, alias=self.alias, common_root=data_set.get_common_root())
result_list.append((res, attributes))
return result_list
class RawExtractor(OmnetExtractor):
r"""
Extract the data for a signal from the input files specified.
Parameters
----------
input_files: List[str]
the list of paths to the input files, as literal path or as a regular expression
signal: str
the name of the signal which is to be extracted
alias: str
the name given to the column with the extracted signal data
"""
yaml_tag = '!RawExtractor'
def __init__(self, /,
input_files:list
, signal:str
, alias:str
, *args, **kwargs):
super().__init__(input_files=input_files, *args, **kwargs)
self.signal:str = signal
self.alias:str = alias
def prepare(self):
data_set = DataSet(self.input_files)
# For every input file construct a `Delayed` object, a kind of a promise
# on the data and the leafs of the computation graph
result_list = []
for db_file in data_set.get_file_list():
res = dask.delayed(OmnetExtractor.read_signals_from_file)\
(db_file, self.signal, self.alias
, moduleName = self.moduleName
, eventNumber = self.eventNumber
, simtimeRaw = self.simtimeRaw
, categorical_columns = self.categorical_columns
, numerical_columns = self.numerical_columns
, base_tags = self.base_tags
, additional_tags = self.additional_tags
, minimal_tags = self.minimal_tags
, attributes_regex_map = self.attributes_regex_map
, iterationvars_regex_map = self.iterationvars_regex_map
, parameters_regex_map = self.parameters_regex_map
)
attributes = DataAttributes(source_file=db_file, alias=self.alias, common_root=data_set.get_common_root())
result_list.append((res, attributes))
return result_list
class PositionExtractor(OmnetExtractor):
r"""
Extract the data for a signal, with the associated positions, from the input files specified.
Parameters
----------
input_files: List[str]
the list of paths to the input files, as literal path or as a regular expression
x_signal: str
the name of the signal with the x-axis coordinates
x_alias: str
the name given to the column with the extracted x-axis position data
y_signal: str
the name of the signal with the y-axis coordinates
y_alias: str
the name given to the column with the extracted y-axis position data
signal: str
the name of the signal to extract
alias: str
the name given to the column with the extracted signal data
restriction: Optional[Union[Tuple[float], str]]
this defines a area restriction on the positions from which the signal
data is extracted, the tuple (x0, y0, x1, y1) defines the corners of
a rectangle
"""
yaml_tag = '!PositionExtractor'
def __init__(self, /,
input_files:list
, x_signal:str, x_alias:str
, y_signal:str, y_alias:str
, signal:str
, alias:str
, restriction:Optional[Union[Tuple[float], str]] = None
, *args, **kwargs
):
super().__init__(input_files=input_files, *args, **kwargs)
self.x_signal:str = x_signal
self.x_alias:str = x_alias
self.y_signal:str = y_signal
self.y_alias:str = y_alias
self.signal:str = signal
self.alias:str = alias
if restriction and isinstance(restriction, str):
self.restriction = eval(restriction)
else:
self.restriction = restriction
@staticmethod
def read_position_and_signal_from_file(db_file
, x_signal:str
, y_signal:str
, x_alias:str
, y_alias:str
, signal:str
, alias:str
, restriction:tuple=None
, moduleName:bool=True
, simtimeRaw:bool=True
, eventNumber:bool=False
, categorical_columns:Optional[set[str]]=None
, numerical_columns:Optional[Union[dict[str,str], set[str]]]=None
, base_tags = None, additional_tags = None
, minimal_tags=True
, attributes_regex_map=tag_regex.attributes_regex_map
, iterationvars_regex_map=tag_regex.iterationvars_regex_map
, parameters_regex_map=tag_regex.parameters_regex_map
):
sql_reader = SqlLiteReader(db_file)
try:
tags = sql_reader.extract_tags(attributes_regex_map, iterationvars_regex_map, parameters_regex_map)
except Exception as e:
loge(f'>>>> ERROR: no tags could be extracted from {db_file}:\n {e}')
return pd.DataFrame()
query = sql_queries.get_signal_with_position(x_signal=x_signal, y_signal=y_signal
, value_label_px=x_alias, value_label_py=y_alias
, signal_name=signal, value_label=alias
, restriction=restriction
, moduleName=moduleName
, simtimeRaw=simtimeRaw
, eventNumber=eventNumber
)
try:
data = sql_reader.execute_sql_query(query)
except Exception as e:
loge(f'>>>> ERROR: no data could be extracted from {db_file}:\n {e}')
return pd.DataFrame()
if 'rowId' in data.columns:
data = data.drop(labels=['rowId'], axis=1)
data = OmnetExtractor.apply_tags(data, tags, base_tags=base_tags, additional_tags=additional_tags, minimal=minimal_tags)
# convert the data type of the explicitly named columns
data = OmnetExtractor.convert_columns_dtype(data \
, categorical_columns = categorical_columns \
, numerical_columns = numerical_columns
)
return data
def prepare(self):
data_set = DataSet(self.input_files)
# For every input file construct a `Delayed` object, a kind of a promise
# on the data and the leafs of the computation graph
result_list = []
for db_file in data_set.get_file_list():
res = dask.delayed(PositionExtractor.read_position_and_signal_from_file)\
(db_file
, self.x_signal
, self.y_signal
, self.x_alias
, self.y_alias
, self.signal
, self.alias
, restriction=self.restriction
, moduleName=self.moduleName
, simtimeRaw=self.simtimeRaw
, eventNumber=self.eventNumber
, categorical_columns=self.categorical_columns \
, numerical_columns=self.numerical_columns \
, base_tags=self.base_tags, additional_tags=self.additional_tags
, minimal_tags=self.minimal_tags
)
attributes = DataAttributes(source_file=db_file, alias=self.alias, common_root=data_set.get_common_root())
result_list.append((res, attributes))
return result_list
class MatchingExtractor(OmnetExtractor):
r"""
Extract the data for multiple signals matching a regular expression, with
the associated positions, from the input files specified.
Parameters
----------
input_files: List[str]
the list of paths to the input files, as literal path or as a regular expression
pattern: str
the regular expression used for matching possible signal names
alias_pattern: str
the template string for naming the extracted signal
alias: str
the name given to the column with the extracted signal data
"""
yaml_tag = '!MatchingExtractor'
def __init__(self, /,
input_files:list
, pattern:str
, alias_pattern:str
, alias:str
, *args, **kwargs