-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLouvain.cs
363 lines (322 loc) · 12.2 KB
/
Louvain.cs
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
using MNCD.Core;
using MNCD.Evaluation.SingleLayer;
using MNCD.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MNCD.CommunityDetection.SingleLayer
{
/// <summary>
/// Compute communities in network based on louvain algorithm.
///
/// Fast unfolding of communities in large networks
/// https://arxiv.org/abs/0803.0476
/// Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte, Etienne Lefebvre.
/// </summary>
public class Louvain
{
/// <summary>
/// Computes communities based on louvain algorithm.
/// </summary>
/// <param name="inputNetwork">Network in which to compute communities.</param>
/// <returns>List of communities.</returns>
public List<Community> Apply(Network inputNetwork)
{
if (inputNetwork.LayerCount > 1)
{
throw new ArgumentException("Louvain works only on single layered networks.");
}
var hierarchy = GetHierarchy(inputNetwork);
if (hierarchy.Count == 0)
{
return inputNetwork.Actors
.Select(a => new Community(a))
.ToList();
}
var ordered = hierarchy.OrderByDescending(h => h.modularity);
return ordered.First().communities;
}
/// <summary>
/// Computes communities hierarchy.
/// </summary>
/// <param name="inputNetwork">Input network.</param>
/// <returns>Hierarchy of communities and it's modularities.</returns>
public List<(double modularity, List<Community> communities)> GetHierarchy(Network inputNetwork)
{
if (inputNetwork.LayerCount > 1)
{
throw new ArgumentException("Louvain works only on single layered networks.");
}
var network = inputNetwork;
List<Community> communities;
Dictionary<Actor, Community> actorToCommunity;
Dictionary<Actor, List<Actor>> actorToActors = null;
var hierarchy = new List<(double modularity, List<Community> communities)>();
while (true)
{
(communities, actorToCommunity) = PhaseOne(network);
var com = communities;
if (actorToActors != null)
{
var original = new List<Community>();
foreach (var c in communities)
{
var actors = c.Actors.SelectMany(a => actorToActors[a]);
original.Add(new Community(actors));
}
com = original;
}
com = com.Where(c => c.Size > 0).ToList();
hierarchy.Add((Modularity.Compute(inputNetwork, com), com));
(network, actorToActors) = PhaseTwo(network, communities, actorToCommunity);
var edges = network.FirstLayer.Edges;
if (network.ActorCount == 1 ||
edges.Count == 0 ||
(edges.Count == 1 && edges.Any(e => e.From == e.To)))
{
break;
}
}
return hierarchy;
}
/// <summary>
/// Phase one of louvain.
/// </summary>
/// <param name="network">Network.</param>
/// <returns>list of communities and mapping of actor to community.</returns>
internal (List<Community>, Dictionary<Actor, Community>) PhaseOne(Network network)
{
var actorToCommunity = network.Actors
.ToDictionary(a => a, a => new Community(a));
var communities = actorToCommunity.Values.ToList();
var actorToNeighbours = network.FirstLayer.GetNeighboursDict();
// First Phase - Local Optimum
var change = true;
var iterations = 0;
while (change && iterations < 1000)
{
iterations++;
change = false;
foreach (var actor in network.Actors)
{
if (!actorToNeighbours.ContainsKey(actor))
{
continue;
}
var ac = actorToCommunity[actor];
var mc = Modularity.Compute(network, communities);
var maxModularity = mc;
var com = ac;
foreach (var neighbour in actorToNeighbours[actor])
{
var nc = actorToCommunity[neighbour];
if (ac == nc)
{
continue;
}
ac.Actors.Remove(actor);
nc.Actors.Add(actor);
var comms = communities.Where(c => c.Size > 0).ToList();
var nm = Modularity.Compute(network, comms);
if (nm > maxModularity)
{
maxModularity = nm;
com = nc;
}
ac.Actors.Add(actor);
nc.Actors.Remove(actor);
}
if (maxModularity > mc)
{
change = true;
ac.Actors.Remove(actor);
com.Actors.Add(actor);
actorToCommunity[actor] = com;
}
}
}
return (communities, actorToCommunity);
}
/// <summary>
/// Phase two of louvain algorithm.
/// </summary>
/// <param name="network">Network.</param>
/// <param name="communities">List of communities.</param>
/// <param name="actorToCommunity">Mapping of actor to community.</param>
/// <returns>Created network and mapping of actor to actors.</returns>
internal (Network, Dictionary<Actor, List<Actor>>) PhaseTwo(
Network network,
List<Community> communities,
Dictionary<Actor, Community> actorToCommunity)
{
var i = 0;
var newCommunityToActor = communities
.Where(c => c.Size > 0)
.ToDictionary(c => c, c =>
{
var id = i++;
return new Actor(id, "a");
});
var newEdges = new Dictionary<(Actor f, Actor t), double>();
foreach (var edge in network.FirstLayer.Edges)
{
var fc = actorToCommunity[edge.From];
var tc = actorToCommunity[edge.To];
var w = edge.Weight;
var fa = newCommunityToActor[fc];
var ta = newCommunityToActor[tc];
if (!newEdges.ContainsKey((fa, ta)))
{
if (!newEdges.ContainsKey((ta, fa)))
{
newEdges.Add((fa, ta), w);
}
else
{
newEdges[(ta, fa)] += w;
}
}
else
{
newEdges[(fa, ta)] += w;
}
}
var newActors = newCommunityToActor.Values.ToList();
var actorToActors = newActors.ToDictionary(
a => a,
a => newCommunityToActor.First(c => c.Value == a).Key.Actors);
var newNetwork = new Network(new Layer(), newActors);
foreach (var newEdge in newEdges)
{
var edge = new Edge
{
From = newEdge.Key.f,
To = newEdge.Key.t,
Weight = newEdge.Value,
};
newNetwork.FirstLayer.Edges.Add(edge);
}
return (newNetwork, actorToActors);
}
/// <summary>
/// Computes modularity gain of moving actor i into community c.
/// </summary>
/// <param name="n">Network.</param>
/// <param name="c">Community.</param>
/// <param name="i">Actor to be moved.</param>
/// <returns>Modularity gain of moving actor in into community c.</returns>
internal double ModularityGain(Network n, Community c, Actor i)
{
var sumIn = GetSumIn(n, c);
var sumTot = GetSumTot(n, c);
var kIn = GetKIn(n, i, c);
var kI = GetKI(n, i);
var m = GetM(n);
return
(((sumIn + kIn) / (2 * m)) - Math.Pow((sumTot + kI) / (2 * m), 2)) -
((sumIn / (2 * m)) - Math.Pow(sumTot / (2 * m), 2) - Math.Pow(kI / (2 * m), 2));
}
/// <summary>
/// Computes sum of weights of links inside the community.
/// </summary>
/// <param name="n">Network.</param>
/// <param name="c">Community.</param>
/// <returns>Sum of weights of links inside the community.</returns>
internal double GetSumIn(Network n, Community c)
{
var res = 0.0;
foreach (var e in n.FirstLayer.Edges)
{
if (c.Actors.Contains(e.From) && c.Actors.Contains(e.To))
{
res += e.Weight;
}
}
return res;
}
/// <summary>
/// Computes sum of the weights of the links incident to nodes in C.
/// </summary>
/// <param name="n">Network.</param>
/// <param name="c">Community.</param>
/// <returns>Sum of the weights of the links incident to nodes in C.</returns>
internal double GetSumTot(Network n, Community c)
{
var res = 0.0;
foreach (var e in n.FirstLayer.Edges)
{
if (c.Actors.Contains(e.From))
{
if (!c.Actors.Contains(e.To))
{
res += e.Weight;
}
}
else if (c.Actors.Contains(e.To))
{
if (!c.Actors.Contains(e.From))
{
res += e.Weight;
}
}
}
return res;
}
/// <summary>
/// Computes sum of the weights of the links incident to node i.
/// </summary>
/// <param name="n">Network.</param>
/// <param name="i">Actor.</param>
/// <returns>Sum of the weights of the links incident to node i.</returns>
internal double GetKI(Network n, Actor i)
{
var res = 0.0;
foreach (var e in n.FirstLayer.Edges)
{
if (e.From == i || e.To == i)
{
res += e.Weight;
}
}
return res;
}
/// <summary>
/// Computes Sum of the weights of the links from i to nodes in C.
/// </summary>
/// <param name="n">Network.</param>
/// <param name="i">Actor.</param>
/// <param name="c">Community.</param>
/// <returns>Sum of the weights of the links from i to nodes in c.</returns>
internal double GetKIn(Network n, Actor i, Community c)
{
var res = 0.0;
foreach (var e in n.FirstLayer.Edges)
{
if (e.From == i)
{
if (c.Actors.Contains(e.To))
{
res += e.Weight;
}
}
else if (e.To == i)
{
if (c.Actors.Contains(e.From))
{
res += e.Weight;
}
}
}
return res;
}
/// <summary>
/// Computes sum of weights of links in the network.
/// </summary>
/// <param name="network">Network.</param>
/// <returns>Sum of weights.</returns>
internal double GetM(Network network)
{
return network.FirstLayer.Edges.Sum(e => e.Weight);
}
}
}