-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlurkerRank.py
357 lines (290 loc) · 10.9 KB
/
lurkerRank.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
__author__ = "DIMES, University of Calabria, 2015"
import csv
import argparse
from operator import itemgetter
import numpy as np
import itertools as it
from scipy.sparse import dok_matrix
from scipy.sparse.sparsetools import csr_scale_columns
import os
import os.path as osp
import glob
from os.path import basename
from os.path import isfile
import networkx as nx
# Field separator character in the input graph file. Values on each line of the file are separated by this character
SEPARATOR = " "
# (Over)size of the node set
DIM_MAX = 2000000
# Damping factor in LurkerRank
ALPHA = 0.85
# Maximum number of iterations
MAX_ITERS = 150
# Convergence threshold
CONV_THRESHOLD = 1e-8
"""
Parses an input digraph file, in NCOL format <source target weight>.
The edge meaning is that "target" node is influenced by (e.g., follows, likes) "source" node.
If "weight" is not specified, edge weights are assumed to be 1.
:param file_in: the name of the file which the data are to be read from.
:param need_mapping: a logical value indicating whether nodes are numbered using a non-progressive order.
:param header: a logical value indicating whether the file contains the names of the variables as its first line.
:return: the transpose of the adjacency matrix in CSR format.
"""
def parser_file(file_in, need_mapping, header=False):
mapping = {} # dict for the mapping of node ids
last_id = 0 # largest id of node
with open(file_in) as in_file:
reader = csv.reader(in_file, delimiter=SEPARATOR)
iter_reader = iter(reader)
if header:
# Skip header
next(iter_reader)
dim = DIM_MAX
P = dok_matrix((dim, dim))
dim = 0
for row in iter_reader:
if row:
source, target = map(int, row[:2])
if need_mapping:
if source not in mapping:
mapping[source] = last_id
last_id += 1
if target not in mapping:
mapping[target] = last_id
last_id += 1
source = mapping[source]
target = mapping[target]
dim = max(dim, source, target)
if len(row) > 2: # true if weights are available
weight = float(row[2])
P[target, source] = weight
else:
P[target, source] = 1.
# Conversion in CSR format
dim += 1
P = P.tocsr()[:dim, :dim]
return P, mapping
"""
Parses an input DiGraph object of networkx.
If "weight" is not specified, edge weights are assumed to be 1.
:param G: the name of the DiGraph object.
:param need_mapping: a logical value indicating whether nodes are numbered using a non-progressive order.
:return: the transpose of the adjacency matrix in CSR format.
"""
def graph_to_matrix(G, need_mapping):
mapping = {} # dict for the mapping of node ids
last_id = 0 # largest id of node
dim = DIM_MAX
P = dok_matrix((dim, dim))
dim = 0
for edge in G.edges(data=True):
source,target,w = edge
if need_mapping:
if source not in mapping:
mapping[source] = last_id
last_id += 1
if target not in mapping:
mapping[target] = last_id
last_id += 1
source = mapping[source]
target = mapping[target]
dim = max(dim, source, target)
if len(w.keys())> 0: # true if weights are available
for k in w.keys(): # if the graph is weighted then the list should contain a single attribute (e.g., 'influence' or 'weight')
weight = float(w[k])
P[target, source] = weight
break
else:
P[target, source] = 1.
# Conversion in CSR format
dim += 1
P = P.tocsr()[:dim, :dim]
return P, mapping
"""
Computes the in-degree vector and the out-degree vector.
:param P: the transpose of the adjacency matrix.
:return: I = the in-degree vector, O = the out-degree vector
"""
def compute_vector(P):
I = P.sum(axis=1).A.ravel() + 1
O = P.sum(axis=0).A.ravel() + 1
return I, O
"""
All LurkerRank functions require in input:
P: transpose of the adjacency matrix
I: in-degree vector
O: out-degree vector
Each of the functions terminates after MAX_ITERS iterations or when the error is not greater than CONV_THRESHOLD,
and returns a unit-norm vector storing the LurkerRank solution.
"""
def compute_LRin(P, I, O):
n = len(I)
r = np.ones(n) / n
ratio = O / I
const = (1 - ALPHA) / n
for _ in range(MAX_ITERS):
r_pre = r
s = P.dot(ratio * r_pre) / O
r = ALPHA * s + const
if np.allclose(r, r_pre, atol=CONV_THRESHOLD, rtol=0):
break
return r / r.sum()
def compute_LRin_out(P, I, O):
n = len(I)
r = np.ones(n) / n
ratio = O / I
const = (1 - ALPHA) / n
sum_in = P.T.sign().dot(I)
sum_in[sum_in == 0] = 1
I_norm = (I / sum_in)
for _ in range(MAX_ITERS):
r_pre = r
lr_in = P.dot(r_pre * ratio) / O
lr_out = 1 + I_norm * P.T.dot(r_pre / ratio)
r = ALPHA * lr_in * lr_out + const
r = r / r.sum()
if np.allclose(r, r_pre, atol=CONV_THRESHOLD, rtol=0):
break
return r
def compute_LRout(P, I, O):
n = len(I)
r = np.ones(n) / n
const = (1 - ALPHA) / n
sum_in = P.T.sign().dot(I)
sum_in[sum_in == 0] = 1
ratio = I / O
I_norm = (I / sum_in)
for _ in range(MAX_ITERS):
r_pre = r
r = ALPHA * I_norm * P.T.dot(r_pre * ratio) + const
if np.allclose(r, r_pre, atol=CONV_THRESHOLD, rtol=0):
break
return r / r.sum()
def compute_alpha_LRin(P, I, O):
n = len(I)
r = np.ones(n) / n
ratio = O / I
for _ in range(MAX_ITERS):
r_pre = r
s = P.dot(ratio * r_pre) / O
r = ALPHA * s + 1
if np.allclose(r, r_pre, atol=CONV_THRESHOLD, rtol=0):
break
return r / r.sum()
def compute_alpha_LRout(P, I, O):
n = len(I)
r = np.ones(n) / n
sum_in = P.T.sign().dot(I)
sum_in[sum_in == 0] = 1
ratio = I / O
I_norm = (I / sum_in)
for _ in range(MAX_ITERS):
r_pre = r
r = ALPHA * I_norm * P.T.dot(r_pre * ratio) + 1
if np.allclose(r, r_pre, atol=CONV_THRESHOLD, rtol=0):
break
return r / r.sum()
def compute_alpha_LRin_out(P, I, O):
n = len(I)
r = np.ones(n) / n
ratio = O / I
sum_in = P.T.sign().dot(I)
sum_in[sum_in == 0] = 1
I_norm = (I / sum_in)
for _ in range(MAX_ITERS):
r_pre = r
lr_in = P.dot(r_pre * ratio) / O
lr_out = 1 + I_norm * P.T.dot(r_pre / ratio)
r = ALPHA * lr_in * lr_out + 1
r = r / r.sum()
if np.allclose(r, r_pre, atol=CONV_THRESHOLD, rtol=0):
break
return r
LR_METHODS = {'LRin': compute_LRin,
'LRinout': compute_LRin_out,
'LRout': compute_LRout,
'acLRin': compute_alpha_LRin,
'acLRinout': compute_alpha_LRin_out,
'acLRout': compute_alpha_LRout
}
def print_result(res, mapping, out_file_path):
nodes = np.arange(0, len(res))
nodes = np.lexsort((nodes, -res))
res = res[nodes]
flat_mapp = []
if mapping:
while mapping:
flat_mapp.append(mapping.popitem())
flat_mapp.sort(key=lambda t: t[1])
with open(out_file_path, "w") as out_file:
for user_id, val in zip(nodes, res):
if flat_mapp:
user_id = flat_mapp[user_id][0]
print(user_id, val, file=out_file, sep=";")
def lr_dict(res, mapping):
lr_dict = {}
nodes = np.arange(0, len(res))
nodes = np.lexsort((nodes, -res))
res = res[nodes]
flat_mapp = []
if mapping:
while mapping:
flat_mapp.append(mapping.popitem())
flat_mapp.sort(key=lambda t: t[1])
for user_id, val in zip(nodes, res):
if flat_mapp:
user_id = flat_mapp[user_id][0]
lr_dict[int(user_id)] = float(val)
return lr_dict
"""
Invokes a particular LurkerRank function.
:param func: the name of a LurkerRank function selected from the enumeration LR_METHODS
:param file_in: the name of the file which the data are to be read from.
:param file_out: the name of the file where the results are to be printed out.
:param need_mapping: a logical value indicating whether nodes are numbered using a non-progressive order.
:param return_dict: if True, the function returns a dict <id,score>, otherwise results are printed out to file_out.
:param input_graph: True if file_in corresponds to a DiGraph object of networkx.
"""
def computeLR(func, file_in, file_out, need_mapping=True, return_dict=False, input_graph=False):
if input_graph==True:
P, mapping = graph_to_matrix(file_in, need_mapping)
else:
P, mapping = parser_file(file_in, need_mapping)
# print("Graph matrix has been created.\n")
I, O = compute_vector(P)
# print("Degree vectors have been created.\n")
res = func(P, I, O)
if return_dict==False:
print_result(res, mapping, file_out)
else:
return lr_dict(res,mapping)
"""
:param dir: the path of the input directory.
:param out: the path of the output directory.
:param need_mapping: a logical value indicating whether nodes are numbered using a non-progressive order.
:param method: the name of the LurkerRank function to run.
"""
def compute_on_dir(dir,out,method,need_mapping=True):
graphs = glob.glob(dir+"*.ncol")
for sg_path in graphs:
in_file = sg_path
func = LR_METHODS[method]
filename = basename(sg_path).split('.')[0]
out_file = out+filename+"_"+method+".txt"
if not isfile(out_file):
folder = osp.split(out_file)[0]
try:
os.makedirs(folder)
except OSError:
pass
computeLR(func, in_file, out_file, need_mapping)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
'inputDir', help='path of the folder containing the input graph file(s)')
parser.add_argument(
'outputDir', help='path of the folder containing the output file(s) storing LurkerRank solution(s)')
parser.add_argument('-lr', required=False, choices=['LRin', 'LRout', 'LRinout','acLRin', 'acLRout', 'acLRinout'], default='LRin', help='LurkerRank method (default: LRin)')
args = parser.parse_args()
compute_on_dir(args.inputDir,args.outputDir,args.lr)