-
Notifications
You must be signed in to change notification settings - Fork 1
/
Modularity.cs
81 lines (74 loc) · 2.38 KB
/
Modularity.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
using MNCD.Core;
using MNCD.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MNCD.Evaluation.SingleLayer
{
/// <summary>
/// Class that implements modularity measure.
/// Based on: http://networksciencebook.com/chapter/9#modularity.
/// </summary>
public static class Modularity
{
/// <summary>
/// Computes modularity for network patitioning.
/// </summary>
/// <param name="network">
/// Network that is partitioned.
/// </param>
/// <param name="communities">
/// List of communities for which the modularity should be computed.
/// </param>
/// <returns>Modularity of the partition.</returns>
public static double Compute(Network network, List<Community> communities)
{
var edges = network.FirstLayer.Edges;
var l = (double)edges.Count();
var lc = CommunityToLinkCount(edges, communities);
var kc = CommunityToDegrees(network, communities);
var m = 0.0;
foreach (var c in communities)
{
m += (lc[c] / l) - Math.Pow(kc[c] / (2.0 * l), 2.0);
}
return m;
}
private static Dictionary<Community, int> CommunityToLinkCount(
List<Edge> edges,
List<Community> communities)
{
var res = communities.ToDictionary(c => c, c => 0);
foreach (var edge in edges)
{
foreach (var c in communities)
{
if (c.Actors.Contains(edge.From) &&
c.Actors.Contains(edge.To))
{
res[c]++;
}
}
}
return res;
}
private static Dictionary<Community, int> CommunityToDegrees(
Network network,
List<Community> communities)
{
var atd = network.GetActorToDegree();
var res = communities.ToDictionary(c => c, c => 0);
foreach (var c in communities)
{
foreach (var a in c.Actors)
{
if (atd.ContainsKey(a))
{
res[c] += (int)atd[a];
}
}
}
return res;
}
}
}