forked from rieck/siggi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
siggi.py
291 lines (214 loc) · 7.53 KB
/
siggi.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
# Siggi - Feature Hashing for Labeled Graphs
# (c) 2015 Konrad Rieck (konrad@mlsec.org)
import networkx as nx
import string
import utils
# Supported modes for bags
modes = {
0: "bag_of_nodes",
1: "bag_of_edges",
2: "bag_of_neighborhoods",
3: "bag_of_reachabilities",
4: "bag_of_shortest_paths",
5: "bag_of_connected_components",
6: "bag_of_attracting_components",
7: "bag_of_branchless_paths",
}
# Global arguments
args = None
def add_arguments(parser):
""" Add command-line arguments to partser """
parser.add_argument('-b', '--bits', metavar='N', default=20, type=int,
help='set bits for feature hashing')
parser.add_argument('-f', '--fmap', default=False, action='store_true',
help='store feature mapping in file')
parser.add_argument('-l', '--minlen', metavar='N', default=1, type=int,
help='set minimum length of shortest paths')
parser.add_argument('-L', '--maxlen', metavar='N', default=3, type=int,
help='set maximum length of shortest paths')
parser.add_argument('-s', '--size', metavar='N', default=1, type=int,
help='set size of neighborhoods')
parser.add_argument('-d', '--depth', metavar='N', default=5, type=int,
help='set depth of reachabilities')
parser.add_argument('-n', '--norm', metavar='S', default='none',
help='set vector norm: l1, l2 or none')
parser.add_argument('-M', '--map', metavar='S', default='count',
help='set map type: binary or count')
parser.add_argument('-p', '--label', metavar='S', default='label',
help='set name of label property')
def set_args(pargs):
""" Set global arguments structure """
global args
args = pargs
def node_label(node):
""" Return the label of a node """
output = []
labels = map(string.strip, args.label.split(","))
for label in labels:
if label in node:
output.append(str(node[label]))
else:
output.append('')
return '|'.join(output)
def bag_name(m):
""" Return the name and config of a bag mode """
s = modes[m].replace("_", " ")
s = s.replace("bag of", "bags of")
if m == 2:
s += " (size: %d)" % args.size
elif m == 3:
s += " (depth: %d)" % args.depth
elif m == 4:
s += " (min: %d, max: %d)" % (args.minlen, args.maxlen)
return s
def bag_of_nodes(graph):
""" Build bag of nodes from graph """
bag = {}
for i in graph.nodes():
label = node_label(graph.node[i])
if label not in bag:
bag[label] = 0
bag[label] += 1
return bag
def bag_of_edges(graph):
""" Build bag of edges from graph """
bag = {}
for i, j in graph.edges():
n1 = node_label(graph.node[i])
n2 = node_label(graph.node[j])
label = "%s-%s" % (n1, n2)
if label not in bag:
bag[label] = 0
bag[label] += 1
return bag
def bag_of_neighborhoods(graph):
""" Build bag of neighborhoods for graph """
paths = nx.all_pairs_shortest_path(graph, cutoff=args.size)
bag = {}
for i in paths:
reachable = filter(lambda x: x != i, paths[i].keys())
n = node_label(graph.node[i])
ns = map(lambda x: node_label(graph.node[x]), reachable)
label = "%s:%s" % (n, '-'.join(sorted(ns)))
if label not in bag:
bag[label] = 0.0
bag[label] += 1.0
return bag
def bag_of_reachabilities(graph):
""" Build bag of reachabilities for graph """
paths = nx.all_pairs_shortest_path(graph, cutoff=args.depth)
bag = {}
for i in paths:
reachable = filter(lambda x: x != i, paths[i].keys())
if len(reachable) == 0:
continue
for j in reachable:
n1 = node_label(graph.node[i])
n2 = node_label(graph.node[j])
label = "%s:%s" % (n1, n2)
if label not in bag:
bag[label] = 0.0
bag[label] += 1.0
return bag
def bag_of_shortest_paths(graph):
""" Build bag of shortest path for graph """
paths = nx.all_pairs_shortest_path(graph, cutoff=args.maxlen)
bag = {}
for i in paths:
for j in paths[i]:
path = map(lambda x: node_label(graph.node[x]), paths[i][j])
if len(path) - 1 < args.minlen:
continue
label = '-'.join(path)
if label not in bag:
bag[label] = 0.0
bag[label] += 1.0
return bag
def bag_of_connected_components(graph):
""" Bag of strongly connected components """
comp = nx.strongly_connected_components(graph)
return __bag_of_components(graph, comp)
def bag_of_attracting_components(graph):
""" Bag of attracting components """
# Hack to deal with broken nx implementation
if len(graph.node) == 0:
return {}
comp = nx.attracting_components(graph)
return __bag_of_components(graph, comp)
def __bag_of_components(graph, comp):
""" Build bag of components for graph """
bag = {}
for nodes in comp:
ns = map(lambda x: node_label(graph.node[x]), nodes)
label = '-'.join(sorted(ns))
if label not in bag:
bag[label] = 0
bag[label] += 1
return bag
def bag_of_elementary_cycles(graph):
""" Bag of elementary cycles """
bag = {}
for cycle in nx.simple_cycles(graph):
ns = map(lambda x: node_label(graph.node[x]), cycle)
# Determine smallest label and rotate cycle
i = min(enumerate(ns), key=lambda x: x[1])[0]
ns.extend(ns[:i])
ns[:i] = []
label = '-'.join(ns)
if label not in bag:
bag[label] = 0
bag[label] += 1
return bag
def bag_of_branchless_paths(graph):
""" Bag of branchless paths """
bag = {}
for i in graph.nodes():
if graph.out_degree(i) > 1:
graph.remove_node(i)
for nodes in nx.weakly_connected_components(graph):
ns = map(lambda x: node_label(graph.node[x]), nodes)
label = '-'.join(reversed(ns))
if label not in bag:
bag[label] = 0
bag[label] += 1
return bag
def bag_to_fvec(bag):
""" Map bag to sparse feature vector """
fvec = {}
hashes = {}
for key in bag:
hash = utils.murmur3(key)
dim = (hash & (1 << args.bits) - 1) + 1
sign = 2 * (hash >> 31) - 1
if dim not in fvec:
fvec[dim] = 0
fvec[dim] += sign * bag[key]
# Store dim-key mapping
if args.fmap:
if dim not in hashes:
hashes[dim] = set()
if key not in hashes[dim]:
hashes[dim].add(key)
return fvec, hashes if args.fmap else None
def fvec_norm(fvec):
""" Normalization of feature vector """
mtype = args.map.lower()
if mtype == "binary":
for k in fvec.keys():
fvec[k] = 1.0
elif mtype != "count":
raise Exception("Unknown map type '%s'" % mtype)
norm = args.norm.lower()
if norm == "l1" or norm == "manhattan":
total = map(lambda x: abs(x), fvec.values())
total = float(sum(total))
for k in fvec.keys():
fvec[k] /= total
elif norm == "l2" or norm == "euclidean":
total = map(lambda x: x * x, fvec.values())
total = float(sum(total)) ** 0.5
for k in fvec.keys():
fvec[k] /= total
elif norm != "none":
raise Exception("Unknown vector norm '%s'" % norm)
return fvec