-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathfastr.py
More file actions
504 lines (403 loc) · 15.6 KB
/
fastr.py
File metadata and controls
504 lines (403 loc) · 15.6 KB
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
'''
This is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this source. If not, see <http://www.gnu.org/licenses/>.
'''
from collections import defaultdict
from collections import OrderedDict
import math
import os
import pickle
import random
import sys
import time
from functools import reduce
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.random_projection import johnson_lindenstrauss_min_dim
from sklearn.random_projection import SparseRandomProjection
import lsh
"""
This file implements FAST-R test suite reduction algorithms.
"""
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# utility function to load test suite
def loadTestSuite(input_file, bbox=False, k=5):
TS = defaultdict()
with open(input_file) as fin:
tcID = 1
for tc in fin:
if bbox:
TS[tcID] = tc[:-1]
else:
TS[tcID] = set(tc[:-1].split())
tcID += 1
shuffled = list(TS.keys())
random.shuffle(shuffled)
newTS = OrderedDict()
for key in shuffled:
newTS[key] = TS[key]
if bbox:
newTS = lsh.kShingles(TS, k)
return newTS
# store signatures on disk for future re-use
def storeSignatures(input_file, sigfile, hashes, bbox=False, k=5):
with open(sigfile, "w") as sigfile:
with open(input_file) as fin:
tcID = 1
for tc in fin:
if bbox:
# shingling
tc_ = tc[:-1]
tc_shingles = set()
for i in range(len(tc_) - k + 1):
tc_shingles.add(hash(tc_[i:i + k]))
sig = lsh.tcMinhashing((tcID, set(tc_shingles)), hashes)
else:
tc_ = tc[:-1].split()
sig = lsh.tcMinhashing((tcID, set(tc_)), hashes)
for hash_ in sig:
sigfile.write(hash_)
sigfile.write(" ")
sigfile.write("\n")
tcID += 1
# load stored signatures
def loadSignatures(input_file):
sig = {}
start = time.perf_counter()
with open(input_file, "r") as fin:
tcID = 1
for tc in fin:
sig[tcID] = [i.strip() for i in tc[:-1].split()]
tcID += 1
return sig, time.perf_counter() - start
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# FAST-PW (pairwise comparison with candidate set)
def fast_pw(input_file, r, b, bbox=False, k=5, memory=False, B=0):
n = r * b # number of hash functions
hashes = [lsh.hashFamily(i) for i in range(n)]
if memory:
test_suite = loadTestSuite(input_file, bbox=bbox, k=k)
# generate minhashes signatures
mh_t = time.perf_counter()
tcs_minhashes = {tc[0]: lsh.tcMinhashing(tc, hashes)
for tc in test_suite.items()}
mh_time = time.perf_counter() - mh_t
ptime_start = time.perf_counter()
else:
# loading input file and generating minhashes signatures
sigfile = input_file.replace(".txt", ".sig")
sigtimefile = "{}_sigtime.txt".format(input_file.split(".")[0])
if not os.path.exists(sigfile):
mh_t = time.perf_counter()
storeSignatures(input_file, sigfile, hashes, bbox, k)
mh_time = time.perf_counter() - mh_t
with open(sigtimefile, "w") as fout:
fout.write(repr(mh_time))
else:
with open(sigtimefile, "r") as fin:
mh_time = eval(fin.read().replace("\n", ""))
ptime_start = time.perf_counter()
tcs_minhashes, load_time = loadSignatures(sigfile)
tcs = set(tcs_minhashes.keys())
# budget B modification
if B == 0:
B = len(tcs)
BASE = 0.5
SIZE = int(len(tcs)*BASE) + 1
bucket = lsh.LSHBucket(tcs_minhashes.items(), b, r, n)
prioritized_tcs = [0]
# First TC
selected_tcs_minhash = lsh.tcMinhashing((0, set()), hashes)
first_tc = random.choice(list(tcs_minhashes.keys()))
for i in range(n):
if tcs_minhashes[first_tc][i] < selected_tcs_minhash[i]:
selected_tcs_minhash[i] = tcs_minhashes[first_tc][i]
prioritized_tcs.append(first_tc)
tcs -= set([first_tc])
del tcs_minhashes[first_tc]
iteration, total = 0, float(len(tcs_minhashes))
while len(tcs_minhashes) > 0:
iteration += 1
if iteration % 100 == 0:
sys.stdout.write(" Progress: {}%\r".format(
round(100*iteration/total, 2)))
sys.stdout.flush()
if len(tcs_minhashes) < SIZE:
bucket = lsh.LSHBucket(tcs_minhashes.items(), b, r, n)
SIZE = int(SIZE*BASE) + 1
sim_cand = lsh.LSHCandidates(bucket, (0, selected_tcs_minhash),
b, r, n)
filtered_sim_cand = sim_cand.difference(prioritized_tcs)
candidates = tcs - filtered_sim_cand
if len(candidates) == 0:
selected_tcs_minhash = lsh.tcMinhashing((0, set()), hashes)
sim_cand = lsh.LSHCandidates(bucket, (0, selected_tcs_minhash),
b, r, n)
filtered_sim_cand = sim_cand.difference(prioritized_tcs)
candidates = tcs - filtered_sim_cand
if len(candidates) == 0:
candidates = tcs_minhashes.keys()
selected_tc, max_dist = random.choice(tuple(candidates)), -1
for candidate in tcs_minhashes:
if candidate in candidates:
dist = lsh.jDistanceEstimate(
selected_tcs_minhash, tcs_minhashes[candidate])
if dist > max_dist:
selected_tc, max_dist = candidate, dist
for i in range(n):
if tcs_minhashes[selected_tc][i] < selected_tcs_minhash[i]:
selected_tcs_minhash[i] = tcs_minhashes[selected_tc][i]
prioritized_tcs.append(selected_tc)
# select budget B
if len(prioritized_tcs) >= B+1:
break
tcs -= set([selected_tc])
del tcs_minhashes[selected_tc]
ptime = time.perf_counter() - ptime_start
max_ts_size = sum((1 for line in open(input_file)))
return mh_time, ptime, prioritized_tcs[1:max_ts_size]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# FAST-f (for any input function f, i.e., size of candidate set)
def fast_(input_file, selsize, r, b, bbox=False, k=5, memory=False, B=0):
n = r * b # number of hash functions
hashes = [lsh.hashFamily(i) for i in range(n)]
if memory:
test_suite = loadTestSuite(input_file, bbox=bbox, k=k)
# generate minhashes signatures
mh_t = time.perf_counter()
tcs_minhashes = {tc[0]: lsh.tcMinhashing(tc, hashes)
for tc in test_suite.items()}
mh_time = time.perf_counter() - mh_t
ptime_start = time.perf_counter()
else:
# loading input file and generating minhashes signatures
sigfile = input_file.replace(".txt", ".sig")
sigtimefile = "{}_sigtime.txt".format(input_file.split(".")[0])
if not os.path.exists(sigfile):
mh_t = time.perf_counter()
storeSignatures(input_file, sigfile, hashes, bbox, k)
mh_time = time.perf_counter() - mh_t
with open(sigtimefile, "w") as fout:
fout.write(repr(mh_time))
else:
with open(sigtimefile, "r") as fin:
mh_time = eval(fin.read().replace("\n", ""))
ptime_start = time.perf_counter()
tcs_minhashes, load_time = loadSignatures(sigfile)
tcs = set(tcs_minhashes.keys())
# budget B modification
if B == 0:
B = len(tcs)
BASE = 0.5
SIZE = int(len(tcs)*BASE) + 1
bucket = lsh.LSHBucket(tcs_minhashes.items(), b, r, n)
prioritized_tcs = [0]
# First TC
selected_tcs_minhash = lsh.tcMinhashing((0, set()), hashes)
first_tc = random.choice(list(tcs_minhashes.keys()))
for i in range(n):
if tcs_minhashes[first_tc][i] < selected_tcs_minhash[i]:
selected_tcs_minhash[i] = tcs_minhashes[first_tc][i]
prioritized_tcs.append(first_tc)
tcs -= set([first_tc])
del tcs_minhashes[first_tc]
iteration, total = 0, float(len(tcs_minhashes))
while len(tcs_minhashes) > 0:
iteration += 1
if iteration % 100 == 0:
sys.stdout.write(" Progress: {}%\r".format(
round(100*iteration/total, 2)))
sys.stdout.flush()
if len(tcs_minhashes) < SIZE:
bucket = lsh.LSHBucket(tcs_minhashes.items(), b, r, n)
SIZE = int(SIZE*BASE) + 1
sim_cand = lsh.LSHCandidates(bucket, (0, selected_tcs_minhash),
b, r, n)
filtered_sim_cand = sim_cand.difference(prioritized_tcs)
candidates = tcs - filtered_sim_cand
if len(candidates) == 0:
selected_tcs_minhash = lsh.tcMinhashing((0, set()), hashes)
sim_cand = lsh.LSHCandidates(bucket, (0, selected_tcs_minhash),
b, r, n)
filtered_sim_cand = sim_cand.difference(prioritized_tcs)
candidates = tcs - filtered_sim_cand
if len(candidates) == 0:
candidates = tcs_minhashes.keys()
to_sel = min(selsize(len(candidates)), len(candidates))
selected_tc_set = random.sample(tuple(candidates), to_sel)
for selected_tc in selected_tc_set:
for i in range(n):
if tcs_minhashes[selected_tc][i] < selected_tcs_minhash[i]:
selected_tcs_minhash[i] = tcs_minhashes[selected_tc][i]
prioritized_tcs.append(selected_tc)
# select budget B
if len(prioritized_tcs) >= B+1:
break
tcs -= set([selected_tc])
del tcs_minhashes[selected_tc]
# select budget B
if len(prioritized_tcs) >= B+1:
break
ptime = time.perf_counter() - ptime_start
max_ts_size = sum((1 for line in open(input_file)))
return mh_time, ptime, prioritized_tcs[1:max_ts_size]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Preparation + utils
# compute euclidean distance
def euclideanDist(v, w):
d = 0
for k in v.keys():
if k not in w.keys():
d += v[k] ** 2
else:
d += (v[k] - w[k]) ** 2
for k in w.keys():
if k not in v.keys():
d += w[k] ** 2
return math.sqrt(d)
# Preparation phase for FAST++ and FAST-CS
def preparation(inputFile, dim=0):
vectorizer = HashingVectorizer() # compute "TF"
testCases = [line.rstrip("\n") for line in open(inputFile)]
testSuite = vectorizer.fit_transform(testCases)
# dimensionality reduction
if dim <= 0:
e = 0.5 # epsilon in jl lemma
dim = johnson_lindenstrauss_min_dim(len(testCases), eps=e)
srp = SparseRandomProjection(n_components=dim)
projectedTestSuite = srp.fit_transform(testSuite)
# map sparse matrix to dict
TS = []
for i in range(len(testCases)):
tc = {}
for j in projectedTestSuite[i].nonzero()[1]:
tc[j] = projectedTestSuite[i, j]
TS.append(tc)
return TS
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# FAST++ Reduction phase
def reductionPlusPlus(TS, B):
reducedTS = []
# distance to closest center
D = defaultdict(lambda:float('Inf'))
# select first center randomly
selectedTC = random.randint(0, len(TS)-1)
reducedTS.append(selectedTC + 1)
D[selectedTC] = 0
while len(reducedTS) < B:
# k-means++ tc reductionCS
norm = 0
for tc in range(len(TS)):
if D[tc] != 0:
dist = euclideanDist(TS[tc], TS[selectedTC])
dist *= dist
if dist < D[tc]:
D[tc] = dist
norm += D[tc]
# safe exit point (if all distances are 0)
# (but not all test cases have been selected)
if norm == 0:
extraTCS = list(set(range(1, len(TS)+1)) - set(reducedTS))
random.shuffle(extraTCS)
reducedTS.extend(extraTCS[:B-len(reducedTS)])
break
c = 0
coinToss = random.random() * norm
for tc, dist in D.items():
if coinToss < c + dist:
reducedTS.append(tc + 1)
D[tc] = 0
break
c += dist
return reducedTS
# FAST++ test suite reduction algorithm
# Returns: preparation time, reduction time, reduced test suite
def fastPlusPlus(inputFile, dim=0, B=0, memory=True):
if memory:
t0 = time.perf_counter()
TS = preparation(inputFile, dim=dim)
t1 = time.perf_counter()
pTime = t1-t0
else:
rpFile = inputFile.replace(".txt", ".rp")
if not os.path.exists(rpFile):
t0 = time.perf_counter()
TS = preparation(inputFile, dim=dim)
t1 = time.perf_counter()
pTime = t1-t0
pickle.dump((pTime, TS), open(rpFile, "wb"))
else:
pTime, TS = pickle.load(open(rpFile, "rb"))
if B <= 0:
B = len(TS)
t2 = time.perf_counter()
reducedTS = reductionPlusPlus(TS, B)
t3 = time.perf_counter()
sTime = t3-t2
return pTime, sTime, reducedTS
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# FAST-CS
# FAST-CS Reduction phase
def reductionCS(TS, B):
reducedTS = []
# compute center of mass
centerOfMass = defaultdict(float)
for tc in TS:
for k, v in tc.items():
centerOfMass[k] += v
# normalize
for k in centerOfMass.keys():
centerOfMass[k] /= len(TS)
# compute distances
D = defaultdict(float)
norm = 0
for tc in range(len(TS)):
dist = euclideanDist(TS[tc], centerOfMass)
D[tc] = dist*dist
norm += D[tc]
# compute probabilities of being sampled
P = []
if norm != 0:
p = 1.0 / (2*len(TS))
for tc in range(len(TS)):
P.append(p + D[tc] / (2*norm))
else:
P = [1.0 / len(TS)] * len(TS)
# numeric error: when sum of P != 1
P[random.randint(0, len(TS)-1)] += 1.0 - sum(P)
# proportional sampling
reducedTS = list(np.random.choice(list(range(1, len(TS)+1)), size=B, p=P, replace=False))
return reducedTS
# FAST-CS test suite reduction algorithm
# Returns: preparation time, reduction time, reduced test suite
def fastCS(inputFile, dim=0, B=0, memory=True):
if memory:
t0 = time.perf_counter()
TS = preparation(inputFile, dim=dim)
t1 = time.perf_counter()
pTime = t1-t0
else:
rpFile = inputFile.replace(".txt", ".rp")
if not os.path.exists(rpFile):
t0 = time.perf_counter()
TS = preparation(inputFile, dim=dim)
t1 = time.perf_counter()
pTime = t1-t0
pickle.dump((pTime, TS), open(rpFile, "wb"))
else:
pTime, TS = pickle.load(open(rpFile, "rb"))
if B <= 0:
B = len(TS)
t2 = time.perf_counter()
reducedTS = reductionCS(TS, B)
t3 = time.perf_counter()
sTime = t3-t2
return pTime, sTime, reducedTS