-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtpcds-95.py
1286 lines (1053 loc) · 39.8 KB
/
tpcds-95.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
import cPickle as pickle
import pandas as pd
import os
import numpy as np
import datetime
import table_schemas
from table_schemas import *
import sys
sys.path.append('/Users/qifan/anaconda/envs/test-environment/lib/python2.7/site-packages/s3fs-0.1.2-py2.7.egg/')
from s3fs import S3FileSystem
import pywren
import redis
from rediscluster import StrictRedisCluster
import time
from hashlib import md5
from io import StringIO
import boto3
from io import BytesIO
from multiprocessing.pool import ThreadPool
import logging
import random
# SELECT
# count(DISTINCT ws_order_number) AS `order count `,
# sum(ws_ext_ship_cost) AS `total shipping cost `,
# sum(ws_net_profit) AS `total net profit `
# FROM
# web_sales ws1, date_dim, customer_address, web_site
# WHERE
# d_date BETWEEN '1999-02-01' AND
# (CAST('1999-02-01' AS DATE) + INTERVAL 60 days)
# AND ws1.ws_ship_date_sk = d_date_sk
# AND ws1.ws_ship_addr_sk = ca_address_sk
# AND ca_state = 'IL'
# AND ws1.ws_web_site_sk = web_site_sk
# AND web_company_name = 'pri'
# AND EXISTS(SELECT *
# FROM web_sales ws2
# WHERE ws1.ws_order_number = ws2.ws_order_number
# AND ws1.ws_warehouse_sk <> ws2.ws_warehouse_sk)
# AND NOT EXISTS(SELECT *
# FROM web_returns wr1
# WHERE ws1.ws_order_number = wr1.wr_order_number)
# ORDER BY count(DISTINCT ws_order_number)
# LIMIT 100
scale = 100
parall_1 = 100
parall_2 = 100
parall_3 = 100
#storage_mode = 'local'
#storage_mode = 's3-only'
storage_mode = 's3-redis'
#execution_mode = 'local'
execution_mode = 'lambda'
pywren_rate = 1000
n_buckets = 1
hostnames = ["tpcds1.oapxhs.0001.usw2.cache.amazonaws.com"]
#"tpcds2.oapxhs.0001.usw2.cache.amazonaws.com"]
n_nodes = len(hostnames)
instance_type = "cache.r3.8xlarge"
wrenexec = pywren.default_executor(shard_runtime=True)
stage_info_load = {}
stage_info_filename = "stage_info_load_95.pickle"
if os.path.exists(stage_info_filename):
stage_info_load = pickle.load(open(stage_info_filename, "r"))
pm = [str(parall_1), str(parall_2), str(parall_3), str(pywren_rate), str(n_nodes)]
filename = "nomiti.cluster-" + storage_mode + '-tpcds-q95-scale' + str(scale) + "-" + "-".join(pm) + "-b" + str(n_buckets) + ".pickle"
#filename = "simple-test.pickle"
print("Scale is " + str(scale))
if storage_mode == 'local':
temp_address = "/Users/qifan/data/q95-temp/"
else:
temp_address = "scale" + str(scale) + "/q95-temp/"
def get_type(typename):
if typename == "date":
return datetime.datetime
if "decimal" in typename:
return np.dtype("float")
if typename == "int" or typename == "long":
return np.dtype("float")
if typename == "float":
return np.dtype(typename)
if typename == "string":
return np.dtype(typename)
raise Exception("Not supported type: " + typename)
def get_s3_locations(table):
print("WARNING: get from S3 locations, might be slow locally.")
s3 = S3FileSystem()
ls_path = os.path.join("qifan-tpcds-data", "scale" + str(scale), table)
all_files = s3.ls(ls_path)
return ["s3://" + f for f in all_files if f.endswith(".csv")]
def get_local_locations(table):
print("WARNING: get from local locations, might not work on lamdbda.")
files = []
path = "/Users/qifan/data/tpcds-scale10/" + table
for f in os.listdir(path):
if f.endswith(".csv"):
files.append(os.path.join(path, f))
return files
def get_name_for_table(tablename):
schema = table_schemas.schemas[tablename]
names = [a[0] for a in schema]
return names
def get_dtypes_for_table(tablename):
schema = table_schemas.schemas[tablename]
dtypes = {}
for a,b in schema:
dtypes[a] = get_type(b)
return dtypes
def read_local_table(key):
loc = key['loc']
names = list(key['names'])
names.append("")
dtypes = key['dtypes']
parse_dates = []
for d in dtypes:
if dtypes[d] == datetime.datetime or dtypes[d] == np.datetime64:
parse_dates.append(d)
dtypes[d] = np.dtype("string")
part_data = pd.read_table(loc,
delimiter="|",
header=None,
names=names,
usecols=range(len(names)-1),
dtype=dtypes,
na_values = "-",
parse_dates=parse_dates)
#print(part_data.info())
return part_data
def read_s3_table(key, s3_client=None):
loc = key['loc']
names = list(key['names'])
names.append("")
dtypes = key['dtypes']
parse_dates = []
for d in dtypes:
if dtypes[d] == datetime.datetime or dtypes[d] == np.datetime64:
parse_dates.append(d)
dtypes[d] = np.dtype("string")
if s3_client == None:
s3_client = boto3.client("s3")
data = []
if isinstance(key['loc'], str):
loc = key['loc']
obj = s3_client.get_object(Bucket='qifan-tpcds-data', Key=loc[22:])['Body'].read()
data.append(obj)
else:
for loc in key['loc']:
obj = s3_client.get_object(Bucket='qifan-tpcds-data', Key=loc[22:])['Body'].read()
data.append(obj)
part_data = pd.read_table(BytesIO("".join(data)),
delimiter="|",
header=None,
names=names,
usecols=range(len(names)-1),
dtype=dtypes,
na_values = "-",
parse_dates=parse_dates)
#print(part_data.info())
return part_data
def hash_key_to_index(key, number):
return int(md5(key).hexdigest()[8:], 16) % number
def my_hash_function(row, indices):
# print indices
#return int(sha1("".join([str(row[index]) for index in indices])).hexdigest()[8:], 16) % 65536
#return hashxx("".join([str(row[index]) for index in indices]))% 65536
#return random.randint(0,65536)
return hash("".join([str(row[index]) for index in indices])) % 65536
def add_bin(df, indices, bintype, partitions):
#tstart = time.time()
# loopy way to compute hvalues
#values = []
#for _, row in df.iterrows():
# values.append(my_hash_function(row, indices))
#hvalues = pd.DataFrame(values)
# use apply()
hvalues = df.apply(lambda x: my_hash_function(tuple(x), indices), axis = 1)
#print("here is " + str(time.time() - tstart))
#print(hvalues)
#print("here is " + str(time.time() - tstart))
if bintype == 'uniform':
#_, bins = pd.qcut(samples, partitions, retbins=True, labels=False)
bins = np.linspace(0, 65536, num=(partitions+1), endpoint=True)
elif bintype == 'sample':
samples = hvalues.sample(n=min(hvalues.size, max(hvalues.size/8, 65536)))
_, bins = pd.qcut(samples, partitions, retbins=True, labels=False)
else:
raise Exception()
#print("here is " + str(time.time() - tstart))
df['bin'] = pd.cut(hvalues, bins=bins, labels=False, include_lowest=False)
#print("here is " + str(time.time() - tstart))
return bins
def write_local_intermediate(table, output_loc):
output_info = {}
if 'bin' in table.columns:
slt_columns = table.columns.delete(table.columns.get_loc('bin'))
else:
slt_columns = table.columns
table.to_csv(csv_buffer, sep="|", header=False, index=False, columns=slt_columns)
output_info['loc'] = output_loc
output_info['names'] = slt_columns
output_info['dtypes'] = table.dtypes[slt_columns]
return output_info
def write_s3_intermediate(output_loc, table, s3_client=None):
csv_buffer = BytesIO()
if 'bin' in table.columns:
slt_columns = table.columns.delete(table.columns.get_loc('bin'))
else:
slt_columns = table.columns
table.to_csv(csv_buffer, sep="|", header=False, index=False, columns=slt_columns)
if s3_client == None:
s3_client = boto3.client('s3')
bucket_index = int(md5(output_loc).hexdigest()[8:], 16) % n_buckets
s3_client.put_object(Bucket="qifan-tpcds-" + str(bucket_index),
Key=output_loc,
Body=csv_buffer.getvalue())
output_info = {}
output_info['loc'] = output_loc
output_info['names'] = slt_columns
output_info['dtypes'] = table.dtypes[slt_columns]
return output_info
def write_redis_intermediate(output_loc, table, redis_client=None):
csv_buffer = BytesIO()
if 'bin' in table.columns:
slt_columns = table.columns.delete(table.columns.get_loc('bin'))
else:
slt_columns = table.columns
table.to_csv(csv_buffer, sep="|", header=False, index=False, columns=slt_columns)
if redis_client == None:
redis_index = hash_key_to_index(output_loc, len(hostnames))
redis_client = redis.StrictRedis(host=hostnames[redis_index], port=6379, db=0)
#redis_client = StrictRedisCluster(startup_nodes=startup_nodes, skip_full_coverage_check=True)
redis_client.set(output_loc, csv_buffer.getvalue())
output_info = {}
output_info['loc'] = output_loc
output_info['names'] = slt_columns
output_info['dtypes'] = table.dtypes[slt_columns]
return output_info
def write_local_partitions(df, column_names, bintype, partitions, storage):
#print(df.columns)
t0 = time.time()
indices = [df.columns.get_loc(myterm) for myterm in column_names]
#print(indices)
bins = add_bin(df, indices, bintype, partitions)
#print((bins))
#print(df)
t1 = time.time()
outputs_info = []
for bin_index in range(len(bins)):
split = df[df['bin'] == bin_index]
if split.size > 0:
output_info = {}
split.drop('bin', axis=1, inplace=True)
#print(split.dtypes)
# write output to storage
output_loc = storage + str(bin_index) + ".csv"
outputs_info.append(write_local_intermediate(split, output_loc))
#print(split.size)
t2 = time.time()
results = {}
results['outputs_info'] = outputs_info
results['breakdown'] = [(t1-t0), (t2-t1)]
return results
def write_s3_partitions(df, column_names, bintype, partitions, storage):
#print(df.columns)
t0 = time.time()
indices = [df.columns.get_loc(myterm) for myterm in column_names]
#print(indices)
bins = add_bin(df, indices, bintype, partitions)
t1 = time.time()
# print("t1 - t0 is " + str(t1-t0))
#print((bins))
#print(df)
s3_client = boto3.client("s3")
outputs_info = []
def write_task(bin_index):
split = df[df['bin'] == bin_index]
if split.size > 0 or split.size < 1:
# print(split.size)
split.drop('bin', axis=1, inplace=True)
#print(split.dtypes)
# write output to storage
output_loc = storage + str(bin_index) + ".csv"
outputs_info.append(write_s3_intermediate(output_loc, split, s3_client))
write_pool = ThreadPool(1)
write_pool.map(write_task, range(len(bins)))
write_pool.close()
write_pool.join()
t2 = time.time()
results = {}
results['outputs_info'] = outputs_info
results['breakdown'] = [(t1-t0), (t2-t1)]
return results
def write_redis_partitions(df, column_names, bintype, partitions, storage):
#print(df.columns)
t0 = time.time()
indices = [df.columns.get_loc(myterm) for myterm in column_names]
#print(indices)
bins = add_bin(df, indices, bintype, partitions)
t1 = time.time()
# print("t1 - t0 is " + str(t1-t0))
#print((bins))
#print(df)
redis_clients = []
pipes = []
for hostname in hostnames:
#redis_client = redis.StrictRedis(host=hostname, port=6379, db=0)
redis_client = redis.Redis(host=hostname, port=6379, db=0)
redis_clients.append(redis_client)
pipes.append(redis_client.pipeline())
#redis_client = redis.StrictRedis(host=redis_hostname, port=6379, db=0)
#redis_client = StrictRedisCluster(startup_nodes=startup_nodes, skip_full_coverage_check=True)
outputs_info = []
def write_task(bin_index):
split = df[df['bin'] == bin_index]
if split.size > 0 or split.size < 1:
# print(split.size)
#split.drop('bin', axis=1, inplace=True)
#print(split.dtypes)
# write output to storage
output_loc = storage + str(bin_index) + ".csv"
redis_index = hash_key_to_index(output_loc, len(hostnames))
#redis_client = redis_clients[redis_index]
redis_client = pipes[redis_index]
outputs_info.append(write_redis_intermediate(output_loc, split, redis_client))
write_pool = ThreadPool(1)
write_pool.map(write_task, range(len(bins)))
write_pool.close()
write_pool.join()
#for i in range(len(bins)):
# write_task(i)
t2 = time.time()
for pipe in pipes:
pipe.execute()
for redis_client in redis_clients:
redis_client.connection_pool.disconnect()
results = {}
results['outputs_info'] = outputs_info
results['breakdown'] = [(t1-t0), (t2-t1)]
return results
def read_local_intermediate(key):
names = list(key['names'])
dtypes = key['dtypes']
parse_dates = []
for d in dtypes:
if dtypes[d] == datetime.datetime or dtypes[d] == np.datetime64:
parse_dates.append(d)
dtypes[d] = np.dtype("string")
part_data = pd.read_table(key['loc'],
delimiter="|",
header=None,
names=names,
dtype=dtypes,
parse_dates=parse_dates)
return part_data
def read_s3_intermediate(key, s3_client=None):
bucket_index = int(md5(key['loc']).hexdigest()[8:], 16) % n_buckets
names = list(key['names'])
dtypes = key['dtypes']
parse_dates = []
for d in dtypes:
if dtypes[d] == datetime.datetime or dtypes[d] == np.datetime64:
parse_dates.append(d)
dtypes[d] = np.dtype("string")
if s3_client == None:
s3_client = boto3.client("s3")
#print('qifan-tpcds-' + str(bucket_index))
#print(key['loc'])
obj = s3_client.get_object(Bucket='qifan-tpcds-' + str(bucket_index), Key=key['loc'])
#print(key['loc'] + "")
part_data = pd.read_table(BytesIO(obj['Body'].read()),
delimiter="|",
header=None,
names=names,
dtype=dtypes,
parse_dates=parse_dates)
#print(part_data.info())
return part_data
def read_redis_intermediate(key, redis_client=None):
#bucket_index = int(md5(key['loc']).hexdigest()[8:], 16) % n_buckets
names = list(key['names'])
dtypes_raw = key['dtypes']
if isinstance(dtypes_raw, dict):
dtypes = dtypes_raw
else:
dtypes = {}
for i in range(len(names)):
dtypes[names[i]] = dtypes_raw[i]
#print(dtypes)
parse_dates = []
for d in dtypes:
if dtypes[d] == datetime.datetime or dtypes[d] == np.datetime64:
parse_dates.append(d)
dtypes[d] = np.dtype("string")
if redis_client == None:
redis_index = hash_key_to_index(key['loc'], len(hostnames))
redis_client = redis.StrictRedis(host=hostnames[redis_index], port=6379, db=0)
part_data = pd.read_table(BytesIO(redis_client.get(key['loc'])),
delimiter="|",
header=None,
names=names,
dtype=dtypes,
parse_dates=parse_dates)
#print(part_data.info())
return part_data
def convert_buffer_to_table(names, dtypes, data):
#bucket_index = int(md5(key['loc']).hexdigest()[8:], 16) % n_buckets
parse_dates = []
for d in dtypes:
if dtypes[d] == datetime.datetime or dtypes[d] == np.datetime64:
parse_dates.append(d)
dtypes[d] = np.dtype("string")
part_data = pd.read_table(BytesIO(data),
delimiter="|",
header=None,
names=names,
dtype=dtypes,
parse_dates=parse_dates)
#print(part_data.info())
return part_data
def mkdir_if_not_exist(path):
if storage_mode == 'local':
get_ipython().system(u'mkdir -p $path ')
def read_local_multiple_splits(names, dtypes, prefix, number_splits, suffix):
key = {}
key['names'] = names
dtypes_dict = {}
for i in range(len(names)):
dtypes_dict[names[i]] = dtypes[i]
key['dtypes'] = dtypes_dict
ds = []
for i in range(number_splits):
key['loc'] = prefix + str(i) + suffix
d = read_local_intermediate(key)
ds.append(d)
return pd.concat(ds)
def read_s3_multiple_splits(names, dtypes, prefix, number_splits, suffix):
dtypes_dict = {}
for i in range(len(names)):
dtypes_dict[names[i]] = dtypes[i]
ds = []
s3_client = boto3.client("s3")
def read_work(split_index):
key = {}
key['names'] = names
key['dtypes'] = dtypes_dict
key['loc'] = prefix + str(split_index) + suffix
d = read_s3_intermediate(key, s3_client)
ds.append(d)
read_pool = ThreadPool(1)
read_pool.map(read_work, range(number_splits))
read_pool.close()
read_pool.join()
return pd.concat(ds)
def read_redis_multiple_splits(names, dtypes, prefix, number_splits, suffix):
dtypes_dict = {}
for i in range(len(names)):
dtypes_dict[names[i]] = dtypes[i]
ds = []
#redis_client = redis.StrictRedis(host=redis_hostname, port=6379, db=0)
#redis_client = StrictRedisCluster(startup_nodes=startup_nodes, skip_full_coverage_check=True)
redis_clients = []
pipes = []
for hostname in hostnames:
#redis_client = redis.StrictRedis(host=hostname, port=6379, db=0)
redis_client = redis.Redis(host=hostname, port=6379, db=0)
redis_clients.append(redis_client)
pipes.append(redis_client.pipeline())
def read_work(split_index):
key = {}
#key['names'] = names
#key['dtypes'] = dtypes_dict
key['loc'] = prefix + str(split_index) + suffix
redis_index = hash_key_to_index(key['loc'], len(hostnames))
#redis_client = redis_clients[redis_index]
pipes[redis_index].get(key['loc'])
#redis_client = pipes[redis_index]
#d = read_redis_intermediate(key, redis_client)
#ds.append(d)
#read_pool = ThreadPool(64)
#read_pool.map(read_work, range(number_splits))
#read_pool.close()
#read_pool.join()
for i in range(number_splits):
read_work(i)
ps = time.time()
read_data = []
for pipe in pipes:
current_data = pipe.execute()
#print(len(current_data))
read_data.extend(current_data)
pe = time.time()
#print("pipe time : " + str(pe-ps))
for redis_client in redis_clients:
redis_client.connection_pool.disconnect()
#return pd.concat(ds)
#if None in read_data:
# print("None in read_data")
#print("number of Nones: " + str(len([None for v in read_data if v is None])) + " " + str(len(read_data)))
return convert_buffer_to_table(names, dtypes_dict, "".join(read_data))
def read_table(key):
if storage_mode == "local":
return read_local_table(key)
else:
return read_s3_table(key)
def read_multiple_splits(names, dtypes, prefix, number_splits, suffix):
if storage_mode == "local":
return read_local_multiple_splits(names, dtypes, prefix, number_splits, suffix)
elif storage_mode == "s3-only":
return read_s3_multiple_splits(names, dtypes, prefix, number_splits, suffix)
else:
return read_redis_multiple_splits(names, dtypes, prefix, number_splits, suffix)
def read_intermediate(key):
if storage_mode == "local":
return read_local_intermediate(key)
elif storage_mode == "s3-only":
return read_s3_intermediate(key)
else:
return read_redis_intermediate(key)
def write_intermediate(table, output_loc):
res = None
if storage_mode == "local":
res = write_local_intermediate(table, output_loc)
elif storage_mode == "s3-only":
res = write_s3_intermediate(table, output_loc)
else:
res = write_redis_intermediate(table, output_loc)
return pickle.dumps([res])
def write_partitions(df, column_names, bintype, partitions, storage):
res = None
if storage_mode == "local":
res = write_local_partitions(df, column_names, bintype, partitions, storage)
elif storage_mode == "s3-only":
res = write_s3_partitions(df, column_names, bintype, partitions, storage)
else:
res = write_redis_partitions(df, column_names, bintype, partitions, storage)
if 'outputs_info' in res and res['outputs_info'] != '':
res['outputs_info'] = pickle.dumps(res['outputs_info'])
return res
def get_locations(table):
if storage_mode == "local":
return get_local_locations(table)
else:
return get_s3_locations(table)
def execute_lambda_stage(stage_function, tasks):
t0 = time.time()
#futures = wrenexec.map(stage_function, tasks)
#pywren.wait(futures, 1, 64, 1)
for task in tasks:
task['write_output'] = True
futures = wrenexec.map_sync_with_rate_and_retries(stage_function, tasks, straggler=False, WAIT_DUR_SEC=5, rate=pywren_rate)
results = [f.result() for f in futures]
run_statuses = [f.run_status for f in futures]
invoke_statuses = [f.invoke_status for f in futures]
t1 = time.time()
res = {'results' : results,
't0' : t0,
't1' : t1,
'run_statuses' : run_statuses,
'invoke_statuses' : invoke_statuses}
return res
def execute_local_stage(stage_function, tasks):
stage_info = []
for task in tasks:
task['write_output'] = True
stage_info.append(stage_function(task))
res = {'results' : stage_info}
return res
def execute_stage(stage_function, tasks):
res = None
if execution_mode == 'local':
res = execute_local_stage(stage_function, tasks)
else:
res = execute_lambda_stage(stage_function, tasks)
for rr in res['results']:
if rr['info']['outputs_info'] != '':
rr['info']['outputs_info'] = pickle.loads(rr['info']['outputs_info'])
return res
# implementing all stages
def stage1(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cs = read_table(key)
t1 = time.time()
tr += t1 - t0
t0 = time.time()
wanted_columns = ['ws_order_number',
'ws_warehouse_sk']
cs_s = cs[wanted_columns]
t1 = time.time()
tc += t1 - t0
storage = output_address + "/part_" + str(key['task_id']) + "_"
res = write_partitions(cs_s, ['ws_order_number'], 'uniform', parall_1, storage)
outputs_info = res['outputs_info']
[tcc, tww] = res['breakdown']
tc += tcc
tw += tww
results = {}
info = {}
if 'write_output' in key and key['write_output']:
#print(outputs_info)
info['outputs_info'] = outputs_info
#results['info'] = {}
results['info'] = info
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
def stage2(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cs = read_multiple_splits(key['names'], key['dtypes'], key['prefix'], key['number_splits'], key['suffix'])
#return 1
t1 = time.time()
tr += t1 - t0
t0 = time.time()
wh_uc = cs.groupby(['ws_order_number']).agg({'ws_warehouse_sk':'nunique'})
target_order_numbers = wh_uc.loc[wh_uc['ws_warehouse_sk'] > 1].index.values
cs_sj_f1 = cs[['ws_order_number']]
cs_sj_f1.drop_duplicates(inplace=True)
cs_sj_f2 = cs_sj_f1.loc[cs_sj_f1['ws_order_number'].isin(target_order_numbers)]
t1 = time.time()
tc += t1 - t0
t0 = time.time()
storage = output_address + "/part_" + str(key['task_id']) + ".csv"
outputs_info = write_intermediate(storage, cs_sj_f2)
t1 = time.time()
tw += t1 - t0
results = {}
info = {}
if 'write_output' in key and key['write_output']:
info['outputs_info'] = outputs_info
#results['info'] = {}
results['info'] = info
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
def stage3(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cs = read_table(key)
t1 = time.time()
tr += t1 - t0
t0 = time.time()
wanted_columns = ['ws_order_number',
'ws_ext_ship_cost',
'ws_net_profit',
'ws_ship_date_sk',
'ws_ship_addr_sk',
'ws_web_site_sk',
'ws_warehouse_sk']
cs_s = cs[wanted_columns]
t1 = time.time()
tc += t1 - t0
storage = output_address + "/part_" + str(key['task_id']) + "_"
res = write_partitions(cs_s, ['ws_order_number'], 'uniform', parall_1, storage)
outputs_info = res['outputs_info']
[tcc, tww] = res['breakdown']
tc += tcc
tw += tww
results = {}
info = {}
if 'write_output' in key and key['write_output']:
info['outputs_info'] = outputs_info
#results['info'] = {}
results['info'] = info
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
def stage4(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cr = read_table(key)
t1 = time.time()
tr += t1 - t0
t0 = time.time()
storage = output_address + "/part_" + str(key['task_id']) + "_"
res = write_partitions(cr, ['wr_order_number'], 'uniform', parall_1, storage)
outputs_info = res['outputs_info']
[tcc, tww] = res['breakdown']
tc += tcc
tw += tww
results = {}
info = {}
if 'write_output' in key and key['write_output']:
info['outputs_info'] = outputs_info
results['info'] = info
#results['info'] = {}
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
def stage5(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
#print(key['names'])
#print(key['dtypes'])
cs = read_multiple_splits(key['names'], key['dtypes'], key['prefix'], key['number_splits'], key['suffix'])
cr = read_multiple_splits(key['names2'], key['dtypes2'], key['prefix2'], key['number_splits2'], key['suffix2'])
d = read_table(key['date_dim'])
#print(key['ws_wh'])
ws_wh = read_intermediate(key['ws_wh'])
#return 1
t1 = time.time()
tr += t1 - t0
t0 = time.time()
cs_sj_f1 = cs.loc[cs['ws_order_number'].isin(ws_wh['ws_order_number'])]
cs_sj_f2 = cs_sj_f1.loc[cs_sj_f1['ws_order_number'].isin(cr.wr_order_number)]
# join date_dim
dd = d[['d_date', 'd_date_sk']]
dd_select = dd[(pd.to_datetime(dd['d_date']) > pd.to_datetime('1999-02-01')) & (pd.to_datetime(dd['d_date']) < pd.to_datetime('1999-04-01'))]
dd_filtered = dd_select[['d_date_sk']]
merged = cs_sj_f2.merge(dd_filtered, left_on='ws_ship_date_sk', right_on='d_date_sk')
del dd
del cs_sj_f2
del dd_select
del dd_filtered
merged.drop('d_date_sk', axis=1, inplace=True)
# now partition with cs_ship_addr_sk
storage = output_address + "/part_" + str(key['task_id']) + "_"
t1 = time.time()
tc += t1 - t0
t0 = time.time()
#print(merged.dtypes)
res = write_partitions(merged, ['ws_ship_addr_sk'], 'uniform', parall_2, storage)
outputs_info = res['outputs_info']
[tcc, tww] = res['breakdown']
tc += tcc
tw += tww
results = {}
info = {}
if 'write_output' in key and key['write_output']:
info['outputs_info'] = outputs_info
results['info'] = info
#results['info'] = {}
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
# mkdir_if_not_exist(output_address)
def stage6(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cs = read_table(key)
t1 = time.time()
tr += t1 - t0
t0 = time.time()
storage = output_address + "/part_" + str(key['task_id']) + "_"
cs = cs[cs.ca_state == 'IL'][['ca_address_sk']]
t1 = time.time()
tc += t1 - t0
t0 = time.time()
res = write_partitions(cs, ['ca_address_sk'], 'uniform', parall_2, storage)
outputs_info = res['outputs_info']
[tcc, tww] = res['breakdown']
tc += tcc
tw += tww
results = {}
info = {}
if 'write_output' in key and key['write_output']:
info['outputs_info'] = outputs_info
results['info'] = info
#results['info'] = {}
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
def stage7(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cs = read_multiple_splits(key['names'], key['dtypes'], key['prefix'], key['number_splits'], key['suffix'])
ca = read_multiple_splits(key['names2'], key['dtypes2'], key['prefix2'], key['number_splits2'], key['suffix2'])
cc = read_table(key['web_site'])
t1 = time.time()
tr += t1 - t0
t0 = time.time()
merged = cs.merge(ca, left_on='ws_ship_addr_sk', right_on='ca_address_sk')
merged.drop('ws_ship_addr_sk', axis=1, inplace=True)
#list_addr = ['Williamson County', 'Williamson County', 'Williamson County', 'Williamson County', 'Williamson County']
cc_p = cc[cc['web_company_name'] == 'pri'][['web_site_sk']]
#print(cc['cc_country'])
merged2 = merged.merge(cc_p, left_on='ws_web_site_sk', right_on='web_site_sk')
toshuffle = merged2[['ws_order_number', 'ws_ext_ship_cost', 'ws_net_profit']]
storage = output_address + "/part_" + str(key['task_id']) + "_"
t1 = time.time()
tc += t1 - t0
t0 = time.time()
res = write_partitions(toshuffle, ['ws_order_number'], 'uniform', parall_3, storage)
outputs_info = res['outputs_info']
[tcc, tww] = res['breakdown']
tc += tcc
tw += tww
results = {}
info = {}
if 'write_output' in key and key['write_output']:
info['outputs_info'] = outputs_info
results['info'] = info
#results['info'] = {}
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
def stage8(key):
[tr, tc, tw] = [0] * 3
t0 = time.time()
output_address = key['output_address']
cs = read_multiple_splits(key['names'], key['dtypes'], key['prefix'], key['number_splits'], key['suffix'])
t1 = time.time()
tr += t1 - t0
t0 = time.time()
a1 = pd.unique(cs['ws_order_number']).size
a2 = cs['ws_ext_ship_cost'].sum()
a3 = cs['ws_net_profit'].sum()
t1 = time.time()
tc += t1 - t0
t0 = time.time()
results = {}
info = {}
info['outputs_info'] = ''
results['info'] = info
results['breakdown'] = [tr, tc, tw, (tc+tc+tw)]
return results
results = []
if os.path.exists(filename):
results = pickle.load(open(filename, "r"))
table = "web_sales"
names = get_name_for_table(table)