-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.py
1834 lines (1507 loc) · 77.6 KB
/
node.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
import copy
import hashlib
import uuid
from abc import abstractmethod
from datetime import datetime
from typing import List
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
# from experiment_graph.execution_environment import ExecutionEnvironment
from experiment_graph.benchmark_helper import BenchmarkMetrics
from experiment_graph.globals import COMBINE_OPERATION_IDENTIFIER
from experiment_graph.graph.auxilary import DataFrame, DataSeries
from experiment_graph.graph.operations import UserDefinedFunction
DEFAULT_RANDOM_STATE = 15071989
AS_KB = 1024.0
class Node(object):
def __init__(self, node_id, execution_environment, underlying_data=None, size=None, unmaterializable=False):
self.id = node_id
self.computed = False
self.access_freq = 0
self.execution_environment = execution_environment
self.size = size
self.underlying_data = underlying_data
self.computed = False if underlying_data is None else True
self._unmaterializable = unmaterializable
@property
def unmaterializable(self):
return self._unmaterializable
@unmaterializable.setter
def unmaterializable(self, value: bool):
if not isinstance(value, bool):
raise TypeError('Unmaterializable can only be a boolean')
self._unmaterializable = value
def __getstate__(self):
state = self.__dict__.copy()
if 'execution_environment' in state:
del state['execution_environment']
return state
def remove_content(self):
del self.underlying_data
self.underlying_data = None
self.computed = False
def __setstate__(self, state):
self.__dict__.update(state)
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
for k, v in self.__dict__.items():
if k is 'execution_environment':
setattr(result, k, self.execution_environment)
else:
setattr(result, k, copy.deepcopy(v, memo))
return result
def set_environment(self, environment):
self.execution_environment = environment
@abstractmethod
def data(self, verbose):
"""
verbose = 0 ==> no logging
verbose = 1 ==> simple logging
:param verbose:
:return:
"""
pass
@abstractmethod
def get_materialized_data(self):
pass
@abstractmethod
def compute_size(self):
pass
@abstractmethod
def clear_content(self):
pass
def update_freq(self):
self.access_freq += 1
def get_freq(self):
return self.access_freq
# TODO: when params are a dictionary with multiple keys the order may not be the same in str conversion
@staticmethod
def edge_hash(oper, params=''):
return oper + '(' + str(params).replace(' ', '') + ')'
@staticmethod
def vertex_hash(prev, edge_hash):
# TODO what are the chances that this cause a collision?
# we should implement a collision strategy as well
return hashlib.md5((prev + edge_hash).encode('utf-8')).hexdigest().upper()
@staticmethod
def generate_uuid():
return uuid.uuid4().hex.upper()[0:8]
@staticmethod
def md5(val):
return hashlib.md5(val.encode('utf-8')).hexdigest()
@staticmethod
def get_not_none(nextnode, exist):
if exist is not None:
return exist
else:
return nextnode
# TODO: need to implement eager_mode when needed
def generate_agg_node(self, oper, args=None, v_id=None, unmaterializable=False):
v_id = self.id if v_id is None else v_id
args = {} if args is None else args
# nextid = self.generate_uuid()
edge_hash = self.edge_hash(oper, args)
nextid = self.vertex_hash(v_id, edge_hash)
nextnode = Agg(nextid, self.execution_environment, unmaterializable=unmaterializable)
exist = self.execution_environment.workload_dag.add_edge(v_id, nextid, nextnode,
{'name': oper,
'oper': 'p_' + oper,
'execution_time': -1,
'executed': False,
'args': args,
'hash': edge_hash},
ntype=Agg.__name__)
return self.get_not_none(nextnode, exist)
def generate_groupby_node(self, oper, args=None, v_id=None):
v_id = self.id if v_id is None else v_id
args = {} if args is None else args
# nextid = self.generate_uuid()
edge_hash = self.edge_hash(oper, args)
nextid = self.vertex_hash(v_id, edge_hash)
nextnode = GroupBy(nextid, self.execution_environment)
exist = self.execution_environment.workload_dag.add_edge(v_id, nextid, nextnode,
{'name': oper,
'oper': 'p_' + oper,
'execution_time': -1,
'executed': False,
'args': args,
'hash': edge_hash},
ntype=GroupBy.__name__)
return self.get_not_none(nextnode, exist)
def generate_sklearn_node(self, oper, args=None, v_id=None, should_warmstart=False, unmaterializable=False):
v_id = self.id if v_id is None else v_id
args = {} if args is None else args
edge_arguments = dict()
edge_arguments['should_warmstart'] = should_warmstart
edge_arguments['warm_startable'] = hasattr(args['model'], 'warm_start')
if edge_arguments['warm_startable']:
if hasattr(args['model'], 'random_state'):
edge_arguments['random_state'] = args['model'].random_state
no_random_state_model = copy.deepcopy(args['model'])
no_random_state_model.random_state = DEFAULT_RANDOM_STATE
edge_arguments['no_random_state_model'] = str(no_random_state_model)
edge_hash = self.edge_hash(oper, args)
nextid = self.vertex_hash(v_id, edge_hash)
nextnode = SK_Model(nextid, self.execution_environment, unmaterializable=unmaterializable)
edge_arguments['name'] = type(args['model']).__name__
edge_arguments['oper'] = 'p_' + oper
edge_arguments['args'] = args
edge_arguments['execution_time'] = -1
edge_arguments['executed'] = False
edge_arguments['hash'] = edge_hash
exist = self.execution_environment.workload_dag.add_edge(v_id, nextid, nextnode,
edge_arguments,
ntype=SK_Model.__name__)
return self.get_not_none(nextnode, exist)
def generate_dataset_node(self, oper, args=None, v_id=None, unmaterializable=False):
v_id = self.id if v_id is None else v_id
args = {} if args is None else args
# c_name = [] if c_name is None else c_name
# c_hash = [] if c_hash is None else c_hash
# nextid = self.generate_uuid()
edge_hash = self.edge_hash(oper, args)
nextid = self.vertex_hash(v_id, edge_hash)
nextnode = Dataset(nextid, self.execution_environment, unmaterializable=unmaterializable)
exist = self.execution_environment.workload_dag.add_edge(v_id, nextid, nextnode,
{'name': oper,
'oper': 'p_' + oper,
'execution_time': -1,
'executed': False,
'args': args,
'hash': edge_hash},
ntype=Dataset.__name__)
return self.get_not_none(nextnode, exist)
def generate_feature_node(self, oper, args=None, v_id=None, unmaterializable=False):
v_id = self.id if v_id is None else v_id
args = {} if args is None else args
# nextid = self.generate_uuid()
edge_hash = self.edge_hash(oper, args)
nextid = self.vertex_hash(v_id, edge_hash)
nextnode = Feature(nextid, self.execution_environment, unmaterializable=unmaterializable)
exist = self.execution_environment.workload_dag.add_edge(v_id, nextid, nextnode,
{'name': oper,
'execution_time': -1,
'executed': False,
'oper': 'p_' + oper,
'args': args,
'hash': edge_hash},
ntype=type(nextnode).__name__)
return self.get_not_none(nextnode, exist)
def generate_evaluation_node(self, oper, args=None, v_id=None):
v_id = self.id if v_id is None else v_id
args = {} if args is None else args
edge_hash = self.edge_hash(oper, args)
nextid = self.vertex_hash(v_id, edge_hash)
nextnode = Evaluation(nextid, self.execution_environment)
exist = self.execution_environment.workload_dag.add_edge(v_id, nextid, nextnode,
{'name': oper,
'execution_time': -1,
'executed': False,
'oper': 'p_' + oper,
'args': args,
'hash': edge_hash},
ntype=type(nextnode).__name__)
return self.get_not_none(nextnode, exist)
def generate_super_node(self, nodes, args=None):
args = {} if args is None else args
involved_nodes = []
for n in nodes:
involved_nodes.append(n.id)
# nextid = ''.join(involved_nodes)
edge_hash = self.edge_hash(COMBINE_OPERATION_IDENTIFIER, args)
nextid = self.vertex_hash(''.join(involved_nodes), edge_hash)
if not self.execution_environment.workload_dag.has_node(nextid):
nextnode = SuperNode(nextid, self.execution_environment, nodes)
self.execution_environment.workload_dag.add_node(nextid,
**{'type': type(nextnode).__name__,
'root': False,
'data': nextnode,
'size': 0,
'involved_nodes': involved_nodes})
for n in nodes:
# this is to make sure each combined edge is a unique name
# This is also used by the optimizer to find the other node when combine
# edges are being examined
self.execution_environment.workload_dag.graph.add_edge(n.id, nextid,
# combine is a reserved word
**{'name': COMBINE_OPERATION_IDENTIFIER,
'oper': COMBINE_OPERATION_IDENTIFIER,
'execution_time': -1,
'executed': False,
'args': args,
'hash': edge_hash})
return nextnode
else:
# TODO: add the update rule (even though it has no effect)
return self.execution_environment.workload_dag.graph.nodes[nextid]['data']
def run_udf(self, operation: UserDefinedFunction, other_inputs: "Node" or List["Node"] = None,
unmaterializable_result=False):
"""
:param operation:
:param other_inputs: For multi-input operators, this argument must be passed.
:param unmaterializable_result: set True if the result of running this operation should not be materialized
:return:
"""
super_node_id = None
if other_inputs is not None:
multi_input_nodes = [self]
if isinstance(other_inputs, list):
multi_input_nodes.extend(other_inputs)
else:
multi_input_nodes.append(other_inputs)
super_node = self.generate_super_node(multi_input_nodes, args={'c_oper': 'udf'})
super_node_id = super_node.id
return_type = operation.return_type
if return_type == Dataset.__name__:
return self.generate_dataset_node('udf', args={'operation': operation}, v_id=super_node_id,
unmaterializable=unmaterializable_result)
elif return_type == Feature.__name__:
return self.generate_feature_node('udf', args={'operation': operation}, v_id=super_node_id,
unmaterializable=unmaterializable_result)
elif return_type == Agg.__name__:
return self.generate_agg_node('udf', args={'operation': operation}, v_id=super_node_id,
unmaterializable=unmaterializable_result)
elif return_type == SK_Model.__name__:
return self.generate_sklearn_node('udf', args={'operation': operation}, v_id=super_node_id,
unmaterializable=unmaterializable_result)
else:
raise TypeError('Invalid return type: {}'.format(return_type))
def p_udf(self, operation: UserDefinedFunction):
result = operation.run(self.get_materialized_data())
return_type = operation.return_type
if return_type == Dataset.__name__:
new_hashes = [(self.md5(v + str(operation))) for v in result.columns]
return self.hash_and_return_dataframe(str(operation), result, column_names=result.columns,
column_hashes=new_hashes)
elif return_type == Feature.__name__:
new_c_hash = self.md5(result.name + str(operation))
return self.hash_and_return_dataseries(str(operation), result, c_name=result.name, c_hash=new_c_hash)
else:
return operation.run(self.get_materialized_data())
def store_dataframe(self, columns, df):
self.execution_environment.data_storage.store_dataframe(columns, df)
def store_feature(self, column, series):
self.execution_environment.data_storage.store_dataseries(column, series)
def find_column_index(self, c):
return self.get_column().index(c)
def get_c_hash(self, c):
i = self.find_column_index(c)
return self.get_column_hash()[i]
def generate_hash(self, column_map, func_name):
return {k: (self.md5(v + func_name)) for k, v in column_map.items()}
def hash_and_return_dataframe(self, func_name, df, column_names=None, column_hashes=None):
if column_names is None:
column_names = self.get_column()
if column_hashes is None:
column_hashes = self.get_column_hash()
new_c_hash = [(self.md5(v + func_name)) for v in column_hashes]
# self.execution_environment.data_storage.store_dataset(new_c_hash, df[column_names])
return DataFrame(column_names=column_names,
column_hashes=new_c_hash,
pandas_df=df[column_names])
def hash_and_return_dataseries(self, func_name, series, c_name=None, c_hash=None):
if c_name is None:
c_name = self.get_column()
if c_hash is None:
c_hash = self.get_column_hash()
new_c_hash = self.md5(c_hash + func_name)
# self.execution_environment.data_storage.store_column(new_c_hash, series)
return DataSeries(column_name=c_name,
column_hash=new_c_hash,
pandas_series=series)
class Agg(Node):
def __init__(self, node_id, execution_environment, underlying_data=None, size=None, unmaterializable=False):
Node.__init__(self, node_id, execution_environment, underlying_data, size)
def clear_content(self):
del self.underlying_data
self.underlying_data = None
self.computed = False
self.size = None
def data(self, verbose=0):
self.update_freq()
if not self.computed:
self.execution_environment.scheduler.schedule(
self.execution_environment.experiment_graph,
self.execution_environment.workload_dag,
self.id,
verbose)
self.computed = True
return self.get_materialized_data()
def get_materialized_data(self):
return self.underlying_data
def compute_size(self):
if self.computed and self.size is None:
start = datetime.now()
from pympler import asizeof
self.size = asizeof.asizeof(self.underlying_data) / AS_KB
self.execution_environment.update_time(BenchmarkMetrics.NODE_SIZE_COMPUTATION,
(datetime.now() - start).total_seconds())
return self.size
def show(self):
return self.id + " :" + self.get_materialized_data().__str__()
class Dataset(Node):
""" Dataset class representing a dataset (set of Features)
This class is analogous to pandas.core.frame.DataFrame
TODO:
* Integration with the graph library
* Add support for every experiment_graph that Pandas DataFrame supports
* Support for Python 3.x
"""
def __init__(self, node_id, execution_environment, underlying_data=None, size=None, unmaterializable=False):
"""
:type underlying_data: DataFrame
"""
Node.__init__(self, node_id, execution_environment, underlying_data, size, unmaterializable)
def clear_content(self):
del self.underlying_data
self.underlying_data = None
self.computed = False
self.size = None
def data(self, verbose=0):
self.update_freq()
if not self.computed:
self.execution_environment.scheduler.schedule(
self.execution_environment.experiment_graph,
self.execution_environment.workload_dag,
self.id,
verbose)
self.computed = True
return self.get_materialized_data()
def get_materialized_data(self):
return self.underlying_data.pandas_df
def get_column(self):
return self.underlying_data.column_names
def get_column_hash(self):
return self.underlying_data.column_hashes
def compute_size(self):
if not self.computed:
# This happens when compute_size is directly called by the user.
self.data()
if self.size is None:
start = datetime.now()
self.size = self.underlying_data.get_size()
self.execution_environment.update_time(BenchmarkMetrics.NODE_SIZE_COMPUTATION,
(datetime.now() - start).total_seconds())
return self.size
else:
return self.size
def set_columns(self, columns):
return self.generate_dataset_node('set_columns', {'columns': columns})
def p_set_columns(self, columns):
df = self.get_materialized_data().copy()
# self.execution_environment.data_storage.store_dataset(self.c_hash, df)
# df.columns = columns
return DataFrame(column_names=columns,
column_hashes=self.get_column_hash(),
pandas_df=df)
def rename(self, columns):
return self.generate_dataset_node('rename', {'columns': columns})
def p_rename(self, columns):
df = self.get_materialized_data().rename(columns=columns)
new_column_names = df.columns
return DataFrame(column_names=new_column_names,
column_hashes=self.get_column_hash(),
pandas_df=df)
def sample(self, n, random_state):
return self.generate_dataset_node('sample', {'n': n, 'random_state': random_state})
def p_sample(self, n, random_state):
return self.hash_and_return_dataframe('sample{}{}'.format(n, random_state),
self.get_materialized_data().sample(n=n, random_state=random_state))
def ffill(self):
return self.generate_dataset_node('ffill')
def p_ffill(self):
return self.hash_and_return_dataframe('ffill', self.get_materialized_data().ffill())
def project(self, columns):
if type(columns) in [str, int]:
return self.generate_feature_node('project', {'columns': columns})
if type(columns) is list:
return self.generate_dataset_node('project', {'columns': columns})
def p_project(self, columns):
if isinstance(columns, list):
p_columns = []
p_hashes = []
for c in columns:
p_columns.append(c)
p_hashes.append(self.get_c_hash(c))
# self.execution_environment.data_storage.store_dataset(p_hashes, self.get_materialized_data()[
# p_columns])
return DataFrame(column_names=p_columns,
column_hashes=p_hashes,
pandas_df=self.underlying_data.pandas_df[p_columns])
else:
# self.execution_environment.data_storage.store_column(self.get_c_hash(columns),
# self.get_materialized_data()[columns])
return DataSeries(column_name=columns,
column_hash=self.get_c_hash(columns),
pandas_series=self.underlying_data.pandas_df[columns])
# overloading the indexing operator similar operation to project
def __getitem__(self, index):
""" Overrides getitem method
If the index argument is of type string or a list, we apply a projection operator (indexing columns)
If the index argument is of type Feature, we apply a 'join' operator where we filter the data using values
in the Feature. The data in the feature must be of the form (index, Boolean)
TODO:
check how to implement the set_column operation, i.e. dataset['new_column'] = new_feature
"""
# project operator
if type(index) in [str, int, list]:
return self.project(index)
# index operator using another Series of the form (index,Boolean)
elif isinstance(index, Feature):
supernode = self.generate_super_node([self, index], {'c_oper': 'filter_with'})
return self.generate_dataset_node('filter_with', args={}, v_id=supernode.id)
else:
raise Exception('Unsupported operation. Only project (column index) is supported')
# TODO uncomment this after adding support for indices
# def set_index(self, keys):
# return self.generate_dataset_node('set_index', {'keys': keys})
#
# def p_set_index(self, keys):
# return self.hash_and_return_dataframe('set_index{}'.format(keys),
# self.get_materialized_data().set_index(keys=keys))
def reset_index(self):
return self.generate_dataset_node('reset_index')
# TODO room for improvement
# we re assigning a random hash to the new column, even though, if index column of two artifacts are the same
# the content will be the same
def p_reset_index(self):
df = self.underlying_data.pandas_df.reset_index()
new_column = df.columns[0]
# new_column_data = df.iloc[0]
new_c_hash = self.md5(self.generate_uuid())
# self.execution_environment.data_storage.store_column(new_c_hash, new_column_data)
# del df
# del new_column_data
return DataFrame(column_names=[new_column] + self.get_column(),
column_hashes=[new_c_hash] + self.get_column_hash(),
pandas_df=df)
def copy(self):
return self.generate_dataset_node('copy')
def p_copy(self):
return DataFrame(column_names=self.get_column(),
column_hashes=self.get_column_hash(),
pandas_df=self.underlying_data.pandas_df)
def head(self, size=5):
return self.generate_dataset_node('head', {'size': size})
def p_head(self, size=5):
return self.hash_and_return_dataframe('head{}'.format(size), self.get_materialized_data().head(size))
def shape(self):
return self.generate_agg_node('shape', {})
def p_shape(self):
return self.get_materialized_data().shape
def isnull(self):
return self.generate_dataset_node('isnull')
def p_isnull(self):
return self.hash_and_return_dataframe('isnull', self.get_materialized_data().isnull())
def sum(self):
return self.generate_agg_node('sum')
def p_sum(self):
return self.get_materialized_data().sum()
def nunique(self, dropna=True):
return self.generate_agg_node('nunique', {'dropna': dropna})
def p_nunique(self, dropna):
return self.get_materialized_data().nunique(dropna=dropna)
def dtypes(self):
return self.generate_agg_node('dtypes')
def p_dtypes(self):
return self.get_materialized_data().dtypes
def describe(self):
return self.generate_agg_node('describe')
def p_describe(self):
return self.get_materialized_data().describe()
def abs(self):
return self.generate_dataset_node('abs')
def p_abs(self):
return self.hash_and_return_dataframe('abs', self.get_materialized_data().abs())
def mean(self):
return self.generate_agg_node('mean')
def p_mean(self):
return self.get_materialized_data().mean()
def min(self):
return self.generate_agg_node('min')
def p_min(self):
return self.get_materialized_data().min()
def max(self):
return self.generate_agg_node('max')
def p_max(self):
return self.get_materialized_data().max()
def count(self):
return self.generate_agg_node('count')
def p_count(self):
return self.get_materialized_data().count()
def std(self):
return self.generate_agg_node('std')
def p_std(self):
return self.get_materialized_data().std()
def quantile(self, values):
return self.generate_agg_node('quantile', {'values': values})
def p_quantile(self, values):
return self.get_materialized_data().quantile(values=values)
def notna(self):
return self.generate_dataset_node('notna')
def p_notna(self):
return self.hash_and_return_dataframe('notna', self.get_materialized_data().notna())
def select_dtypes(self, data_type):
return self.generate_dataset_node('select_dtypes', {'data_type': data_type})
# TODO: do a proper grouping of the methods
# TODO: the dataframe shape and column names of some functions like select types and one hot encode
# TODO: can only be inferred after the operation is executed. We should group these functions
# (I think we are mentioning these in the paper as well)
def p_select_dtypes(self, data_type):
df = self.get_materialized_data().select_dtypes(data_type)
c_names = []
c_hashes = []
# find the selected subset
for c in df.columns:
c_names.append(c)
c_hashes.append(self.get_c_hash(c))
# self.execution_environment.data_storage.store_dataset(c_hashes, df[c_names])
return DataFrame(column_names=c_names,
column_hashes=c_hashes,
pandas_df=df[c_names])
# If drop column results in one column the return type should be a Feature
def drop(self, columns):
return self.generate_dataset_node('drop', {'columns': columns})
def p_drop(self, columns):
if isinstance(columns, str):
columns = [columns]
new_c = []
new_hash = []
for c in self.get_column():
if c not in columns:
new_c.append(c)
new_hash.append(self.get_c_hash(c))
# self.execution_environment.data_storage.store_dataset(new_hash, self.get_materialized_data()[new_c])
return DataFrame(column_names=new_c,
column_hashes=new_hash,
pandas_df=self.get_materialized_data()[new_c])
def dropna(self):
return self.generate_dataset_node('dropna')
def p_dropna(self):
return self.hash_and_return_dataframe('dropna', self.get_materialized_data().dropna())
def sort_values(self, col_name, ascending=False):
return self.generate_dataset_node('sort_values', args={'col_name': col_name, 'ascending': ascending})
def p_sort_values(self, col_name, ascending):
return self.hash_and_return_dataframe('sort_values{}{}'.format(col_name, ascending),
self.get_materialized_data().sort_values(col_name,
ascending=ascending).reset_index())
def add_columns(self, col_names, features):
if type(features) == list:
raise Exception('Currently only one column at a time is allowed to be added')
# supernode = self.generate_super_node([self] + features, {'col_names': col_names})
else:
supernode = self.generate_super_node([self, features], {'col_names': col_names, 'c_oper': 'add_columns'})
return self.generate_dataset_node('add_columns', {'col_names': col_names}, v_id=supernode.id)
def onehot_encode(self):
return self.generate_dataset_node('onehot_encode', {})
def p_onehot_encode(self):
df = pd.get_dummies(self.get_materialized_data())
new_column = []
new_hash = []
# create the md5 hash values for columns
for c in df.columns:
new_column.append(c)
if c in self.get_column():
new_hash.append(self.get_c_hash(c))
else:
# generate a unique prefix to make sure onehot encoding of different datasets with the same
# column name does not result in the same column hash
new_hash.append(self.md5(self.generate_uuid() + c))
# self.execution_environment.data_storage.store_dataset(new_hash, df[new_column])
return DataFrame(column_names=new_column,
column_hashes=new_hash,
pandas_df=df[new_column])
def corr(self):
return self.generate_agg_node('corr', {})
def p_corr(self):
return self.get_materialized_data().corr()
# TODO: is it OK to assume as_index is always false?
# we can recreate the original one anyway
# For now we materialize the result as an aggregate node so everything will be stored inside the graph
def groupby(self, col_names):
return self.generate_groupby_node('groupby', {'col_names': col_names, 'as_index': False})
# TODO create a new GroupBy underlying data type ( similar to DataFrame and DataSeries)
def p_groupby(self, col_names, as_index):
df = self.get_materialized_data().groupby(col_names, as_index=as_index)
if isinstance(col_names, str):
col_names = [col_names]
key = self.md5("".join(col_names))
new_key_columns = []
new_key_hashes = []
for c in col_names:
new_key_columns.append(c)
new_key_hashes.append(self.md5(self.get_c_hash(c) + 'groupkey' + key))
new_group_columns = []
new_group_hashes = []
for c in self.get_column():
# if it is , it's been added as part of the group key
if c not in col_names:
new_group_columns.append(c)
new_group_hashes.append(self.md5(self.get_c_hash(c) + 'group' + key))
return [df, new_key_columns, new_key_hashes, new_group_columns, new_group_hashes]
# combined node
def concat(self, nodes, axis=1):
if type(nodes) == list:
supernode = self.generate_super_node(nodes=[self] + nodes, args={'c_oper': 'concat', 'axis': axis})
else:
supernode = self.generate_super_node(nodes=[self] + [nodes], args={'c_oper': 'concat', 'axis': axis})
return self.generate_dataset_node('concat', v_id=supernode.id, args={'axis': axis})
# removes the columns that do not exist in the other dataframe
def align(self, other):
"""
Align is similar to pandas.align, however it only returns one dataset
example Dataset.align:
ds1.get_column() # ['1','2','3']
ds2.get_column() # ['2','3','4']
ds_aligned = ds1.align(ds2)
ds_aligned.get_column() # ['2','3']
example Pandas.align:
df1.get_column() # ['1','2','3']
df2.get_column() # ['2','3','4']
df1_aligned,df2_aligned = ds1.align(ds2)
df1_aligned.get_column() # ['2','3']
df2_aligned.get_column() # ['2','3']
If the user needs to align both datasets, he/she should call the function twice.
Note: currently, we only support 'inner' join and column-oriented aligning
:param other: other Dataset to align with
:return: original Dataset with the columns that do not exist in the other dataset removed
"""
supernode = self.generate_super_node([self, other], {'c_oper': 'align'})
return self.generate_dataset_node('align', v_id=supernode.id)
# dataframe merge operation operation of dataframes
def merge(self, other, on, how='left'):
supernode = self.generate_super_node([self, other], {'c_oper': 'merge'})
return self.generate_dataset_node('merge', args={'on': on, 'how': how}, v_id=supernode.id)
def fit_sk_model(self, model):
return self.generate_sklearn_node('fit_sk_model', {'model': model})
def fit_sk_model_with_labels(self, model, labels, custom_args=None, should_warmstart=False):
supernode = self.generate_super_node([self, labels], {'c_oper': 'fit_sk_model_with_labels'})
return self.generate_sklearn_node('fit_sk_model_with_labels', {'model': model, 'custom_args': custom_args},
v_id=supernode.id, should_warmstart=should_warmstart)
def p_fit_sk_model(self, model, warm_start=False):
start = datetime.now()
if warm_start:
model.warm_start = True
model.fit(self.get_materialized_data())
self.execution_environment.update_time(BenchmarkMetrics.MODEL_TRAINING,
(datetime.now() - start).total_seconds())
return model
def replace_columns(self, col_names, features):
if type(features) == list:
supernode = self.generate_super_node([self] + features,
{'col_names': col_names, 'c_oper': 'replace_columns'})
else:
supernode = self.generate_super_node([self, features],
{'col_names': col_names, 'c_oper': 'replace_columns'})
return self.generate_dataset_node('replace_columns', {'col_names': col_names}, v_id=supernode.id)
class Evaluation(Node):
def __init__(self, node_id, execution_environment, underlying_data=None, size=None):
Node.__init__(self, node_id, execution_environment, underlying_data, size)
def compute_size(self):
if self.computed and self.size is None:
start = datetime.now()
from pympler import asizeof
self.size = asizeof.asizeof(self.underlying_data) / AS_KB
self.execution_environment.update_time(BenchmarkMetrics.NODE_SIZE_COMPUTATION,
(datetime.now() - start).total_seconds())
return self.size
def clear_content(self):
del self.underlying_data
self.underlying_data = None
self.computed = False
self.size = None
def data(self, verbose=0):
self.update_freq()
if not self.computed:
self.execution_environment.scheduler.schedule(
self.execution_environment.experiment_graph,
self.execution_environment.workload_dag,
self.id,
verbose)
self.computed = True
return self.get_materialized_data()
def get_materialized_data(self):
return self.underlying_data
class Feature(Node):
""" Feature class representing one (and only one) column of a data.
This class is analogous to pandas.core.series.Series
"""
def __init__(self, node_id, execution_environment, underlying_data=None, size=None, unmaterializable=False):
"""
:type underlying_data: DataSeries
"""
Node.__init__(self, node_id, execution_environment, underlying_data, size, unmaterializable)
def clear_content(self):
self.underlying_data = None
self.computed = False
self.size = None
def dtype(self, verbose=0):
if not self.computed:
self.execution_environment.scheduler.schedule(
self.execution_environment.experiment_graph,
self.execution_environment.workload_dag,
self.id,
verbose)
self.computed = True
return self.get_materialized_data().dtype
def data(self, verbose=0):
self.update_freq()
if not self.computed:
self.execution_environment.scheduler.schedule(
self.execution_environment.experiment_graph,
self.execution_environment.workload_dag,
self.id,
verbose)
self.computed = True
return self.get_materialized_data()
def get_materialized_data(self):
return self.underlying_data.pandas_series
def get_column(self):
return self.underlying_data.column_name
def get_column_hash(self):
return self.underlying_data.column_hash
def compute_size(self):
if self.computed and self.size is None:
start = datetime.now()
self.size = self.underlying_data.get_size()
self.execution_environment.update_time(BenchmarkMetrics.NODE_SIZE_COMPUTATION,
(datetime.now() - start).total_seconds())
return self.size
else:
return self.size
def setname(self, name):
return self.generate_feature_node('setname', {'name': name})
def p_setname(self, name):
return DataSeries(column_name=name,
column_hash=self.get_column_hash(),
pandas_series=self.underlying_data.pandas_series)
def math(self, oper, other):
# If other is a Feature Column
if isinstance(other, Feature):
supernode = self.generate_super_node([self, other], {'c_oper': oper})
return self.generate_feature_node(oper, v_id=supernode.id)
# If other is a numerical value
else:
return self.generate_feature_node(oper, {'other': other})
# Overriding math operators
def __mul__(self, other):
return self.math('__mul__', other)
def p___mul__(self, other):
return self.hash_and_return_dataseries('__mul__{}'.format(other), self.get_materialized_data() * other)
def __rmul__(self, other):
return self.math('__rmul__', other)
def p___rmul__(self, other):
return self.hash_and_return_dataseries('__rmul__{}'.format(other), other * self.get_materialized_data())
def __truediv__(self, other):
return self.math('__truediv__', other)
def p___truediv__(self, other):
return self.hash_and_return_dataseries('__truediv__{}'.format(other), self.get_materialized_data() / other)
def __rtruediv__(self, other):
return self.math('__rtruediv__', other)
def p___rtruediv__(self, other):
return self.hash_and_return_dataseries('__rtruediv__{}'.format(other), other / self.get_materialized_data())
def __itruediv__(self, other):
return self.math('__itruediv__', other)
def p___itruediv__(self, other):
return self.hash_and_return_dataseries('__itruediv__{}'.format(other), other / self.get_materialized_data())
def __add__(self, other):
return self.math('__add__', other)
def p___add__(self, other):
return self.hash_and_return_dataseries('__add__{}'.format(other), self.get_materialized_data() + other)
def __radd__(self, other):
return self.math('__radd__', other)
def p___radd__(self, other):
return self.hash_and_return_dataseries('__radd__{}'.format(other), other + self.get_materialized_data())
def __sub__(self, other):
return self.math('__sub__', other)
def p___sub__(self, other):
return self.hash_and_return_dataseries('__sub_{}'.format(other), self.get_materialized_data() - other)
def __rsub__(self, other):
return self.math('__rsub__', other)