forked from patapizza/pylouvain
-
Notifications
You must be signed in to change notification settings - Fork 3
/
pylouvain.py
305 lines (292 loc) · 11 KB
/
pylouvain.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
#!/usr/bin/env python3
'''
Implements the Louvain method.
Input: a weighted undirected graph
Ouput: a (partition, modularity) pair where modularity is maximum
'''
class PyLouvain:
'''
Builds a graph from _path.
_path: a path to a file containing "node_from node_to" edges (one per line)
'''
@classmethod
def from_file(cls, path):
f = open(path, 'r')
lines = f.readlines()
f.close()
nodes = {}
edges = []
for line in lines:
n = line.split()
if not n:
break
nodes[n[0]] = 1
nodes[n[1]] = 1
w = 1
if len(n) == 3:
w = int(n[2])
edges.append(((n[0], n[1]), w))
# rebuild graph with successive identifiers
nodes_, edges_ = in_order(nodes, edges)
print("%d nodes, %d edges" % (len(nodes_), len(edges_)))
return cls(nodes_, edges_)
'''
Builds a graph from _path.
_path: a path to a file following the Graph Modeling Language specification
'''
@classmethod
def from_gml_file(cls, path):
f = open(path, 'r')
lines = f.readlines()
f.close()
nodes = {}
edges = []
current_edge = (-1, -1, 1)
in_edge = 0
for line in lines:
words = line.split()
if not words:
break
if words[0] == 'id':
nodes[int(words[1])] = 1
elif words[0] == 'source':
in_edge = 1
current_edge = (int(words[1]), current_edge[1], current_edge[2])
elif words[0] == 'target' and in_edge:
current_edge = (current_edge[0], int(words[1]), current_edge[2])
elif words[0] == 'value' and in_edge:
current_edge = (current_edge[0], current_edge[1], int(words[1]))
elif words[0] == ']' and in_edge:
edges.append(((current_edge[0], current_edge[1]), 1))
current_edge = (-1, -1, 1)
in_edge = 0
nodes, edges = in_order(nodes, edges)
print("%d nodes, %d edges" % (len(nodes), len(edges)))
return cls(nodes, edges)
'''
Initializes the method.
_nodes: a list of ints
_edges: a list of ((int, int), weight) pairs
'''
def __init__(self, nodes, edges):
self.nodes = nodes
self.edges = edges
# precompute m (sum of the weights of all links in network)
# k_i (sum of the weights of the links incident to node i)
self.m = 0
self.k_i = [0 for n in nodes]
self.edges_of_node = {}
self.w = [0 for n in nodes]
for e in edges:
self.m += e[1]
self.k_i[e[0][0]] += e[1]
self.k_i[e[0][1]] += e[1] # there's no self-loop initially
# save edges by node
if e[0][0] not in self.edges_of_node:
self.edges_of_node[e[0][0]] = [e]
else:
self.edges_of_node[e[0][0]].append(e)
if e[0][1] not in self.edges_of_node:
self.edges_of_node[e[0][1]] = [e]
elif e[0][0] != e[0][1]:
self.edges_of_node[e[0][1]].append(e)
# access community of a node in O(1) time
self.communities = [n for n in nodes]
self.actual_partition = []
'''
Applies the Louvain method.
'''
def apply_method(self):
network = (self.nodes, self.edges)
best_partition = [[node] for node in network[0]]
best_q = -1
i = 1
while 1:
#print("pass #%d" % i)
i += 1
partition = self.first_phase(network)
q = self.compute_modularity(partition)
partition = [c for c in partition if c]
#print("%s (%.8f)" % (partition, q))
# clustering initial nodes with partition
if self.actual_partition:
actual = []
for p in partition:
part = []
for n in p:
part.extend(self.actual_partition[n])
actual.append(part)
self.actual_partition = actual
else:
self.actual_partition = partition
if q == best_q:
break
network = self.second_phase(network, partition)
best_partition = partition
best_q = q
return (self.actual_partition, best_q)
'''
Computes the modularity of the current network.
_partition: a list of lists of nodes
'''
def compute_modularity(self, partition):
q = 0
m2 = self.m * 2
for i in range(len(partition)):
q += self.s_in[i] / m2 - (self.s_tot[i] / m2) ** 2
return q
'''
Computes the modularity gain of having node in community _c.
_node: an int
_c: an int
_k_i_in: the sum of the weights of the links from _node to nodes in _c
'''
def compute_modularity_gain(self, node, c, k_i_in):
return 2 * k_i_in - self.s_tot[c] * self.k_i[node] / self.m
'''
Performs the first phase of the method.
_network: a (nodes, edges) pair
'''
def first_phase(self, network):
# make initial partition
best_partition = self.make_initial_partition(network)
while 1:
improvement = 0
for node in network[0]:
node_community = self.communities[node]
# default best community is its own
best_community = node_community
best_gain = 0
# remove _node from its community
best_partition[node_community].remove(node)
best_shared_links = 0
for e in self.edges_of_node[node]:
if e[0][0] == e[0][1]:
continue
if e[0][0] == node and self.communities[e[0][1]] == node_community or e[0][1] == node and self.communities[e[0][0]] == node_community:
best_shared_links += e[1]
self.s_in[node_community] -= 2 * (best_shared_links + self.w[node])
self.s_tot[node_community] -= self.k_i[node]
self.communities[node] = -1
communities = {} # only consider neighbors of different communities
for neighbor in self.get_neighbors(node):
community = self.communities[neighbor]
if community in communities:
continue
communities[community] = 1
shared_links = 0
for e in self.edges_of_node[node]:
if e[0][0] == e[0][1]:
continue
if e[0][0] == node and self.communities[e[0][1]] == community or e[0][1] == node and self.communities[e[0][0]] == community:
shared_links += e[1]
# compute modularity gain obtained by moving _node to the community of _neighbor
gain = self.compute_modularity_gain(node, community, shared_links)
if gain > best_gain:
best_community = community
best_gain = gain
best_shared_links = shared_links
# insert _node into the community maximizing the modularity gain
best_partition[best_community].append(node)
self.communities[node] = best_community
self.s_in[best_community] += 2 * (best_shared_links + self.w[node])
self.s_tot[best_community] += self.k_i[node]
if node_community != best_community:
improvement = 1
if not improvement:
break
return best_partition
'''
Yields the nodes adjacent to _node.
_node: an int
'''
def get_neighbors(self, node):
for e in self.edges_of_node[node]:
if e[0][0] == e[0][1]: # a node is not neighbor with itself
continue
if e[0][0] == node:
yield e[0][1]
if e[0][1] == node:
yield e[0][0]
'''
Builds the initial partition from _network.
_network: a (nodes, edges) pair
'''
def make_initial_partition(self, network):
partition = [[node] for node in network[0]]
self.s_in = [0 for node in network[0]]
self.s_tot = [self.k_i[node] for node in network[0]]
for e in network[1]:
if e[0][0] == e[0][1]: # only self-loops
self.s_in[e[0][0]] += e[1]
self.s_in[e[0][1]] += e[1]
return partition
'''
Performs the second phase of the method.
_network: a (nodes, edges) pair
_partition: a list of lists of nodes
'''
def second_phase(self, network, partition):
nodes_ = [i for i in range(len(partition))]
# relabelling communities
communities_ = []
d = {}
i = 0
for community in self.communities:
if community in d:
communities_.append(d[community])
else:
d[community] = i
communities_.append(i)
i += 1
self.communities = communities_
# building relabelled edges
edges_ = {}
for e in network[1]:
ci = self.communities[e[0][0]]
cj = self.communities[e[0][1]]
try:
edges_[(ci, cj)] += e[1]
except KeyError:
edges_[(ci, cj)] = e[1]
edges_ = [(k, v) for k, v in edges_.items()]
# recomputing k_i vector and storing edges by node
self.k_i = [0 for n in nodes_]
self.edges_of_node = {}
self.w = [0 for n in nodes_]
for e in edges_:
self.k_i[e[0][0]] += e[1]
self.k_i[e[0][1]] += e[1]
if e[0][0] == e[0][1]:
self.w[e[0][0]] += e[1]
if e[0][0] not in self.edges_of_node:
self.edges_of_node[e[0][0]] = [e]
else:
self.edges_of_node[e[0][0]].append(e)
if e[0][1] not in self.edges_of_node:
self.edges_of_node[e[0][1]] = [e]
elif e[0][0] != e[0][1]:
self.edges_of_node[e[0][1]].append(e)
# resetting communities
self.communities = [n for n in nodes_]
return (nodes_, edges_)
'''
Rebuilds a graph with successive nodes' ids.
_nodes: a dict of int
_edges: a list of ((int, int), weight) pairs
'''
def in_order(nodes, edges):
# rebuild graph with successive identifiers
nodes = list(nodes.keys())
nodes.sort()
i = 0
nodes_ = []
d = {}
for n in nodes:
nodes_.append(i)
d[n] = i
i += 1
edges_ = []
for e in edges:
edges_.append(((d[e[0][0]], d[e[0][1]]), e[1]))
return (nodes_, edges_)