-
Notifications
You must be signed in to change notification settings - Fork 1
/
LIMITlib.py
executable file
·1830 lines (1644 loc) · 70.3 KB
/
LIMITlib.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 psycopg2
import time
import math
import numpy as np
import sys
import os
import random
import datetime
import random
import pycurl
import StringIO
import npVas as vas
import json
res_x = 1920 / 4
res_y = 1080 / 4
y0 = 21.146359
y1 = 49.012657
x1 = -74.349531
x0 = -126.391414
us_map = ((-170, -60), (15, 70))
ny_map = ((-74.129, -71.8298), (40.3153, 41.1069))
map=us_map
rv=(32,18)
ev=(480,270)
hv=(100,100)
yStep=(y1-y0)/res_y
xStep=(x1-x0)/res_x
##############Tweets ID########################################################
maxID=1009129304360288256
minID=862500001267011588
interval_size=293258606186553 #500
startID=862500001267011588
#############################################################################
##############Uber ID########################################################
# maxID=1412117940
# minID=1396310400
# startID=1396310400
#############################################################################
#############################################################################
##############Texi ID########################################################
# maxID=999999996
# minID=16
# startID=16
#############################################################################
#postgresql connection
conStr = "dbname='postgres' user='postgres' host='192.168.209.1' port='5432' password='liming' "
conn = psycopg2.connect(conStr)
cur = conn.cursor()
#oracle connection
# ora_conn=cx_Oracle.connect("system","Oracle123","curium.ics.uci.edu:1521/orcl")
# ora_cur=ora_conn.cursor()
def CreateBiasedDS(scale,newTab,srcTab='tweets',col='coordinate'):
try:
#cur.execute("truncate "+newTab)
print 'Old table found, deleted'
except psycopg2.InternalError:
print 'No old table found, creating table.'
cur.execute("create table "+newTab+" as select * from "+srcTab+" where 1=2")
xlist=range(0,scale)
ylist=range(0,scale)
random.shuffle(xlist)
random.shuffle(ylist)
xstep=(x1-x0)/scale
ystep=(y1-y0)/scale
for x in xlist:
for y in ylist:
rect="box'(("+str(x0+x*xstep)+","+str(y0+y*ystep)+"),("+str(x0+(x+1)*xstep)+","+str(y0+(y+1)*ystep)+"))'"
sql="insert into "+newTab+" select * from "+srcTab+" where "+col+" <@"+rect+" order by "+col+"<->point(0,0)"
cur.execute(sql)
cur.execute("commit")
print "Done."
def restart(version=9.6):
if sys.platform == 'darwin':
os.system('brew services stop postgresql')
os.system('brew services start postgresql')
elif sys.platform == 'linux2':
if version >= 9.5:
print 'sudo systemctl restart postgresql-' + str(version)
os.system('sudo systemctl restart postgresql-' + str(version))
else:
os.system('sudo systemctl restart postgresql')
i = 0
while i <= 10:
try:
conn = psycopg2.connect(conStr)
cur = conn.cursor()
break
except psycopg2.DatabaseError:
print 'wait 1s for db restarting ... ...'
time.sleep(1)
i += 1
if i > 10:
raise psycopg2.DatabaseError
# Return the coordinate of keyword from table tb, if limit is -1, then return all the records, order by is the id of the table.
def GetCoordinate(tb, keyword, limit=-1, orderby=False):
conn = psycopg2.connect(conStr)
cur = conn.cursor()
sql = "select count(*) from information_schema.columns where table_name='"+tb+"' and column_name='coordinate'"
cur.execute(sql)
hasPoint=cur.fetchall()[0][0]
if int(hasPoint) == 1:
sql = " select coordinate[0],coordinate[1] from " + tb + " where to_tsvector('english',text)@@to_tsquery('english','" + keyword + "')"
else:
sql = "select x,y from " + tb + " where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"')"
if orderby:
sql += " order by id"
if limit >= 0:
sql += " limit " + str(limit)
cur.execute(sql)
return cur.fetchall()
# get coordinates from oracle
def GetCoordinateOra(tb, keyword, limit=-1, orderby=False):
sql = "select x,y from " + tb + " where contains(text,'"+keyword+"')>0"
if orderby:
sql += " order by id"
if limit >= 0:
sql += " where rownum>= " + str(limit)
ora_cur.execute(sql)
return ora_cur.fetchall()
def GetCoordinateSMP(tb,keyword,r,method):
sql=""
if method=='B':
sql="select coordinate[0],coordinate[1] from "+tb+" tablesample bernoulli("+str(r)+") where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"')"
else:
sql="select coordinate[0],coordinate[1] from "+tb+" tablesample system("+str(r)+") where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"')"
cur.execute(sql)
return cur.fetchall()
def GetCoordinateUber(tb, base, limit=-1, orderby=False):
conn = psycopg2.connect(conStr)
cur = conn.cursor()
sql = "select coordinate[0],coordinate[1] from " + tb #+ " where category='"+base+"'"
if limit >= 0:
sql += " limit " + str(limit)
cur.execute(sql)
return cur.fetchall()
def GetCoordinateRange(tb,startID, endID):
conn = psycopg2.connect(conStr)
cur = conn.cursor()
sql = "select coordinate[0],coordinate[1] from " + tb +" where id between "+str(startID)+" and "+str(endID)
cur.execute(sql)
return cur.fetchall()
# Return the keywords in table tb, the lower and upper are the frequency bounds, k is the limit number of returned keywords.
def GetKeywords(tb, lower, upper, k):
conn = psycopg2.connect(conStr)
cur = conn.cursor()
sql = "select vector,count from " + tb + " where count>=" + str(lower) + " and count<" + str(
upper) + "order by count limit " + str(
k) # +" and vector not in (select distinct keyword from keyword_k_q) order by count"
cur.execute(sql)
return cur.fetchall()
# Map the coodrinates into cells, the type of 'ar' is the numpy array, r is the coordinate range of the map. the returned value H is the matrix of cells,
# each value is the number of records in the cell.
def hashByNumpy(ar, r=map,b=(res_x, res_y)):
H, x, y = np.histogram2d(ar[:, 0], ar[:, 1], bins=b, range=r)
return H
# L:LIMIT, S: Block based table sample, B: Record based table sample
def TimeQuality(wList,TabList,method='L',RatioL=1,RatioH=90,kStep=5):
for w in wList:
for tab in TabList:
fullRec=GetCoordinate(tab,w)
pImageLen=imageLen(np.array(fullRec))
for r in range(RatioL,RatioH+1,kStep):
if method=='L':
k=int(float(r)/100.0*len(fullRec))
sql="select coordinate from "+tab+" where to_tsvector('english',text)@@to_tsquery('english','"+w+"') limit "+str(k)
print w,tab,'LIMIT',len(fullRec),r,imageLen(np.array(fullRec[:k]))/float(pImageLen),SQLexeTime(sql)
elif method=='B':
sql="select coordinate from "+tab+" tablesample bernoulli("+str(r)+") where to_tsvector('english',text)@@to_tsquery('english','"+w+"')"
print w,tab,'BERNOULLI',len(fullRec),r,imageLen(np.array(GetCoordinateSMP(tab,w,r,method)))/float(pImageLen),SQLexeTime(sql)
elif method=='S':
sql="select coordinate from "+tab+" tablesample system("+str(r)+") where to_tsvector('english',text)@@to_tsquery('english','"+w+"')"
print w,tab,'SYSTEM',len(fullRec),r,imageLen(np.array(GetCoordinateSMP(tab,w,r,method)))/float(pImageLen),SQLexeTime(sql)
else:
print 'Unrecognized sampling method:', method
def imageLen(array):
return np.count_nonzero(hashByNumpy(array))
# return the mse of two matrix
def myMSE(m1,m2, binary=True):#m1, m2 are the matrixs of the ground-truth map and approximate map
if binary:
m1=np.where(m1>0,1,0) #convert each element to 0 or 1
m2=np.where(m2>0,1,0) #convert each element to 0 or 1
err=0
for i in range(0, len(m1)):
for j in range(0,len(m1[0])):
err+=(m1[i][j]-m2[i][j])**2
return math.sqrt(err)/(len(m1)*len(m1[0]))
# err=math.sqrt(np.sum((m1-m2)**2))
# err/=float(len(m1)*len(m1[0]))
# return err
#Use binary search to find the k that have quality Q in coordinate ar.
def findkofQ(ar, Q):
perfectLen = imageLen(np.array(ar))
i = 0.0
l = 0.0
h = 100.0
similarity = 0.0
iterTimes = 0
while (similarity < 0.85 or similarity > 0.86) and iterTimes < 10:
if similarity < 0.85:
l = i
i = (h + i) / 2
else:
h = i
i = (i + l) / 2
k = int(i * len(ar) / 100)
sampleLen = imageLen(np.array(ar[:k]))
similarity = float(sampleLen) / perfectLen
iterTimes += 1
return i
#Find the k of hybrid queries, w:keyword, q:quality, tb: original data table, hybridtab: offline sample table
def kOfHybridQueries(w, q, tb,hybridtab='null'):
coord = GetCoordinate(tb, w, -1)
if len(coord) < 5000:
return 0
offlineHs = np.zeros(shape=ev, dtype=int)
if hybridtab is not 'null':
offlinecoord = GetCoordinate(hybridtab, w, -1)
offlineHs = hashByNumpy(np.array(offlinecoord))
ar = np.array(coord)
H = hashByNumpy(ar)#matrix of from the original data table
perfectLen = np.count_nonzero(H)
i = 0.0
l = 0.0
h = 100.0
similarity = 0.0
iterTimes = 0
#binary search of k for quality q, max iteration times is 20
while (similarity < q or similarity > q * 1.01) and iterTimes < 20:
if similarity < q:
l = i
i = (h + i) / 2
else:
h = i
i = (i + l) / 2
k = int(i * len(ar) / 100)
Hs = hashByNumpy(ar[:k])
if hybridtab is not 'null':#combine the online subset with the offline subset
Hs += offlineHs
sampleLen = np.count_nonzero(Hs)
similarity = float(sampleLen) / perfectLen
iterTimes += 1
return k
def kOfHybridQueriesUber(w, q, tb,hybridtab='null'):
coord = GetCoordinateUber(tb, w, -1)
if len(coord) < 5000:
return 0
offlineHs = np.zeros(shape=ev, dtype=int)
if hybridtab is not 'null':
offlinecoord = GetCoordinateUber(hybridtab, w, -1)
offlineHs = hashByNumpy(np.array(offlinecoord))
ar = np.array(coord)
H = hashByNumpy(ar)#matrix of from the original data table
perfectLen = np.count_nonzero(H)
i = 0.0
l = 0.0
h = 100.0
similarity = 0.0
iterTimes = 0
#binary search of k for quality q, max iteration times is 20
while (similarity < q or similarity > q * 1.01) and iterTimes < 20:
if similarity < q:
l = i
i = (h + i) / 2
else:
h = i
i = (i + l) / 2
k = int(i * len(ar) / 100)
Hs = hashByNumpy(ar[:k])
if hybridtab is not 'null':#combine the online subset with the offline subset
Hs += offlineHs
sampleLen = np.count_nonzero(Hs)
similarity = float(sampleLen) / perfectLen
iterTimes += 1
return k
# find k of hybird queries in oracle, the only difference is call of GetCoordinate
def kOfHybridQueriesOra(w, q, tb,hybridtab='null'):
coord = GetCoordinateOra(tb, w, -1)
if len(coord) < 5000:
return 0
offlineHs = np.zeros(shape=ev, dtype=int)
if hybridtab is not 'null':
offlinecoord = GetCoordinateOra(hybridtab, w, -1)
offlineHs = hashByNumpy(np.array(offlinecoord))
ar = np.array(coord)
H = hashByNumpy(ar)#matrix of from the original data table
perfectLen = np.count_nonzero(H)
i = 0.0
l = 0.0
h = 100.0
similarity = 0.0
iterTimes = 0
#binary search of k for quality q, max iteration times is 20
while (similarity < q or similarity > q * 1.01) and iterTimes < 20:
if similarity < q:
l = i
i = (h + i) / 2
else:
h = i
i = (i + l) / 2
k = int(i * len(ar) / 100)
Hs = hashByNumpy(ar[:k])
if hybridtab is not 'null':#combine the online subset with the offline subset
Hs += offlineHs
sampleLen = np.count_nonzero(Hs)
similarity = float(sampleLen) / perfectLen
iterTimes += 1
return k
#fine the trend of k when scaling ataset
def ScaleDataSize(kwList,tab):
for w in kwList:
coord = GetCoordinate(tab, w, -1)
for s in range(10, 101, 10):
size = s * len(coord) / 100
scoord = coord[:size]
r = findkofQ(scoord, 0.85)
print w, 'dataset size:',size,'85% quality:',r * size/100
#Load state polygons to db from file
def loadStatePolygon():
poly = demjson.decode_file("state.json")
for state in poly['features']:
name = state['properties']['name']
polys = state['geometry']['coordinates']
for p in polys:
coords = "'" + str(p).replace('[', '(').replace(']', ')')[1:-1] + "'"
sql = "insert into statepolygon values('" + name + "'," + coords + ")"
cur.execute(sql)
print name
cur.execute('commit')
#update the column of state in coordtweets
def updateStateField():
cur.execute("select id from coordtweets")
ids = cur.fetchall()
i = 0
for id in ids:
name = "NULL"
cur.execute("select state from statepolygon where poly@>(select coordinate from coordtweets where id=" + str(
id[0]) + ") limit 1")
res = cur.fetchall()
if len(res) > 0:
name = res[0][0]
cur.execute("update coordtweets set state='" + name + "' where id=" + str(id[0]))
i += 1
print i, id
cur.execute('commit')
#produce count map of subset LIMIT k
def countMap(w, k=4000000):
sql = "select state, count(*) from (select state,id from coordtweets where to_tsvector('english',text)@@to_tsquery('english','" + w + "') limit " + str(
k) + ") t group by t.state"
cur.execute(sql)
return cur.fetchall()
#use the distributed precision to compute the count map quality, s and e are the start and end frequency
def countMapQuality(s, e):
keywords = GetKeywords('vectorcount', s, e, 1000)
for w in keywords:
gt = dict((x, y) for x, y in countMap(w[0]))
for i in gt.keys():
gt[i] = float(gt[i]) / w[1]
for r in range(1, 101, 1):
k = r * w[1] / 100
sub = dict((x, y) for x, y in countMap(w[0], k))
for i in sub.keys():
sub[i] = float(sub[i]) / k
e = 0.0
for i in gt.keys():
if sub.has_key(i):
e += math.pow((gt[i] - sub[i]), 2)
else:
e += math.pow(gt[i], 2)
print w[0], r / 1000, k, math.sqrt(e)
def getError(gt, freq, sub, k):
e = 0.0
for i in gt.keys():
if sub.has_key(i):
e += math.pow(float(gt[i]) / freq - float(sub[i]) / k, 2)
else:
e += math.pow(float(gt[i]) / freq, 2)
return math.sqrt(e)
def countMapQualityMem(s, e):
keywords = GetKeywords('vectorcount', s, e, 1000)
for w in keywords:
cur.execute(
"select state from coordtweets where to_tsvector('english',text)@@to_tsquery('english','" + w[0] + "')")
res = cur.fetchall()
freq = len(res)
gt = {}
for i in res:
if gt.has_key(i[0]):
gt[i[0]] += 1
else:
gt[i[0]] = 1
for r in range(1, 201, 1):
k = r * w[1] / 1000
sub = {}
for i in range(0, k):
if sub.has_key(res[i][0]):
sub[res[i][0]] += 1
else:
sub[res[i][0]] = 1
print w[0], float(k) / w[1], getError(gt, freq, sub, k)
#compare k in online, online+offline, s,e are the start and end frequencies, tb is the original data table
def kComparison(s, e, tb):
keywords = GetKeywords('vectorcount', s, e, 100)
for w in keywords:
online = kOfHybridQueries(w[0], 0.85, tb)#online
offset0 = (kOfHybridQueries(w[0], 0.85, tb, 'gridsample0'))#online+stratified sample
offset50 = (kOfHybridQueries(w[0], 0.85, tb, 'gridsample50'))#onlien+stratified sample+ sample from tail
offsetalpha = (kOfHybridQueries(w[0], 0.85, tb, 'gridsample'))#onlien+stratified sample+ sample from tail+reducing #records in cells of LIMIT k
if online > 0:
print w[0], w[1], online, offset0, offset50, offsetalpha
# find the k of each cell that how many records need to be scanned to find the keyword
def FindFirstIndexofKeyword(keyword):
for x in range(0,res_x):
for y in range(0,res_y):
bottomleftX=x0+xStep*x
bottomleftY=y0+yStep*y
toprightX=x0+xStep*(x+1)
toprightY=y0+yStep*(y+1)
box="box '("+str(bottomleftX)+","+str(bottomleftY)+"),("+str(toprightX)+","+str(toprightY)+")'"
sql="select text from coordtweets where "+box+"@>coordinate"
cur.execute(sql)
texts=cur.fetchall()
i=0
found=False
for text in texts:
i+=1
sql="select to_tsvector('english','"+text[0].replace("'"," ")+"')@@to_tsquery('english','"+keyword+"')"
cur.execute(sql)
result=cur.fetchall()
if result[0][0]:
found=True
break
if found:
cur.execute("insert into firstindex values('"+keyword+"',"+str(x)+","+str(y)+","+str(i)+","+str(len(texts))+")")
else:
cur.execute("insert into firstindex values('"+keyword+"',"+str(x)+","+str(y)+","+str(0)+","+str(len(texts))+")")
cur.execute("commit")
#find the max density of the map
def maxDensity(tb):
for x in range(0,res_x):
for y in range(0,res_y):
bottomleftX=x0+xStep*x
bottomleftY=y0+yStep*y
toprightX=x0+xStep*(x+1)
toprightY=y0+yStep*(y+1)
box="box '("+str(bottomleftX)+","+str(bottomleftY)+"),("+str(toprightX)+","+str(toprightY)+")'"
sqlcnt="select count(*) from "+tb+" where "+box+"@>coordinate"
cur.execute(sqlcnt)
cnt=cur.fetchall()
if cnt[0][0]>dmax:
dmax=cnt[0][0]
#alpha=0: use pure stratified sampling
#alpha=x: the #records in each cell is proportional to its density, the cells that density>(1/alpha)* max_density have no records.
def stratifiedSampling(k,alpha=0):
i=0
j=0
dmax=maxDensity('coordtweets')#the max density of coordtweets is 399,000.
for x in range(0,res_x):
for y in range(0,res_y):
tmpoffset=0
bottomleftX=x0+xStep*x
bottomleftY=y0+yStep*y
toprightX=x0+xStep*(x+1)
toprightY=y0+yStep*(y+1)
box="box '("+str(bottomleftX)+","+str(bottomleftY)+"),("+str(toprightX)+","+str(toprightY)+")'"
sqlcnt="select count(*) from coordtweets where "+box+"@>coordinate"
cur.execute(sqlcnt)
cnt=cur.fetchall()
if cnt[0][0]==0:
continue
tmpk=int(k*float(max(0,dmax-alpha*cnt[0][0]))/dmax)
if cnt[0][0]>=tmpk:
tmpoffset=cnt[0][0]-tmpk
else:
tmpoffset=0
sql="insert into gridsample select * from coordtweets where "+box+"@>coordinate offset "+str(tmpoffset)+" limit "+str(tmpk)
cur.execute(sql)
print res_x,x,res_y,y,cnt[0][0],tmpoffset,tmpk
cur.execute('commit')
print "Grid Sample: k="+str(k)
# Get curves of keyword w in table tab, start k=10%, end k=90%
def Curves(w,tab):
coord=GetCoordinate(tab,w)
print w,len(coord)
perfectImageLen=imageLen(np.array(coord))
for r in range(10,100,10):
subLen=int(float(r)*len(coord)/100.0)
aprxImageLen=imageLen(np.array(coord[:subLen]))
print r,float(aprxImageLen)/perfectImageLen
#k: the threshold of #records for each cell
#refTab: the table created by using LIMIT k of original datatable without contains keyword.
def gridSampleTopCells(k,refTab,smpTab,srcTab):
cur.execute("create table if not exists "+smpTab+" as select * from tweets where 1=2")
cur.execute("commit")
totaltime=0
for x in range(0,res_x):
for y in range(0,res_y):
tmpoffset=0
bottomleftX=x0+xStep*x
bottomleftY=y0+yStep*y
toprightX=x0+xStep*(x+1)
toprightY=y0+yStep*(y+1)
box="box '("+str(bottomleftX)+","+str(bottomleftY)+"),("+str(toprightX)+","+str(toprightY)+")'"
#remove top n cells
sql="select count(*) from "+refTab+" where "+box+"@>coordinate"
cur.execute(sql)
cnt=cur.fetchall()[0][0]
if cnt>=k:
continue
else:
tmpk=k-cnt
# sqlcnt="select count(*) from tweets where "+box+"@>coordinate"
# cur.execute(sqlcnt)
# cnt=cur.fetchall()
# if cnt[0][0]>=tmpk:
# tmpoffset=cnt[0][0]-tmpk
# else:
# tmpoffset=0
# if cnt[0][0]>0:
t1=time.time()
sql="insert into "+smpTab+" select * from "+srcTab+" where "+box+"@>coordinate offset "+str(cnt)+" limit "+str(tmpk)##str(tmpoffset)
cur.execute(sql)
t2=time.time()
print res_x,x,res_y,y,cnt,tmpk
totaltime+=t2-t1
cur.execute('commit')
print "Grid Sample: k="+str(k)+", net time:"+str(totaltime)
# using the random function to get a random sample for each cell.
def gridSampleRandomFunction():
cur.execute("create table if not exists vas_ss3 as select * from tweets where 1=2")
cur.execute("commit")
totaltime=0
for x in range(0,res_x):
for y in range(0,res_y):
tmpoffset=0
bottomleftX=x0+xStep*x
bottomleftY=y0+yStep*y
toprightX=x0+xStep*(x+1)
toprightY=y0+yStep*(y+1)
box="box '("+str(bottomleftX)+","+str(bottomleftY)+"),("+str(toprightX)+","+str(toprightY)+")'"
#remove top n cells
sql="select count(*) from ss3 where "+box+"@>coordinate"
cur.execute(sql)
cnt=cur.fetchall()[0][0]
if cnt==0:
continue
print x,y
sql="select count(*) from rnd5 where "+box+"@>coordinate"
cur.execute(sql)
cnt2=cur.fetchall()[0][0]
r=float(cnt)/float(cnt2)
sql="insert into vas_ss3 select * from rnd5 where "+box+"@>coordinate and random()<="+str(r)
cur.execute(sql)
cur.execute('commit')
print "Grid Sample: k="+str(k)+", net time:"+str(totaltime)
#get k of original, offline sample. tab is the original data table, ss is the sample lsit, wlist is the keyword list, quality is the specified quality
def KofQueries(tab,ss,wlist,quality):
kwList=wlist##freq: 50k,500k,1M,2M
stratSampleList=[ss]
origTab=tab
for kw in kwList:
##A. Original query, get the number of all records that contain the keyword, and time
freq=len(lmt.GetCoordinate(origTab,kw,-1))
print tab,kw,freq,'null','0','1'
##B. Online sampling (LIMIT K), get the number of records of quality=quality, and time
for q in quality:
k=lmt.kOfHybridQueries(kw,q,origTab)
print tab,kw,k,'null','0',q
##C. Online sampling + Offline sampling
for smp in stratSampleList:
k0=len(lmt.GetCoordinate(smp, kw, -1))## #records in offline sample
k1=lmt.kOfHybridQueries(kw,q,origTab,smp)
print tab,kw,k1,smp,k0,q
def SQLexeTime(sql,times=1):
totalTime=0.0
for i in range(0,times):
cur.execute("select count(*) from (select coordinate from dummyTab) a")
cur.execute("select count(*) from dummyTab where to_tsvector('english',text)@@to_tsquery('english','veteran')")
s=time.time()
cur.execute(sql)
e=time.time()
totalTime+=e-s
return totalTime/times
# get execution time of keyword on table. dataset is the original data table, k1 is the k of original data table, smpTab is the sample table, k0 is the k of sample table.
def getExeTime(dataset='BiasedUber',keyword='B02512',k1=1000,smpTab='smp',k0=100):
#limitSQL="select * from "+dataset+" where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"') limit "+k1
#sampleSQL="select * from "+smpTab+" where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"') limit "+k0
limitSQL="select * from BiasedUber tablesample system(65) where category='B02512'"
sampleSQL="select * from BiasedUber where category='B02512'"
###
dummySQL="select count(*) from (select coordinate from dummytab) a"
dummySQL2="select count(*) from tweets where to_tsvector('english',text)@@to_tsquery('english','veteran')"
limitT=0.0
sampleT=0.0
for i in range(0,5):
#lmt.restart()
cur.execute(dummySQL)
cur.execute(dummySQL2)
ts=time.time()
cur.execute(limitSQL)
te=time.time()
limitT+=te-ts
cur.execute(dummySQL)
cur.execute(dummySQL2)
ts=time.time()
cur.execute(sampleSQL)
te=time.time()
sampleT+=te-ts
return limitT/5.0,sampleT/5.0
# get the accessed blocks of a query in postgresql.
def CountBlocks(dataset,keyword,k1,smpTab,k0):
explainSQL="explain(analyze,buffers) "+"select * from "+dataset+" where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"') limit "+k1
explainSQL2="explain(analyze,buffers) "+"select * from "+smpTab+" where to_tsvector('english',text)@@to_tsquery('english','"+keyword+"') limit "+k0
lmt.cur.execute(explainSQL)
lines=lmt.cur.fetchall()
blocks2=""
blocks1=lines[5]
if smpTab!='null':
lmt.cur.execute(explainSQL2)
lines=lmt.cur.fetchall()
blocks2=lines[5]
print blocks1,blocks2
#find k of the category of biaseduber
def kInUber(category='B02512',tab='BiasedUber',quality=0.85):
coord=GetCoordinateUber(tab,category)
pLen=np.count_nonzero(hashByNumpy(np.array(coord),r=((-75, -72), (39, 43))))
r=1
sLen=0
while(sLen<quality*pLen):
r+=1
k=int(r/100.0*len(coord))
sLen=np.count_nonzero(hashByNumpy(np.array(coord[:k]),r=((-75, -72), (39, 43))))
print r
# tweets id quality test
def idQuality(startID=820000001267011588, interval=1891293030932766,quality=0.85):
sql="select coordinate[0],coordinate[1] from biasedtweets where id>="+str(startID)+" and id<"+str(startID+interval)
cur.execute(sql)
coord=cur.fetchall()
pLen=imageLen(np.array(coord))
q=0.0
r=1
while q<quality:
r+=1
k=int(r/100.0*len(coord))
sLen=imageLen(np.array(coord[:k]))
q=float(sLen)/pLen
print pLen,sLen,r,q
def idQualityRnd(startID=820000001267011588, interval=1891293030932766,quality=0.85):
sql="select coordinate[0],coordinate[1] from biasedtweets where id>="+str(startID)+" and id<"+str(startID+interval)
cur.execute(sql)
coord=cur.fetchall()
pLen=imageLen(np.array(coord))
q=0.0
r=20
while q<quality:
r+=1
sql="select coordinate[0],coordinate[1] from biasedtweets tablesample system("+str(r)+") where id>="+str(startID)+" and id<"+str(startID+interval)
cur.execute(sql)
scoord=cur.fetchall()
sLen=imageLen(np.array(scoord))
q=float(sLen)/pLen
print pLen,sLen,r,q
# test of execution time
def exe():
#dummySQL1="select count(*) from (select * from dummyTab) t"
dummySQL2="select count(*)from (select * from dummyTab where id<1009129304360288256 and id>820000001267011588) t"
for ss in range(0,3):
for i in [3,5,9]:
sql1="(select coordinate from biasedtweets where id>=820000001267011588 and id<821891294297944354 limit "+str(i/100.0*1264038)+") t"
sql2="(select coordinate from biasedtweets tablesample system("+str(i*10)+") where id>=820000001267011588 and id<821891294297944354) t"
sql3="(select coordinate from biasedtweets tablesample system("+str(i*10)+")) t"
#sql="select count(*) from (select * from sBiasedUber tablesample system("+str((i+1)*10)+") where category='B02512') t"
#sql="select count(*) from (select * from sBiasedUber where category='B02512' limit "+str(int((i+1)*0.1*205673)) + " ) t"
#sql="select count(*) from (select * from sBiasedUber tablesample system("+str((i+1)*10)+") ) t"
t=0
for j in range(0,3):
#cur.execute(dummySQL1)
cur.execute(dummySQL2)
if ss==0:
sql=sql1
elif ss==1:
sql=sql2
else:
sql=sql3
t1=time.time()
cur.execute(sql)
t2=time.time()
t=t+t2-t1
print ss,i,t/3.0
#Find k and r of different ranges in Tweets.
def RangeQ(quality=0.85,tab='bigtweets',binSize=1000, ranges=[200,500]):
maxID=1009129304360288256
minID=820000001267011588
step=(maxID-minID)/binSize
startID=minID#860473672128972652
endID=minID
resultFile=open("RangeQ.txt",'w')
resultFile.close()
resultFile=open("RangeQ.txt",'a')
for times in ranges:
startID=minID
while(startID<maxID):
endID=startID+step*times
sql="select coordinate[0],coordinate[1] from "+tab+" where id>="+str(startID)+" and id<"+str(endID)
#print sql
cur.execute(sql)
coord=np.array(cur.fetchall())
if len(coord>0):
pLen=imageLen(coord)
q=0.0
r=10
k=0
while q<quality:
k=int(r/100.0*len(coord))
sLen=imageLen(coord[:k])
q=float(sLen)/pLen
r+=1
print times,startID,endID,len(coord),r,k
resultFile.writelines(str(times)+ " " +str(startID)+ " " +str(endID)+ " " +str(len(coord))+ " " +str(r)+ " " +str(k)+'\n')
resultFile.flush()
startID=endID
#Find #records and ratio in random ranges.
def RangeMerge(tab='biasedtweets'):
maxID=1009129304360288256
minID=862500001267011588
step=(maxID-minID)/1000
for bin in range(0,1):
startID=minID+step*10*12*bin
endID=startID+step*10*12
#sql="select coordinate[0],coordinate[1] from "+tab+" where id>="+str(startID)+" and id<"+str(endID)
sql="select coordinate[0],coordinate[1] from "+tab+" limit 5000000 offset "+str(bin*10000000+20000000)
cur.execute(sql)
coord=np.array(cur.fetchall())
if len(coord>0):
pLen=imageLen(coord)
print 'Group','Ratio','#Record','#Point','#SubsetRecord','#SubsetPoint','Quality'+str(bin)
for r in range(1,11):
k=int(float(r)/10.0*len(coord))
sLen=imageLen(coord[:k])
print bin,r*10,len(coord),pLen,k,sLen,float(sLen)/pLen
# A, B and A&B subset relationship
def IsSubset():
sqlA="select coordinate[0],coordinate[1] from bigtweets where id>820000001267011588 and id<=823000001267011588"
sqlB="select coordinate[0],coordinate[1] from bigtweets where id>823000001267011588 and id<826000001267011588"
sqlAB="select coordinate[0],coordinate[1] from bigtweets where id>820000001267011588 and id<=824000001267011588"
cur.execute(sqlA)
coordA=cur.fetchall()
cur.execute(sqlB)
coordB=cur.fetchall()
cur.execute(sqlAB)
coordAB=cur.fetchall()
print 'A',imageLen(np.array(coordA))
print 'B',imageLen(np.array(coordB))
print 'AB-B',imageLen(np.array(coordAB[:len(coordA)]))
print 'AB-A',imageLen(np.array(coordAB[len(coordA):]))
print 'AB',imageLen(np.array(coordAB))
print 'A+k',imageLen(np.array(coordAB[:len(coordA)+500000]))
print 'k',imageLen(np.array(coordAB[len(coordA):len(coordA)+500000]))
#hashByNumpy(ar, r=((-170, -60), (15, 70)),b=(res_x, res_y)):
def clear_histogram(tab=""):
sql="delete from "+tab
cur.execute(sql)
cur.execute("commit")
def dividing_points(nEV,point_num):
id=minID
intervalSize=(maxID-minID)/nEV
for i in range(0, point_num):
sql="insert into splitting_point values("+str(id)+",0,0,0)"
cur.execute(sql)
cur.execute("commit")
id = id + intervalSize
def create_histogram(nEV,tab, nBucket=10,nInterval=10):
sql="select point from splitting_point order by point asc"
cur.execute(sql)
points=cur.fetchall()
startPoint=points[0]
parent_id=0.0
for endPoint in points:
#retrieve data
sql="select coordinate[0],coordinate[1] from "+tab+" where id between "+str(startPoint[0])+" and "+str(endPoint[0])
cur.execute(sql)
coord=np.array(cur.fetchall())
if len(coord)<1:
continue
#a new parent intval
sql="insert into parent_interval(parent_id,startval,endval) values("+str(parent_id)+","+str(startPoint[0])+","+str(endPoint[0])+")"
cur.execute(sql)
cur.execute("commit")
#records for the new parent_interval
OriginalViz=hashByNumpy(coord,r=map,b=ev)
for x in range(0,ev[0]):
for y in range(0,ev[1]):
if OriginalViz[x][y]!=0:
sql="insert into parent_pixels(parent_id,x,y) values("+str(parent_id)+","+str(x)+","+str(y)+")"
cur.execute(sql)
cur.execute("commit")
#child intervals
for r in range(0,nBucket):
ks=int(r*10/100.0*len(coord))
ke=int((r+1)*10/100.0*len(coord))
tmpVizA=hashByNumpy(coord[0:ke],r=map,b=ev)
LowVizA=hashByNumpy(np.array(np.transpose(np.nonzero(tmpVizA))),r=((0,ev[0]),(0,ev[1])),b=rv)
###reversed value
tmpVizB=hashByNumpy(coord[ks-len(coord):],r=map,b=ev)
LowVizB=hashByNumpy(np.array(np.transpose(np.nonzero(tmpVizB))),r=((0,ev[0]),(0,ev[1])),b=rv)
for x in range(0,rv[0]):
for y in range(0,rv[1]):
if LowVizA[x][y]!=0 or LowVizB[x][y]!=0:
sql="insert into child_interval(parent_id,child_id,x,y,a,b) values("+str(parent_id)+","+str(r)+","+str(x)+","+str(y)+","+str(LowVizA[x][y])+","+str(LowVizB[x][y])+")"
cur.execute(sql)
cur.execute("commit")
startPoint=endPoint
parent_id+=2048.0
print "DONE."
def SnapShot(dt,rdt,nEV,nInterval,nBucket,tab):
step=(maxID-minID)/nInterval
for i in range(0,nEV):
sql="select coordinate[0],coordinate[1] from "+tab+" where id>="+str(startID+i*step)+" and id<"+str(startID+(i+1)*step)
qs=time.time()
cur.execute(sql)
coord=np.array(cur.fetchall())
qe = time.time()
if len(coord)<1:
continue
ps=time.time()
OriginalViz=hashByNumpy(coord,r=map,b=ev)
pe=time.time()
ss=time.time()
for x in range(0,ev[0]):
for y in range(0,ev[1]):
if OriginalViz[x][y]!=0:
sql="insert into "+dt+" values("+str(i)+","+str(x)+","+str(y)+")"
cur.execute(sql)
cur.execute("commit")
se = time.time()
#print "Original viz for partition",i,"Done."
############################################
rt=0
for r in range(0,nBucket):
ks=int(r*10/100.0*len(coord))
ke=int((r+1)*10/100.0*len(coord))
rs=time.time()
tmpVizA=hashByNumpy(coord[0:ke],r=map,b=ev)
LowVizA=hashByNumpy(np.array(np.transpose(np.nonzero(tmpVizA))),r=((0,ev[0]),(0,ev[1])),b=rv)
###reversed value
tmpVizB=hashByNumpy(coord[ks-len(coord):],r=map,b=ev)
LowVizB=hashByNumpy(np.array(np.transpose(np.nonzero(tmpVizB))),r=((0,ev[0]),(0,ev[1])),b=rv)
re = time.time()
rt+=re-rs
for x in range(0,rv[0]):
for y in range(0,rv[1]):
if LowVizA[x][y]!=0 or LowVizB[x][y]!=0:
sql="insert into "+rdt+" values("+str(i)+","+str(r)+","+str(x)+","+str(y)+","+str(LowVizA[x][y])+","+str(LowVizB[x][y])+")"
cur.execute(sql)
cur.execute("commit")
#print "RV for partition",i,"bucket",r, ", Done."
print qe-qs, pe-ps+rt, se-ss
print "DONE."
def List2Matrix(list,matrix):
for i in list:
matrix[i[0]][i[1]]=i[2]
def RewrittenQuery(lev,rev,yl,yr,xl,xr,etab,rtab):#14963
sql="select distinct x,y from "+etab+" where viz>="+str(lev)+" and viz<="+str(rev)
cur.execute(sql)
hist = cur.fetchall()
RV_rl=hashByNumpy(np.array(hist),r=((0,ev[0]),(0,ev[1])),b=rv)
sql="select distinct x,y from "+etab+" where viz>"+str(lev)+" and viz<"+str(rev)
cur.execute(sql)
hist = cur.fetchall()
RV_m = np.zeros(shape=rv)
if len(hist) > 0:
RV_m=hashByNumpy(np.array(hist),r=((0,ev[0]),(0,ev[1])),b=rv)
sql="select x,y,b from "+rtab+" where part="+str(lev)+" and buck="+str(yl)
cur.execute(sql)
hist = cur.fetchall()
RV_yl = np.zeros(shape=rv)
if len(hist) > 0:
List2Matrix(hist,RV_yl)
sql="select x,y,a from "+rtab+" where part="+str(rev)+" and buck="+str(yr)
cur.execute(sql)
hist = cur.fetchall()
RV_yr=np.zeros(shape=rv)
if len(hist) > 0:
List2Matrix(hist,RV_yr)
sql="select x,y,b from "+rtab+" where part="+str(lev)+" and buck="+str(xl)
cur.execute(sql)
hist = cur.fetchall()
RV_xl=np.zeros(shape=rv)
if len(hist) > 0:
List2Matrix(hist,RV_xl)
sql="select x,y,a from "+rtab+" where part="+str(rev)+" and buck="+str(xr)
cur.execute(sql)
hist=cur.fetchall()
RV_xr=np.zeros(shape=rv)
if len(hist) > 0:
List2Matrix(hist,RV_xr)
numerator=0.0
denominator=0.0
for i in range(0,rv[0]):
for j in range(0,rv[1]):
tmp=max(RV_xl[i][j],RV_xr[i][j],RV_m[i][j])
numerator+=tmp
denominator+=min(tmp+RV_yl[i][j]-RV_xl[i][j]+RV_yr[i][j]-RV_xr[i][j],RV_rl[i][j])
return numerator/denominator
def RewrittenQuery2(lb=8,rb=1):#14963
sql="select distinct x,y from EV where viz>0 and viz<5"
cur.execute(sql)
union=np.array(cur.fetchall())
unionRV=hashByNumpy(union,r=((0,480),(0,270)),b=rv)
sql="select x,y,b from RV where part=0 and buck="+str(lb)
cur.execute(sql)
left=cur.fetchall()
for r in left:
if unionRV[r[0]][r[1]]<r[2]:
unionRV[r[0]][r[1]]=r[2]
sql="select x,y,a from RV where part=2 and buck="+str(rb)
cur.execute(sql)
right=cur.fetchall()
for r in right:
if unionRV[r[0]][r[1]]<r[2]:
unionRV[r[0]][r[1]]=r[2]
aprmtVal=np.sum(np.reshape(unionRV,(unionRV.size,)))
print aprmtVal/11174.0
def QualityCompare(b):
#startID=862500001267011588
#endID=startID+1466293030932760
#sql="select coordinate[0],coordinate[1] from bigtweets where id>=862500001267011588 and id<"+str(endID)
#cur.execute(sql)
#coordA=np.array(cur.fetchall())
#startID=endID
#endID=startID+1466293030932760
#sql="select coordinate[0],coordinate[1] from bigtweets where id>="+str(startID)+ " and id<"+str(endID)
#cur.execute(sql)
#coordB=np.array(cur.fetchall())
#coordAB=np.concatenate((coordA,coordB),axis=0)
#pLen=imageLen(coordAB)