Recherche de tag: louvain
louvain [Python]

import numpy as np
import os
def genlouvain(B, seed=None):
'''
The optimal community structure is a subdivision of the network into
nonoverlapping groups of nodes which maximizes the number of within-group
edges and minimizes the number of between-group edges.
This function is a fast an accurate multi-iterative generalization of the
louvain community detection algorithm. This function subsumes and improves
upon modularity_[louvain,finetune]_[und,dir]() and additionally allows to
optimize other objective functions (includes built-in Potts Model i
Hamiltonian, allows for custom objective-function matrices).
Parameters
----------
B : str | NxN np.arraylike
string describing objective function type, or provides a custom
objective-function matrix. builtin values 'modularity' uses Q-metric
as objective function, or 'potts' uses Potts model Hamiltonian.
Default value 'modularity'.
seed : int | None
random seed. default value=None. if None, seeds from /dev/urandom.
Returns
-------
ci : Nx1 np.array
final community structure
q : float
optimized q-statistic (modularity only)
'''
np.random.seed(seed)
st0 = np.random.get_state()
n = len(B)
ci = np.arange(n) + 1
Mb = ci.copy()
B = np.squeeze(np.asarray(B))
B = (B + B.T)/2.0
Hnm = np.zeros((n, n))
for m in range(1, n + 1):
Hnm[:, m - 1] = np.sum(B[:, ci == m], axis=1) # node to module degree
H = np.sum(Hnm, axis=1) # node degree
Hm = np.sum(Hnm, axis=0) # module degree
q0 = -np.inf
# compute modularity
q = np.sum(B[np.tile(ci, (n, 1)) == np.tile(ci, (n, 1)).T])
first_iteration = True
while q - q0 > 1e-10:
it = 0
flag = True
while flag:
it += 1
if it > 1000:
raise ValueError('Modularity infinite loop style G. '
'Please contact the developer.')
flag = False
for u in np.random.permutation(n):
ma = Mb[u] - 1
dQ = Hnm[u, :] - Hnm[u, ma] + B[u, u] # algorithm condition
dQ[ma] = 0
max_dq = np.max(dQ)
if max_dq > 1e-10:
flag = True
mb = np.argmax(dQ)
Hnm[:, mb] += B[:, u]
Hnm[:, ma] -= B[:, u] # change node-to-module strengths
Hm[mb] += H[u]
Hm[ma] -= H[u] # change module strengths
Mb[u] = mb + 1
_, Mb = np.unique(Mb, return_inverse=True)
Mb += 1
M0 = ci.copy()
if first_iteration:
ci = Mb.copy()
first_iteration = False
else:
for u in range(1, n + 1):
ci[M0 == u] = Mb[u - 1] # assign new modules
n = np.max(Mb)
b1 = np.zeros((n, n))
for i in range(1, n + 1):
for j in range(i, n + 1):
# pool weights of nodes in same module
bm = np.sum(B[np.ix_(Mb == i, Mb == j)])
b1[i - 1, j - 1] = bm
b1[j - 1, i - 1] = bm
B = b1.copy()
Mb = np.arange(1, n + 1)
Hnm = B.copy()
H = np.sum(B, axis=0)
Hm = H.copy()
q0 = q
q = np.trace(B) # compute modularity
dir = 'output'
if not os.path.isdir(dir): os.makedirs(dir)
output = open (os.path.join(dir, 'gen_louvain_seed.txt'),'a+')
print >> output, "%i" % (st0[1][0])
return ci, q
0/5 - [0 rating]