/
threeLayerConnComponentsPartition.py
369 lines (300 loc) · 13.3 KB
/
threeLayerConnComponentsPartition.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
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
364
365
366
367
368
369
__author__ = "Moses A. Boudourides & Sergios T. Lenis"
__copyright__ = "Copyright (C) 2015 Moses A. Boudourides & Sergios T. Lenis"
__license__ = "Public Domain"
__version__ = "1.0"
'''
This script finds the connected components of a 3-layer graph.
'''
import community as cm
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
import random
from collections import Counter
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
def analyticThreeLayerGraph(n,p,r1,r2,r3,G_isolates=True):
G=nx.erdos_renyi_graph(n,p)
if G_isolates:
G.remove_nodes_from(nx.isolates(G))
layer1 = random.sample(G.nodes(),int(len(G.nodes())*r1))
layer2 = random.sample(set(G.nodes())-set(layer1),int(len(G.nodes())*r2))
layer3 = list(set(G.nodes())-set(layer1)-set(layer2))
edgeList =[]
for e in G.edges():
if (e[0] in layer1 and e[1] in layer2) or (e[0] in layer2 and e[1] in layer1):
edgeList.append(e)
if (e[0] in layer2 and e[1] in layer3) or (e[0] in layer3 and e[1] in layer2):
edgeList.append(e)
if (e[0] in layer3 and e[1] in layer1) or (e[0] in layer1 and e[1] in layer3):
edgeList.append(e)
return G, layer1, layer2, layer3, edgeList
def create_node_conncomp_graph(G,layer1,layer2,layer3):
npartition = list(nx.connected_components(G))
layers={'layer1':layer1,'layer2':layer2,'layer3':layer3}
broken_partition={}
for i,v in enumerate(npartition):
vs=set(v)
for ii,vv in layers.items():
papa=vs.intersection(set(vv))
if len(papa)==len(v):
broken_partition['a_%i_%s_s' %(i,ii)]=v
elif len(papa)>0:
broken_partition['b_%i_%s' %(i,ii)]=list(papa)
vs=vs-set(vv)
broken_graph=nx.Graph()
rbroken_partition=dict()
colors=[name for name,hex in matplotlib.colors.cnames.iteritems()]
colors=list(set(colors)-set(['red','blue','green']))
cl=dict()
for i,v in broken_partition.items():
name=i.split('_')
for ii in v:
rbroken_partition[ii]=i
if name[-1]=='s':
cl[name[1]]=colors.pop()
elif name[0]=='b' and not cl.has_key(name[1]):
cl[name[1]]=colors.pop()
for i,v in rbroken_partition.items():
name=v.split('_')
broken_graph.add_node(v,color=cl[name[1]])
edg=G[i]
for j in edg:
if j not in broken_partition[v]:
if not broken_graph.has_edge(v,rbroken_partition[j]):
broken_graph.add_edge(v,rbroken_partition[j])
return broken_graph,broken_partition,npartition
def plot_graph_stack(G,broken_graph,broken_partition,npartition,layer1,layer2,layer3,d1=1.5,d2=5.,d3=0,d4=.8,nodesize=1000,withlabels=True,edgelist=[],layout=True,alpha=0.5):
if layout:
pos=nx.spring_layout(G)
else:
pos=nx.random_layout(G)
top_set=set()
bottom_set=set()
middle_set=set()
down=[]
right=[]
left=[]
mlayer_part={}
for i in broken_partition:
ii=i.split('_')
if ii[1] not in mlayer_part:
mlayer_part[ii[1]]=set([ii[2]])
else:
mlayer_part[ii[1]].add(ii[2])
layers_m=Counter()
for k,v in mlayer_part.items():
if len(v)==1:
layers_m[1]+=1
elif len(v)==2:
layers_m[2]+=1
elif len(v)==3:
layers_m[3]+=1
else:
print k,v
broken_pos={}
mlayer_part={}
for i in broken_partition:
# print i.split('_')
ii=i.split('_')
if ii[1] not in mlayer_part:
mlayer_part[ii[1]]=set([ii[2]])
else:
mlayer_part[ii[1]].add(ii[2])
layers_m=Counter()
for k,v in mlayer_part.items():
if len(v)==1:
layers_m[1]+=1
elif len(v)==2:
layers_m[2]+=1
elif len(v)==3:
layers_m[3]+=1
else:
print k,v
singles=0
for i,v in broken_partition.items():
name=i.split('_')
if name[-1]=='s':
singles+=1
ndnd=random.choice(v)
npos=pos[ndnd]
if ndnd in layer1:
broken_pos[i]=[d2*(npos[0]),d2*(npos[1]+d1)]
top_set.add(i)
left.append(broken_pos[i])
elif ndnd in layer2:
broken_pos[i]=[d2*(npos[0]),d2*(npos[1]-d1)]
bottom_set.add(i)
right.append(broken_pos[i])
else:
broken_pos[i]=[d2*npos[0],d2*(npos[1])]
middle_set.add(i)
down.append(broken_pos[i])
xleft=[i[0] for i in left]
yleft=[i[1] for i in left]
aleft = [min(xleft)-d1/2.,max(yleft)+d1/2.-d3]
bleft = [max(xleft)+d1/2.,max(yleft)+d1/2.+d3]
cleft = [max(xleft)+d1/2.-d4,min(yleft)-d1/2.+d3]
dleft = [min(xleft)-d1/2.-d4,min(yleft)-d1/2.-d3]
xright=[i[0] for i in right]
yright=[i[1] for i in right]
aright = [min(xright)-d1/2.,max(yright)+d1/2.-d3]
bright = [max(xright)+d1/2.,max(yright)+d1/2.+d3]
cright = [max(xright)+d1/2.-d4,min(yright)-d1/2.+d3]
dright = [min(xright)-d1/2.-d4,min(yright)-d1/2.-d3]
xdown=[i[0] for i in down]
ydown=[i[1] for i in down]
adown = [min(xdown)-d1/2.,max(ydown)+d1/2.-d3]
bdown = [max(xdown)+d1/2.,max(ydown)+d1/2.+d3]
cdown = [max(xdown)+d1/2.-d4,min(ydown)-d1/2.+d3]
ddown = [min(xdown)-d1/2.-d4,min(ydown)-d1/2.-d3]
fig=plt.figure(figsize=(20,20))
ax=fig.add_subplot(111)
ax.add_patch(Polygon([aleft,bleft,cleft,dleft],color='r',alpha=0.1))
plt.plot([aleft[0],bleft[0],cleft[0],dleft[0],aleft[0]],[aleft[1],bleft[1],cleft[1],dleft[1],aleft[1]],'-r')
ax.add_patch(Polygon([aright,bright,cright,dright],color='b',alpha=0.1))
plt.plot([aright[0],bright[0],cright[0],dright[0],aright[0]],[aright[1],bright[1],cright[1],dright[1],aright[1]],'-b')
ax.add_patch(Polygon([adown,bdown,cdown,ddown],color='g',alpha=0.1))
plt.plot([adown[0],bdown[0],cdown[0],ddown[0],adown[0]],[adown[1],bdown[1],cdown[1],ddown[1],adown[1]],'-g')
nodeSize=[nodesize*len(broken_partition[i]) for i in list(top_set)]
nodeColor=[broken_graph.node[i]['color'] for i in list(top_set) ]
nx.draw_networkx_nodes(broken_graph,broken_pos, nodelist=list(top_set),node_shape='s',node_color=nodeColor,alpha=1,node_size=nodeSize)
nodeSize=[nodesize*len(broken_partition[i]) for i in list(middle_set)]
nodeColor=[broken_graph.node[i]['color'] for i in list(middle_set) ]
nx.draw_networkx_nodes(broken_graph,broken_pos, nodelist=list(middle_set),node_shape='s',node_color=nodeColor,alpha=1,node_size=nodeSize)
nodeSize=[nodesize*len(broken_partition[i]) for i in list(bottom_set)]
nodeColor=[broken_graph.node[i]['color'] for i in list(bottom_set) ]
nx.draw_networkx_nodes(broken_graph,broken_pos,nodelist=list(bottom_set),node_shape='s',node_color=nodeColor,alpha=1,node_size=nodeSize)
if withlabels:
nx.draw_networkx_labels(G,pos)
lay1_edges=[ed for ed in G.edges() if ed[0] in layer1 and ed[1] in layer1]
lay2_edges=[ed for ed in G.edges() if ed[0] in layer2 and ed[1] in layer2]
lay3_edges=[ed for ed in G.edges() if ed[0] in layer3 and ed[1] in layer3]
nx.draw_networkx_edges(broken_graph,broken_pos,alpha=0.3)
for i,v in broken_partition.items():
for nd in v:
atrr=G.node[nd]
G.add_node(nd,attr_dict=atrr,asso=i)
# print G.nodes(data=True)
rr=nx.attribute_assortativity_coefficient(G,'asso')
# print 'Attribute assortativity coefficient wrt layer partition (old)= %f' %orr
title_s='%i connected components (%i 3-layered, %i 2-layered, %i 1-layered)\n Discrete assortativity coefficient of the joint partition for connected_components and 3 layers = %f ' %(len(npartition),layers_m[3],layers_m[2],layers_m[1],rr)
# title_s='%i connected components (%i 3-layered, %i 2-layered, %i 1-layered)' %(len(npartition),layers_m[3],layers_m[2],layers_m[1]) # %(len(npartition),len(npartition)-singles,singles)
plt.title(title_s,{'size': '20'})
plt.axis('off')
plt.show()
def plot_graph(G,broken_graph,broken_partition,npartition,layer1,layer2,layer3,d1=1.5,d2=5.,d3=0,d4=.8,nodesize=1000,withlabels=True,edgelist=[],layout=True,alpha=0.5):
if layout:
pos=nx.spring_layout(G)
else:
pos=nx.random_layout(G)
top_set=set()
bottom_set=set()
middle_set=set()
down=[]
right=[]
left=[]
mlayer_part={}
for i in broken_partition:
ii=i.split('_')
if ii[1] not in mlayer_part:
mlayer_part[ii[1]]=set([ii[2]])
else:
mlayer_part[ii[1]].add(ii[2])
layers_m=Counter()
for k,v in mlayer_part.items():
if len(v)==1:
layers_m[1]+=1
elif len(v)==2:
layers_m[2]+=1
elif len(v)==3:
layers_m[3]+=1
else:
print k,v
broken_pos={}
singles=0
for i,v in broken_partition.items():
name=i.split('_')
if name[-1]=='s':
singles+=1
ndnd=random.choice(v)
npos=pos[ndnd]
if ndnd in layer1:
broken_pos[i]=[d2*(npos[0]-d1),d2*(npos[1]+d1)]
top_set.add(i)
left.append(broken_pos[i])
elif ndnd in layer2:
broken_pos[i]=[d2*(npos[0]+d1),d2*(npos[1]+d1)]
bottom_set.add(i)
right.append(broken_pos[i])
else:
broken_pos[i]=[d2*npos[0],d2*(npos[1]-d1)]
middle_set.add(i)
down.append(broken_pos[i])
xleft=[i[0] for i in left]
yleft=[i[1] for i in left]
aleft = [min(xleft)-d1/2.,max(yleft)+d1/2.+d3]
bleft = [max(xleft)+d1/2.,max(yleft)+d1/2.+3*d3]
cleft = [max(xleft)+d1/2.,min(yleft)-d1/2.-3*d3]
dleft = [min(xleft)-d1/2.,min(yleft)-d1/2.-d3]
xright=[i[0] for i in right]
yright=[i[1] for i in right]
aright = [min(xright)-d1/2.,max(yright)+d1/2.+d3]
bright = [max(xright)+d1/2.,max(yright)+d1/2.+3*d3]
cright = [max(xright)+d1/2.,min(yright)-d1/2.-3*d3]
dright = [min(xright)-d1/2.,min(yright)-d1/2.-d3]
xdown=[i[0] for i in down]
ydown=[i[1] for i in down]
adown = [min(xdown)-d1/2.,max(ydown)+d1/2.+d3]
bdown = [max(xdown)+d1/2.,max(ydown)+d1/2.+3*d3]
cdown = [max(xdown)+d1/2.,min(ydown)-d1/2.-3*d3]
ddown = [min(xdown)-d1/2.,min(ydown)-d1/2.-d3]
fig=plt.figure(figsize=(20,20))
ax=fig.add_subplot(111)
ax.add_patch(Polygon([aleft,bleft,cleft,dleft],color='r',alpha=0.1))
plt.plot([aleft[0],bleft[0],cleft[0],dleft[0],aleft[0]],[aleft[1],bleft[1],cleft[1],dleft[1],aleft[1]],'-r')
ax.add_patch(Polygon([aright,bright,cright,dright],color='b',alpha=0.1))
plt.plot([aright[0],bright[0],cright[0],dright[0],aright[0]],[aright[1],bright[1],cright[1],dright[1],aright[1]],'-b')
ax.add_patch(Polygon([adown,bdown,cdown,ddown],color='g',alpha=0.1))
plt.plot([adown[0],bdown[0],cdown[0],ddown[0],adown[0]],[adown[1],bdown[1],cdown[1],ddown[1],adown[1]],'-g')
nodeSize=[nodesize*len(broken_partition[i]) for i in list(top_set)]
nodeColor=[broken_graph.node[i]['color'] for i in list(top_set) ]
nx.draw_networkx_nodes(broken_graph,broken_pos, nodelist=list(top_set),node_shape='s',node_color=nodeColor,alpha=1,node_size=nodeSize)
nodeSize=[nodesize*len(broken_partition[i]) for i in list(middle_set)]
nodeColor=[broken_graph.node[i]['color'] for i in list(middle_set) ]
nx.draw_networkx_nodes(broken_graph,broken_pos, nodelist=list(middle_set),node_shape='s',node_color=nodeColor,alpha=1,node_size=nodeSize)
nodeSize=[nodesize*len(broken_partition[i]) for i in list(bottom_set)]
nodeColor=[broken_graph.node[i]['color'] for i in list(bottom_set) ]
nx.draw_networkx_nodes(broken_graph,broken_pos,nodelist=list(bottom_set),node_shape='s',node_color=nodeColor,alpha=1,node_size=nodeSize)
if withlabels:
nx.draw_networkx_labels(G,pos)
lay1_edges=[ed for ed in G.edges() if ed[0] in layer1 and ed[1] in layer1]
lay2_edges=[ed for ed in G.edges() if ed[0] in layer2 and ed[1] in layer2]
lay3_edges=[ed for ed in G.edges() if ed[0] in layer3 and ed[1] in layer3]
nx.draw_networkx_edges(broken_graph,broken_pos,alpha=0.3) #0.15
# orr=nx.attribute_assortativity_coefficient(broken_graph,'color')
for i,v in broken_partition.items():
for nd in v:
atrr=G.node[nd]
G.add_node(nd,attr_dict=atrr,asso=i)
rr=nx.attribute_assortativity_coefficient(G,'asso')
# print 'Attribute assortativity coefficient wrt layer partition (old) = %f' %orr
title_s='%i connected components (%i 3-layered, %i 2-layered, %i 1-layered)\n Discrete assortativity coefficient of the joint partition for connected_components and 3 layers = %f ' %(len(npartition),layers_m[3],layers_m[2],layers_m[1],rr)
plt.title(title_s,{'size': '20'})
plt.axis('off')
plt.show()
# n = 50
# p = 0.05
# r1 = 0.333
# r2 = 0.333
# r3 = 0.333
# G, layer1, layer2, layer3, edgeList = analyticThreeLayerGraph(n,p,r1,r2,r3,G_isolates=False)
# # # print G.nodes()
# # # print layer1
# # # print layer2
# # # print layer3
# broken_graph,broken_partition,npartition=create_node_conncomp_graph(G,layer1,layer2,layer3)
# # # print broken_partition
# print broken_graph.nodes(data=True)
# plot_graph(G,broken_graph,broken_partition,npartition,layer1,layer2,layer3,withlabels=False,nodesize=10,layout=False)