@@ -171,6 +171,32 @@ def modularity(self):
171
171
172
172
173
173
class LouvainCommunityDetection (object ):
174
+ """ Uses the Louvain Community Detection algorithm to detect
175
+ communities in networks
176
+
177
+ Parameters
178
+ ----------
179
+ graph : netwrokx Graph object
180
+ communities : list of sets, optional
181
+ initial identified communties
182
+ minthr : float, optional
183
+ minimum threshold value for change in modularity
184
+ default(0.0000001)
185
+
186
+ Examples
187
+ --------
188
+ >>> louvain = LouvainCommunityDetection(graph)
189
+ >>> partitions = louvain.run()
190
+ >>> ## best partition
191
+ >>> partitions[-1].modularity()
192
+
193
+ References
194
+ ----------
195
+ .. [1] VD Blondel, JL Guillaume, R Lambiotte, E Lefebvre, "Fast
196
+ unfolding of communities in large networks", Journal of Statistical
197
+ Mechanics: Theory and Experiment vol.10, P10008 2008.
198
+
199
+ """
174
200
175
201
def __init__ (self , graph , communities = None , minthr = 0.0000001 ):
176
202
self .graph = graph
@@ -180,7 +206,7 @@ def __init__(self, graph, communities=None, minthr=0.0000001):
180
206
def run (self ):
181
207
dendogram = self .gen_dendogram ()
182
208
partitions = self .partitions_from_dendogram (dendogram )
183
- return partitions
209
+ return [ WeightedPartition ( self . graph , part ) for part in partitions ]
184
210
185
211
186
212
def gen_dendogram (self ):
@@ -191,13 +217,13 @@ def gen_dendogram(self):
191
217
192
218
#special case, when there is no link
193
219
#the best partition is everyone in its communities
194
- if graph .number_of_edges () == 0 :
195
- return WeightedPartition (self .graph )
220
+ if self . graph .number_of_edges () == 0 :
221
+ return [ WeightedPartition (self .graph )]
196
222
197
223
current_graph = self .graph .copy ()
198
- part = WeightedPartition (self .graph , self .communities )
224
+ part = WeightedPartition (self .graph , self .initial_communities )
199
225
# first pass
200
- mod = modularity (part )
226
+ mod = part . modularity ()
201
227
dendogram = list ()
202
228
new_part = self ._one_level (part , self .minthr )
203
229
new_mod = new_part .modularity ()
@@ -210,16 +236,15 @@ def gen_dendogram(self):
210
236
partition = WeightedPartition (current_graph )
211
237
newpart = self ._one_level (partition , self .minthr )
212
238
new_mod = newpart .modularity ()
213
- if new_mod - mod < minthr :
239
+ if new_mod - mod < self . minthr :
214
240
break
215
241
216
242
dendogram .append (newpart )
217
243
mod = new_mod
218
244
current_graph ,_ = meta_graph (newpart )
219
245
return dendogram
220
246
221
- @staticmethod
222
- def _one_level (part , min_modularity = .0000001 ):
247
+ def _one_level (self , part , min_modularity = .0000001 ):
223
248
"""run one level of patitioning"""
224
249
curr_mod = part .modularity ()
225
250
modified = True
0 commit comments