-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.py
428 lines (318 loc) · 15.1 KB
/
graph.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
import argparse
import snap
import networkx as nx
import random
import matplotlib.pyplot as plt
import time
import copy
from collections import Counter
import math
#Crea i pesi degli archi
def labeling(graph, t):
min_probability = 0 # Valore minimo di probabilità
max_probability = 1 # Valore massimo di probabilità
random.seed(time.time())
#Aggiungo anche il t sui nodi
for node in graph.Nodes():
graph.AddIntAttrDatN(node, t, "t")
graph.AddIntAttrDatN(node, t, "t")
for edge in graph.Edges():
u = edge.GetSrcNId()
v = edge.GetDstNId()
if u == v:
graph.DelEdge(u, v)
break
max_degree = max(graph.GetNI(u).GetDeg(), graph.GetNI(v).GetDeg())
probability = 1 / (max_degree + 1)
normalized_probability = (probability - min_probability) / (max_probability - min_probability)
random_value = random.uniform(0,1)
if random_value <= normalized_probability:
graph.AddIntAttrDatE(edge, -1, 'weight')
else:
graph.AddIntAttrDatE(edge, 1, 'weight') # Arco positivo
#Recupera i nodi adiacenti (sia in che out)
def get_neighbors(graph, id_node):
neighbors = set()
node = graph.GetNI(id_node)
for i in range(node.GetDeg()):
neighbor = node.GetNbrNId(i)
neighbors.add(neighbor)
return neighbors
#Setta i gradi sia positivi che negativi dei nodi
def set_degree_node(graph):
#Inizialmente i gradi per tutti i nodi vengono messi a 0 altrimenti non è possibile leggere l'attributo
for node in graph.Nodes():
graph.AddIntAttrDatN(node, 0, "degree_pos")
graph.AddIntAttrDatN(node, 0, "degree_neg")
graph.AddIntAttrDatN(node, 0, 'degree_tot')
for edge in graph.Edges():
src_id = edge.GetSrcNId()
dst_id = edge.GetDstNId()
src_node = graph.GetNI(src_id)
dst_node = graph.GetNI(dst_id)
#Setto il grado generale dei nodi
graph.AddIntAttrDatN(src_node, graph.GetIntAttrDatN(src_node, 'degree_tot') + 1, 'degree_tot')
graph.AddIntAttrDatN(dst_node, graph.GetIntAttrDatN(src_node, 'degree_tot') + 1, 'degree_tot')
#Sia della sorgente che della destinazione, perché siamo su un grafo orientato
if(graph.GetIntAttrDatE(edge, "weight") == 1):
graph.AddIntAttrDatN(src_node, graph.GetIntAttrDatN(src_node, 'degree_pos') + 1, 'degree_pos')
graph.AddIntAttrDatN(dst_node, graph.GetIntAttrDatN(dst_node, 'degree_pos') + 1, 'degree_pos')
else:
graph.AddIntAttrDatN(src_node, graph.GetIntAttrDatN(src_node, 'degree_neg') + 1, 'degree_neg')
graph.AddIntAttrDatN(dst_node, graph.GetIntAttrDatN(dst_node, 'degree_neg') + 1, 'degree_neg')
#Recupera i vicini positivi o negativi di un nodo
def get_neighbors_weighed(graph, node_id, weight):
neighbors = get_neighbors(graph, node_id)
new_neighbors = set()
for neighbor_id in neighbors:
edge = None
#Recupero l'arco corretto (perché è un grafo non direzionato, ma si comporta come direzionato)
if graph.GetNI(neighbor_id).IsOutNId(node_id):
edge = graph.GetEI(neighbor_id, node_id) #Arco tra max_node_id -> neighbor_id
else:
edge = graph.GetEI(node_id, neighbor_id) #Arco tra neighbor_id -> max_node_id
weight_edge = graph.GetIntAttrDatE(edge, "weight")
if weight_edge == weight:
new_neighbors.add(neighbor_id)
return new_neighbors
def third_algorithm(graph, k):
counter = Counter()
seed_set = set()
while len(seed_set) < k:
#Metto nel counter gli elementi che rispettano la condizione degree_pos >= degree_neg
#Lo ricalcolo ogni volta perché il grado può essere decrementato
for node in graph.Nodes():
node_id = node.GetId()
degree_pos = graph.GetIntAttrDatN(node_id, 'degree_pos')
degree_neg = graph.GetIntAttrDatN(node_id, 'degree_neg')
t = graph.GetIntAttrDatN(node_id, 't')
if degree_pos >= degree_neg:
counter[node_id] = degree_pos - degree_neg / t
max_node_id = max(counter, key=counter.get) # Ottieni la chiave con il valore massimo
counter.clear() # Svuoto il Counter
seed_set.add(max_node_id) #Aggiungo al seed_set
#Prendo la lista dei nodi adiacenti al nodo aggiungo al seed_set
neighbors = get_neighbors(graph, max_node_id)
for neighbor_id in neighbors:
edge = None
#Recupero l'arco corretto (perché è un grafo non direzionato, ma si comporta come direzionato)
if graph.GetNI(neighbor_id).IsOutNId(max_node_id):
edge = graph.GetEI(neighbor_id, max_node_id) #Arco tra max_node_id -> neighbor_id
else:
edge = graph.GetEI(max_node_id, neighbor_id) #Arco tra neighbor_id -> max_node_id
weight = graph.GetIntAttrDatE(edge, "weight")
if weight == 1: #Decremente il grado positivo sia di max_node_id che di neighbor_id
graph.AddIntAttrDatN(max_node_id, graph.GetIntAttrDatN(max_node_id, 'degree_pos') - 1, 'degree_pos')
graph.AddIntAttrDatN(neighbor_id, graph.GetIntAttrDatN(neighbor_id, 'degree_pos') - 1, 'degree_pos')
else: #Decremente il grado negativo sia di max_node_id che di neighbor_id
graph.AddIntAttrDatN(max_node_id, graph.GetIntAttrDatN(max_node_id, 'degree_neg') - 1, 'degree_neg')
graph.AddIntAttrDatN(neighbor_id, graph.GetIntAttrDatN(neighbor_id, 'degree_neg') - 1, 'degree_neg')
return seed_set
def sup_TSS(graph, dict_neighbor, node_id, flag_t = True):
neighbors = get_neighbors(graph, node_id) #Recupero i vicini di node_t_with_zero
#Per ogni vicino decremento la t e il grado
for neighbor in neighbors:
if flag_t:
graph.AddIntAttrDatN(
neighbor,
graph.GetIntAttrDatN(neighbor, 't') - 1,
't')
graph.AddIntAttrDatN(
neighbor,
graph.GetIntAttrDatN(node_id, 'degree_tot') - 1,
'degree_tot')
#Elimino v dai vicini di u
new_neighbors = set(dict_neighbor[neighbor])
new_neighbors.discard(node_id)
dict_neighbor[neighbor] = new_neighbors
def TSS(graph, k):
seed_set = set()
dict_neighbor = {}
counter = Counter()
v = None
for node in graph.Nodes():
neighbors = get_neighbors(graph, node.GetId())
dict_neighbor[node.GetId()] = copy.deepcopy(neighbors)
while len(seed_set) < k:
node_t_with_zero = None
node_t_degree_min_t = None
#Trovo nodo con t == 0
for node in graph.Nodes():
node_id = node.GetId()
if graph.GetIntAttrDatN(node_id, 't') == 0:
node_t_with_zero = node_id
break
#Trovo nodo con d < t
for node in graph.Nodes():
node_id = node.GetId()
if graph.GetIntAttrDatN(node_id, 'degree_tot') < graph.GetIntAttrDatN(node_id, 't'):
node_t_degree_min_t = node_id
break
#Se esiste un nodo con t = 0
if node_t_with_zero is not None:
sup_TSS(graph, dict_neighbor, node_t_with_zero)
v = node_t_with_zero
else:
if node_t_degree_min_t is not None:
seed_set.add(node_t_degree_min_t)
sup_TSS(graph, dict_neighbor, node_t_degree_min_t)
v = node_t_degree_min_t
else:
for node in graph.Nodes():
node_id = node.GetId()
degree = graph.GetIntAttrDatN(node_id, 'degree_tot')
t = graph.GetIntAttrDatN(node_id, 't')
counter[node_id] = t / degree * (degree + 1)
max_node_id = max(counter, key=counter.get) # Ottieni la chiave con il valore massimo
counter.clear() # Svuoto il Counter
v = max_node_id
sup_TSS(graph, dict_neighbor, max_node_id, False)
graph.DelNode(v)
del dict_neighbor[v]
return seed_set
def cascade(graph, seed_set):
prev_influenced = set()
influencing = copy.deepcopy(seed_set)
while len(influencing) != len(prev_influenced):
prev_influenced = copy.deepcopy(influencing)
for node in graph.Nodes():
node_id = node.GetId()
#Condizione di guarda per prendere nodi non influenzati
if node_id in prev_influenced:
continue
neighbors_pos = get_neighbors_weighed(graph, node_id, 1)
neighbors_neg = get_neighbors_weighed(graph, node_id, -1)
intersection_set_pos = neighbors_pos.intersection(prev_influenced) #Calcolo l'intersezione di neighbors_pos con prev_influenzed
intersection_set_neg = neighbors_neg.intersection(prev_influenced) #Calcolo l'intersezione di neighbors_neg con prev_influenzed
t = graph.GetIntAttrDatN(node_id, 't')
if len(intersection_set_pos) - len(intersection_set_neg) >= t:
influencing.add(node_id)
return influencing
def create_community(graph):
G = snap.ConvertGraph(snap.PUNGraph, graph)
# Esegui l'algoritmo di community detection
CmtyV = snap.TCnComV()
modularity = snap.CommunityCNM(G,CmtyV)
print("#Communities:", len(CmtyV))
return CmtyV, modularity
def communities_seed_minimization(graph, k):
seed_set = set()
CmtyV, _ = create_community(graph)
# Stampa le informazioni sulle community
#print("Numero di community individuate:", len(CmtyV))
# Creo la lista di community
Cmty_list = []
for i, Cmty in enumerate(CmtyV):
#print("Community", i + 1, ":", )
Cmty_list.append((i,Cmty,len(Cmty)))
#for NI in Cmty:
# print(NI, end=" ")
#print()
#Ordino le community dalla più grande alla più piccola
ordered_Cmty = sorted(Cmty_list, key=lambda x: x[2], reverse=True)
'''
print("Final") #Just printing the final Cmty list
for tupl_Cmty in final_cmty:
print("Community", tupl_Cmty[0], ":", )
for NI in tupl_Cmty[1]:
print(NI, end=" ")
print()
'''
final_cmty = []
for Cmt in ordered_Cmty:
NIdV = snap.TIntV()
for NI in Cmt[1]:
NIdV.Add(NI)
SubGraph = snap.GetSubGraph(graph, NIdV)
# Calcola la centralità di intermediazione per la community corrente
CentrH, _ = snap.GetBetweennessCentr(SubGraph)
final_cmty.append((Cmt[0],Cmt[1], SubGraph, CentrH)) #0: ID_Comm, 1: Nodi Comm, 2: Grafo Comm, 3: Centralità Nodi Comm
print("FINE SUBGRAFO")
while(len(seed_set) < k):
for tupl_Cmty in final_cmty:
if len(seed_set) == k:
break
new_node = None
SubGraph = tupl_Cmty[2]
CentrH = tupl_Cmty[3]
while(new_node is None):
if len(CentrH) == 0:
new_node = -1
break
#max_centr_node = max(CentrH, key=CentrH.get)
max_centr_node = max(CentrH, key=lambda k: CentrH[k] if k not in seed_set else float('-inf'))
deg_neg = graph.GetIntAttrDatN(max_centr_node, 'degree_neg')
deg_pos = graph.GetIntAttrDatN(max_centr_node, 'degree_pos')
#print(f"max_centr_node: {max_centr_node}, pos: {deg_pos}, neg: {deg_neg}")
if (deg_pos - deg_neg) >= graph.GetIntAttrDatN(max_centr_node, 't'):
new_node = max_centr_node
else:
del CentrH[max_centr_node]
if new_node == -1:
continue
else:
seed_set.add(new_node)
print(f"Community: {tupl_Cmty[0]}, nodo trovato {new_node}")
return seed_set
def printGr(filename):
G = nx.Graph()
with open(filename, 'r') as file:
for line in file:
source, target = line.strip().split()
G.add_edge(source, target)
# Creazione del grafico
pos = nx.spring_layout(G) # Layout del grafico
nx.draw(G, pos, with_labels=False, node_color='blue', node_size=30)
plt.show()
def save_results_to_file(results, file_path):
with open(file_path, "a") as file:
file.write(str(results) + "\n") # k t influenced
if __name__ == '__main__':
filename = "datasets/facebook_combined.txt"
#printGr(filename)
parser = argparse.ArgumentParser()
parser.add_argument('-k', dest='k', action='store',
default='', type=int, help='k size of seed-set')
parser.add_argument('-t', dest='t', action='store',
default='', type=int, help='treshold of nodes')
parser.add_argument('-a', dest='a', action='store',
default='', type=str, help='name of the algorithm')
args = parser.parse_args()
# Load the Graph from Edge List file
graph = snap.LoadEdgeList(snap.TNEANet,filename , 0, 1)
#Labeling
labeling(graph, args.t)
#Setto i gradi positivi e negativi su ogni nodo
set_degree_node(graph)
#Salvo il grafo solo con label e attributi, in modo da passare al cascade un grafo senza manipolazioni
file_path = "graph.bin"
FOut = snap.TFOut(file_path)
graph.Save(FOut)
FOut.Flush()
FIn = snap.TFIn(file_path)
loaded_graph = snap.TNEANet.Load(FIn)
#seed_set = third_algorithm(graph, args.k)
#seed_set = TSS(graph, args.k)
#print(seed_set)
#print(f"Lunghezza seed_set: {len(seed_set)}")
if args.a == "tss":
seed_set = TSS(graph, args.k)
#print(seed_set)
influenced = cascade(loaded_graph, seed_set)
print(f"Lunghezza influenced: {len(influenced) - len(seed_set)}")
results = f"{args.k} {args.t} {len(influenced) - len(seed_set)}"
save_results_to_file(results, f"tss/TSS_{args.k}_{args.t}.txt")
elif args.a == "third":
seed_set = third_algorithm(graph, args.k)
#print(seed_set)
influenced = cascade(loaded_graph, seed_set)
print(f"Lunghezza influenced: {len(influenced) - len(seed_set)}")
results = f"{args.k} {args.t} {len(influenced) - len(seed_set)}"
save_results_to_file(results, f"third/Third_{args.k}_{args.t}.txt")
elif args.a == "csm":
seed_set = communities_seed_minimization(graph, args.k)
#print(seed_set)
influenced = cascade(loaded_graph, seed_set)
print(f"Lunghezza influenced: {len(influenced) - len(seed_set)}")
results = f"{args.k} {args.t} {len(influenced) - len(seed_set)}"
save_results_to_file(results, f"csm/CSM_{args.k}_{args.t}.txt")