-
Notifications
You must be signed in to change notification settings - Fork 0
/
clusters.rb
387 lines (318 loc) · 9.02 KB
/
clusters.rb
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
# coding: utf-8
require 'csv'
# todo: document
module Clusters
VERSION = '0.0.1'
EPS = 1.7
MIN_POINTS = 2
# Precondition checking
class Preconditions
def self.check_argument(exp, msg = nil, *fmt)
unless exp
raise_exception(ArgumentError, msg, *fmt)
end
exp
end
def self.raise_exception(e, msg, *fmt)
message = ''
message = sprintf(msg, *fmt) unless fmt.empty?
message = msg unless msg.nil?
raise e, message
end
end
# TODO
class Operations
def self.inner_product(vector_a, vector_b)
product = 0.0
vector_a.zip(vector_b) do |x, y|
product += x * y
end
product
end
def self.plus(a, b)
n = a.size - 1
v = []
(0..n).each { |i|
v[i] = a[i] + b[i]
}
v
end
def self.sum(vector)
vector.inject(0.0) { |result, element| result + element }
end
def self.sum_square(vector)
vector.inject(0.0) { |result, element| result + element**2 }
end
def self.sqrt_sum_square(vector)
Math.sqrt(sum_square(vector))
end
def self.sum_diff_square(vector_a, vector_b)
sum = 0.0
vector_a.zip(vector_b) do |x, y|
sum += (x - y)**2
end
sum
end
end
# TODO
class Distances
def check_preconditions(a, b)
are_arrays = (is_array?(a) && is_array?(b))
same_dimension = have_same_dimension?(a, b)
non_null_vectors = !(is_null_vector(a) || is_null_vector(b))
Preconditions.check_argument(are_arrays, 'You have entered non array vectors')
Preconditions.check_argument(same_dimension, 'You have entered two vectors with diff dimensions')
Preconditions.check_argument(non_null_vectors, 'You have entered a null vector')
end
def euclid_distance(vector_a, vector_b)
Math::sqrt(Operations.sum_diff_square(vector_a, vector_b))
end
def euclid_similarity(vector_a, vector_b)
1.0 / (1.0 + euclid_distance(vector_a, vector_b))
end
def is_array?(vector)
vector.instance_of?(Array)
end
def have_same_dimension?(vector_a, vector_b)
vector_a.size == vector_b.size
end
def is_null_vector(vector)
vector.empty?
end
def calculate(vector_a, vector_b)
check_preconditions(vector_a, vector_b)
euclid_distance(vector_a, vector_b)
end
end
# Single Link Clustering
class SingleLink
INFINITY = +1.0/0.0
# m: measurer
# k: k clusters
# data: an array of feature vectors
def cluster(s, k, data)
distance = EPS
while true
# loop with increasing distance until
# cluster size is correct
distance *= 1.1 # TODO: this may need tuning/parameterization
clusters = []
all_vectors = data
until all_vectors.empty?
# build clusters at this distance
p = all_vectors[0]
others = all_vectors[1..data.length - 1]
close = []
far = []
others.to_a.each do |i|
#puts s.calculate(p, i)
if p != i && s.calculate(p, i) < distance
close << i unless i.nil?
else
far << i unless i.nil?
end
end
close << p
clusters << close
all_vectors = far
end
if clusters.size <= k
return clusters
end
end
end
end
# TODO
class DensityBasedScan
# todo: document
def initialize(eps, min_pts)
@distance = Distances.new
@eps = eps
@min_pts = min_pts
end
def cluster(data)
clusters = []
visited = Hash.new
eps = @eps
min_pts = @min_pts
data.each do |vector|
if visited[vector] != :visited
visited[vector] = :visited
neighbors = find_neighbors(data, vector, eps)
if neighbors.size < min_pts
visited[vector] = :noise
else
cluster = [vector]
clusters.push(cluster)
neighbors.each do |neighbor|
# not contained in the cluster
unless clusters.map { |val| val.include?(neighbor) }.include?(true)
expand(data, visited, neighbor, cluster, clusters, eps, min_pts)
end
end
end
end
end
clusters
end
def expand(data, visited, vector, cluster, clusters, eps, min_pts)
cluster.push(vector)
if visited[vector] != :visited
visited[vector] = :visited
neighbors = find_neighbors(data, vector, eps)
if neighbors.size >= min_pts
neighbors.each do |neighbor|
unless clusters.map {|val| val.include?(neighbor)}.include?(true)
expand(data, visited, neighbor, cluster, clusters, eps, min_pts)
end
end
end
end
end
def find_neighbors(data, a, eps)
hood = []
data.each do |b|
if alike?(a, b, eps) # dbscan is < eps
hood.push(b)
end
end
hood
end
# alike, but no the same
def alike?(a, b, eps)
distance = @distance.calculate(a, b)
a != b && distance < eps
end
end
# TODO
class Plot
# TODO
# 1. plot frequency distribution of loops in bind
# 2. plot clusters
# 3. build a table (taxonomy)
# 4. create a document for presentation
end
def self.of(data, eps = EPS, min_pts = MIN_POINTS)
cluster_maker = DensityBasedScan.new(eps, min_pts)
cluster_maker.cluster(data)
end
def self.generate_features(path)
output = []
CSV.foreach(path, :headers => true) do |row|
features = []
# loop field
loop = row['loop']
features << loop.scan(/update/m).size # state update
features << [loop.scan(/while/m).size - 1, 0].max # inner while
features << [loop.scan(/for/m).size - 1, 0].max # inner for
features << [loop.scan(/do/m).size - 1, 0].max # inner do-while
features << loop.scan(/if\s*(.*?)/m).size +
loop.scan(/switch\s*(.*?)/m).size # conditionals
# structs field
features << row['structs'].split(' ').reject {|s| s == 'none' }.size
# types field
features << row['types'].split(' ').reject {|s| s == 'none' }.size
# number of terms in loop invariant (include those cases where you
features << row['loopinv'].split( /\s+|\b/ )
.reject {|each|
each.match(/([\[\]\{\\}\*\?\\])/) # remove [] and () and {}
}.size
output << features
end
output
end
def self.prune(data)
output = []
data.each do |e|
unless e == []
ref = output.include?(e)
if ref
#nothing
else
output << e
end
end
end
end
def self.find_distinct(field, path)
output = []
CSV.foreach(path, :headers => true) do |row|
structs = row[field].split(' ')
structs.each do |e|
unless e == 'none'
ref = output.include?(e)
if ref
#nothing
else
output << e
end
end
end
end
output.size
end
def self.echo(data)
puts 'All feature vectors'
puts '-----------------------------'
index = 0
data.each do |feature_vector|
print "#{index += 1}. " + feature_vector.to_s
print "\n"
end
print "\n"
end
def self.dbscan(path)
# F = [ #updates, #inner_whiles,
# #inner_fors, #inner_dowhiles,
# #conditionals, #structs,
# #user_types, #terms_in_loop_invariant
# ]
data = generate_features(path)
echo(data)
clusters = of(prune(data))
overview(data, clusters, 'Using Density based Scan Clustering')
end
def self.single_link(path, k)
data = generate_features(path)
single_link = SingleLink.new
s = Distances.new
clusters = single_link.cluster(s, k, prune(data))
overview(data, clusters, 'Single Link Clustering')
end
def self.min_distance(clusters)
d = Distances.new
max = 0.0
clusters.each do |cluster|
clusters.each do |cluster_prime|
val = d.calculate(cluster, cluster_prime)
if val > max
max = val
end
end
end
max
end
def self.overview(data, clusters, msg)
indexes = {}
data.each_with_index { |key, index| indexes[key] = index }
puts "All clusters (using #{msg})"
puts "Dimensionality: #{clusters.size}"
puts '-----------------------------'
clusters.each_index do |dim|
puts
puts "Cluster #{dim + 1} of size #{clusters[dim].size} "
puts "Cluster's distance between its elements is #{min_distance(clusters[dim])} "
clusters[dim].each do |cluster|
print cluster
print '@('
print indexes[cluster]
print ')'
print "\n"
end
end
print "\n"
end
end
# Build clusters from collected data in csv file
Clusters.dbscan('structs_and_types.csv')
Clusters.single_link('structs_and_types.csv', 4)