-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhiclus_blockmodel.py
47 lines (40 loc) · 1.62 KB
/
hiclus_blockmodel.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
__author__ = """\n""".join(['Maksim Tsvetovat <[email protected]','Drew Conway <[email protected]>',
'Aric Hagberg <[email protected]>'])
from collections import defaultdict
import networkx as nx
import numpy
from scipy.cluster import hierarchy
from scipy.spatial import distance
import matplotlib.pyplot as plt
import hc
"""Draw a blockmodel diagram of a clustering alongside the original network"""
def hiclus_blockmodel(G):
# Extract largest connected component into graph H
#H=nx.connected_component_subgraphs(G)[0]
# H = G.subgraph(max(nx.connected_components(G), key=len))
# Create parititions with hierarchical clustering
H = G.copy()
partitions = hc.create_hc(H)
# Build blockmodel graph
#BM=nx.blockmodel(H,partitions)
BM = nx.quotient_graph(H, partitions)
# Draw original graph
pos=nx.spring_layout(H,iterations=100)
fig=plt.figure(1,figsize=(6,10))
ax=fig.add_subplot(211)
nx.draw(H,pos, node_size=10, with_labels=True, ax=ax)
# plt.xlim(0,1)
# plt.ylim(0,1)
# Draw block model with weighted edges and nodes sized by number of internal nodes
node_size=[BM.node[x]['nnodes']*10 for x in BM.nodes()]
edge_width=[(2*d['weight']) for (u,v,d) in BM.edges(data=True)]
# Set positions to mean of positions of internal nodes from original graph
posBM={}
for n in BM:
xy=numpy.array([pos[u] for u in BM.node[n]['graph']])
posBM[n]=xy.mean(axis=0)
ax=fig.add_subplot(212)
nx.draw(BM,posBM,node_size=node_size,width=edge_width,with_labels=False, ax=ax)
# plt.xlim(0,1)
# plt.ylim(0,1)
# plt.axis('off')