-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdiverse_club.py
2094 lines (1954 loc) · 96.6 KB
/
diverse_club.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/home/despoB/mb3152/anaconda2/bin/python
# rich club stuff
from richclub import preserve_strength, RC
# graph theory stuff you might have
import brain_graphs
import networkx as nx
import community as louvain
import igraph
from igraph import Graph, ADJ_UNDIRECTED, VertexClustering, arpack_options
arpack_options.maxiter=300000 #spectral community detection fails without this
#standard stuff you probably have
import pandas as pd
import os
import sys
import time
from collections import Counter
import numpy as np
from quantities import millimeter
import subprocess
import pickle
import random
import scipy
from scipy.io import loadmat
import scipy.io as sio
from scipy.stats.stats import pearsonr
from sklearn.metrics.cluster import normalized_mutual_info_score
from itertools import combinations, permutations
import glob
import math
from multiprocessing import Pool
#plotting
import seaborn as sns
import matplotlib.pylab as plt
import matplotlib as mpl
from matplotlib import patches
import matplotlib.gridspec as gridspec
plt.rcParams['pdf.fonttype'] = 42
path = '/home/despoB/mb3152/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf/Helvetica.ttf'
mpl.font_manager.FontProperties(fname=path)
mpl.rcParams['font.family'] = 'Helvetica'
#some globals that we want to have everywhere
global homedir #set this to wherever you save the repo to, e.g., mine is in /home/despoB/mb3152/diverse_club/
homedir = '/home/despoB/mb3152/'
global tasks #HCP tasks
tasks = ['WM','GAMBLING','RELATIONAL','MOTOR','LANGUAGE','SOCIAL','REST']
global costs #for functional connectivity matrices
costs = np.arange(5,21) *0.01
global algorithms
global algorithm_names
global cores
cores = 2
algorithm_names = np.array(['infomap','walktrap','spectral','edge betweenness','label propogation','louvain','spin glass','walktrap (n)','louvain (resolution)'])
algorithms = np.array(['infomap','walktrap','spectral','edge_betweenness','label_propogation','louvain','spin_glass','walktrap_n','louvain_res'])
order = np.array(['infomap','walktrap','spectral','edge_betweenness','label_propogation','louvain','spin_glass','rich club, thresholded','rich club, dense','walktrap_n','louvain_res'])
def corrfunc(x, y, **kws):
r, _ = pearsonr(x, y)
ax = plt.gca()
ax.annotate("r={:.3f}".format(r) + ",p={:.3f}".format(_),xy=(.1, .9), xycoords=ax.transAxes)
def tstatfunc(x, y,bc=False):
t, p = scipy.stats.ttest_ind(x,y)
if bc != False:
bfc = np.around((p * bc),5)
p = np.around(p,5)
if bfc <= 0.05:
if bfc == 0.0:
bfc = ' < 1e-5'
if p == 0.0:
p = ' < 1e-5'
return "t=%s \n p=%s \n bf=%s" %(np.around(t,3),p,bfc)
else:
return "t=%s" %(np.around(t,3))
else:
p = np.around(p,5)
if p == 0.0:
p = ' < 1e-5'
return "t=%s,p=%s" %(np.around(t,3),p)
def small_tstatfunc(x, y,bc=False):
t, p = scipy.stats.ttest_ind(x,y)
if bc != False:
bfc = (p * bc)
if p < 1e-5: pstr = '*!'
elif p < .05: pstr = '*'
else: pstr = None
if bfc <= 0.05:
if bfc < 1e-5: bfc = '*!'
else: bfc = '*'
return "%s \n p%s \n bf%s" %(np.around(t,3),pstr,bfc)
elif p<0.05: return "t=%s \n p%s" %(np.around(t,3),pstr)
else: return ""
else:
if p < 1e-5: pst = '*!'
elif p < .05: pst = '*'
else: pstr = None
if pstr == None: return "%s" %(np.around(t,3))
else: return "%s \n p%s" %(np.around(t,3),p)
def really_small_tstatfunc(x, y,bc=False):
t, p = scipy.stats.ttest_ind(x,y)
t = int(t)
if bc != False:
bfc = (p * bc)
if bfc < 1e-5: bfc = str(t) + '**'
elif bfc < 0.05: bfc = str(t) + '*'
else: bfc = ''
return bfc
else:
if p < 1e-5: pst = str(t) + '**'
elif p < .05: pst = str(t) + '* '
else: pstr = ''
return pst
def mm_2_inches(mm):
mm = mm * millimeter
mm.units = 'inches'
return mm.item()
def participation_coef(W, ci, degree='undirected'):
'''
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
Flag to describe nature of graph 'undirected': For undirected graphs
'in': Uses the in-degree
'out': Uses the out-degree
Returns
-------
P : Nx1 np.ndarray
participation coefficient
'''
if degree == 'in':
W = W.T
_, ci = np.unique(ci, return_inverse=True)
ci += 1
n = len(W) # number of vertices
Ko = np.sum(W, axis=1) # (out) degree
Gc = np.dot((W != 0), np.diag(ci)) # neighbor community affiliation
Kc2 = np.zeros((n,)) # community-specific neighbors
for i in range(1, int(np.max(ci)) + 1):
Kc2 += np.square(np.sum(W * (Gc == i), axis=1))
P = np.ones((n,)) - Kc2 / np.square(Ko)
# P=0 if for nodes with no (out) neighbors
P[np.where(np.logical_not(Ko))] = 0
return P
def load_object(path_to_object):
f = open('%s' %(path_to_object),'r')
return pickle.load(f)
def save_object(o,path_to_object):
f = open(path_to_object,'w+')
pickle.dump(o,f)
f.close()
def make_airport_graph():
vs = []
sources = pd.read_csv('/%s/diverse_club/graphs/routes.dat'%(homedir),header=None)[3].values
dests = pd.read_csv('/%s/diverse_club/graphs/routes.dat'%(homedir),header=None)[5].values
graph = Graph()
for s in sources:
if s in dests: continue
try: vs.append(int(s))
except: continue
for s in dests:
try: vs.append(int(s))
except: continue
graph.add_vertices(np.unique(vs).astype(str))
sources = pd.read_csv('/%s/diverse_club/graphs/routes.dat'%(homedir),header=None)[3].values
dests = pd.read_csv('/%s/diverse_club/graphs//routes.dat'%(homedir),header=None)[5].values
for s,d in zip(sources,dests):
if s == d:continue
try:
int(s)
int(d)
except: continue
if int(s) not in vs: continue
if int(d) not in vs: continue
s = str(s)
d = str(d)
eid = graph.get_eid(s,d,error=False)
if eid == -1: graph.add_edge(s,d,weight=1)
else: graph.es[eid]['weight'] = graph.es[eid]["weight"] + 1
graph.delete_vertices(np.argwhere((np.array(graph.degree())==0)==True).reshape(-1))
v_to_d = []
for i in range(graph.vcount()):
if len(graph.subcomponent(i)) < 3000:
v_to_d.append(i)
graph.delete_vertices(v_to_d)
graph.write_gml('/%s/diverse_club/graphs/airport.gml'%(homedir))
airports = pd.read_csv('/%s/diverse_club/graphs/airports.dat'%(homedir),header=None)
longitudes = []
latitudes = []
for v in range(graph.vcount()):
latitudes.append(airports[6][airports[0]==int(graph.vs['name'][v])].values[0])
longitudes.append(airports[7][airports[0]==int(graph.vs['name'][v])].values[0])
vc = brain_graphs.brain_graph(graph.community_infomap(edge_weights='weight'))
degree = graph.strength(weights='weight')
graph.vs['community'] = np.array(vc.community.membership)
graph.vs['longitude'] = np.array(longitudes)
graph.vs['latitude'] = np.array(latitudes)
graph.vs['pc'] = np.array(vc.pc)
graph.write_gml('/%s/diverse_club/graphs/airport_viz.gml'%(homedir))
def nan_pearsonr(x,y):
x = np.array(x)
y = np.array(y)
isnan = np.sum([x,y],axis=0)
isnan = np.isnan(isnan) == False
return pearsonr(x[isnan],y[isnan])
def attack(variables):
np.random.seed(variables[0])
vc = variables[1]
n_attacks = variables[2]
rankcut = variables[3]
graph = vc.community.graph
pc = vc.pc
pc[np.isnan(pc)] = 0.0
deg = np.array(vc.community.graph.strength(weights='weight'))
connector_nodes = np.argsort(pc)[rankcut:]
degree_nodes = np.argsort(deg)[rankcut:]
healthy_sp = np.sum(np.array(graph.shortest_paths()))
degree_edges = []
for d in combinations(degree_nodes,2):
if graph[d[0],d[1]] > 0:
degree_edges.append([d])
connector_edges = []
for d in combinations(connector_nodes,2):
if graph[d[0],d[1]] > 0:
connector_edges.append([d])
connector_edges = np.array(connector_edges)
degree_edges = np.array(degree_edges)
idx = 0
de = len(connector_edges)
dmin = int(de*.5)
dmax = int(de*.9)
attack_degree_sps = []
attack_pc_sps = []
attack_degree_mods = []
attack_pc_mods = []
while True:
num_kill = np.random.choice(range(dmin,dmax),1)[0]
np.random.shuffle(degree_edges)
np.random.shuffle(connector_edges)
d_edges = degree_edges[:num_kill]
c_edges = connector_edges[:num_kill]
d_graph = graph.copy()
c_graph = graph.copy()
for cnodes,dnodes in zip(c_edges.reshape(c_edges.shape[0],2),d_edges.reshape(d_edges.shape[0],2)):
cnode1,cnode2,dnode1,dnode2 = cnodes[0],cnodes[1],dnodes[0],dnodes[1]
d_graph.delete_edges([(dnode1,dnode2)])
c_graph.delete_edges([(cnode1,cnode2)])
if d_graph.is_connected() == False or c_graph.is_connected() == False:
d_graph.add_edges([(dnode1,dnode2)])
c_graph.add_edges([(cnode1,cnode2)])
deg_sp = np.array(d_graph.shortest_paths()).astype(float)
c_sp = np.array(c_graph.shortest_paths()).astype(float)
attack_degree_sps.append(np.nansum(deg_sp))
attack_pc_sps.append(np.nansum(c_sp))
idx = idx + 1
if idx == n_attacks:
break
return [attack_pc_sps,attack_degree_sps,healthy_sp]
def check_network(network):
loops = np.array(network.community.graph.is_loop())
multiples = np.array(network.community.graph.is_multiple())
assert network.community.graph.is_connected() == True
assert np.isnan(network.pc).any() == False
assert len(loops[loops==True]) == 0.0
assert len(multiples[multiples==True]) == 0.0
assert network.community.graph.has_multiple() == False
assert network.community.graph.is_directed() == False
assert network.community.graph.is_weighted()
assert np.min(network.community.graph.degree()) > 0
assert np.isnan(network.community.graph.degree()).any() == False
assert np.nanmax(np.array(network.pc)) < 1.
assert np.isclose(network.pc,participation_coef(np.array(network.matrix),np.array(network.community.membership))).all() == True
assert np.isclose(network.pc,participation_coef(np.array(network.matrix),np.array(network.community.membership).reshape(-1,1))).all() == True
assert np.sum(abs(network.pc-participation_coef(np.array(network.matrix),np.array(network.community.membership)))) < 1e-10
def random_test(network,rankcut):
nr = load_object('/%s/diverse_club/results/%s_%s_%s.obj'%(homedir,network,rankcut,'random'))
n = load_object('/%s/diverse_club/results/%s_%s_%s.obj'%(homedir,network,.8,'infomap'))
rs = []
for i in range(1000):
rs.append(pearsonr(nr.networks[i].pc,nr.networks[i].wmd)[0])
print 'random_pc & random wmd ' + str(np.mean(rs))
rs = []
for i in range(len(n.networks)):
rs.append(pearsonr(n.networks[i].pc,n.networks[i].wmd)[0])
print 'real_pc and real wmd ' + str(np.mean(rs))
rs = []
for i in range(1000):
rs.append(pearsonr(nr.networks[i].pc,nr.networks[i].community.graph.strength(weights='weight'))[0])
print 'random_pc & real degree ' + str(np.mean(rs))
rs = []
for i in range(len(n.networks)):
rs.append(pearsonr(n.networks[i].pc,n.networks[i].community.graph.strength(weights='weight'))[0])
print 'real_pc and real degree ' + str(np.mean(rs))
rs = []
for i in range(1000):
a = n.networks[int(nr.networks[i].community.graph.density()*100)-5].pc.copy()
b = nr.networks[i].pc.copy()
a[a ==0.0] = np.nan
b[b ==0.0] = np.nan
rs.append(nan_pearsonr(a,b)[0])
print 'real_pc and random pc ' + str(np.mean(rs))
rs = []
for i in range(1,999):
a = nr.networks[0].pc.copy()
if int(nr.networks[i].community.graph.density()*100) == 19:
b = nr.networks[i].pc.copy()
a[a ==0.0] = np.nan
b[b ==0.0] = np.nan
rs.append(nan_pearsonr(a,b)[0])
def plot_brainmap(measure='components'):
diverse_df = pd.read_csv('%s/diverse_club/results/diverse_brainmap.csv'%(homedir)).rename(columns={'Modules Engaged':'communities engaged','Club Activity':'club activity','Components Engaged':'components engaged'})
d_rs = []
for algorithm in algorithms:
tdf = diverse_df[diverse_df['Community Algorithm']==algorithm]
p = pearsonr(tdf['club activity'],tdf['%s engaged'%(measure)])[0]
d_rs.append(p)
colors = np.zeros((9,3))
colors[np.ix_([0,1])] = sns.cubehelix_palette(8)[-3],sns.cubehelix_palette(8)[3]
colors[np.ix_([2,3,4,5,6,7,8])] = np.array(sns.color_palette("cubehelix", 18))[-7:]
sns.lmplot(x="%s engaged"%(measure), y="club activity", hue="Community Algorithm", data=diverse_df, palette=colors,legend=False,size=8)
sns.plt.legend(loc=2)
sns.plt.title('mean r: ' +str(np.mean(d_rs))[:5])
sns.plt.savefig('/%s/diverse_club/figures/diverse_brainmap_%s.pdf'%(homedir,measure))
sns.plt.show()
rich_df = pd.read_csv('%s/diverse_club/results/rich_brainmap.csv'%(homedir)).rename(columns={'Modules Engaged':'communities engaged','Club Activity':'club activity','Components Engaged':'components engaged'})
rich_df = rich_df[(rich_df['Community Algorithm'] == 'infomap') | (rich_df['Community Algorithm'] == 'louvain_res')]
r_rs = []
for algorithm in ['infomap','louvain_res']:
tdf = rich_df[rich_df['Community Algorithm']==algorithm]
p = pearsonr(tdf['club activity'],tdf['%s engaged'%(measure)])[0]
r_rs.append(p)
rich_df['Community Algorithm'][rich_df['Community Algorithm']=='infomap'] = 'sparse'
rich_df['Community Algorithm'][rich_df['Community Algorithm']=='louvain_res'] = 'dense'
colors = np.zeros((2,3))
colors[0] = sns.light_palette("green")[5][:3]
colors[1] = sns.light_palette("green")[2][:3]
sns.lmplot(x="%s engaged"%(measure), y="club activity", hue="Community Algorithm", data=rich_df, palette=colors,legend=False,size=8)
sns.plt.legend(loc=2)
sns.plt.title('mean r: ' +str(np.mean(r_rs))[:5])
sns.plt.savefig('/%s/diverse_club/figures/rich_brainmap_%s.pdf'%(homedir,measure))
sns.plt.show()
def plot_community_stats(network,network_objects,measure='sizes'):
# if network_objects == None:
# network_objects = []
# for community_alg in algorithms:
# print community_alg
# network_objects.append(load_object('/%s/diverse_club/graphs/graph_objects/%s_0.8_%s.obj'%(homedir,network,community_alg)))
if network == 'f_c_elegans':
iters = ['Worm1','Worm2','Worm3','Worm4']
if network == 'human':
iters = tasks
if network == 'structural_networks':
iters = ['c elegans','macaque','flight traffic','US power grid']
sns.set(context="paper",font='Helvetica',style='white')
nconditions = len(iters)
if nconditions/2 == nconditions/2.:
fig,subplots = sns.plt.subplots(int(np.ceil((nconditions+1)/2.)),2,figsize=(mm_2_inches(183),mm_2_inches(61.75*np.ceil((nconditions+1)/2.))))
subplots = subplots.reshape(-1)
else:
fig,subplots = sns.plt.subplots(int(np.ceil(nconditions/2.)),2,figsize=(mm_2_inches(183),mm_2_inches(61.75*np.ceil(nconditions/2.))))
subplots = subplots.reshape(-1)
for sidx,name_idx in enumerate(iters):
sizes = np.zeros((9,16))
q_values = np.zeros((9,16))
q_values[:] = np.nan
sizes[:] = np.nan
for idx,alg in enumerate(algorithms):
n = load_object('/%s/diverse_club/graphs/graph_objects/%s_0.8_%s.obj'%(homedir,network,alg))
niter = 0
for nidx,nn in enumerate(n.networks):
if n.names[nidx].split('_')[0] != '%s'%(name_idx) and n.names[nidx].split('_')[0] != '%s'%(name_idx.lower()):
continue
sizes[idx,niter] = int(len(nn.community.sizes()))
q_values[idx,niter] = nn.community.modularity
niter += 1
sizes[-2] = np.flip(sizes[-2],axis=0)
q_values[-2] = np.flip(q_values[-2],axis=0)
if measure == 'sizes':
plot_matrix = sizes
fmt = ".0f"
if measure == 'q':
plot_matrix = q_values
fmt = ".2f"
plot_matrix[plot_matrix<0.0] = 0.0
heatfig = sns.heatmap(plot_matrix,annot=True,xticklabels=[''],yticklabels=np.flip(algorithm_names,0),square=True,rasterized=True,ax=subplots[sidx],cbar=False,fmt=fmt,annot_kws={"size": 5})
heatfig.set_yticklabels(np.flip(heatfig.axes.get_yticklabels(),0),rotation=360,fontsize=6)
heatfig.set_xlabel('density, resolution (louvain), or n (walktrap)')
heatfig.set_title(name_idx.lower(),fontdict={'fontsize':'large'})
if len(subplots) - nconditions == 2:
for ax in subplots[-2:]:
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.spines['left'].set_color('white')
ax.spines['bottom'].set_color('white')
ax.spines['right'].set_color('white')
ax.spines['top'].set_color('white')
else:
ax = subplots[-1]
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.spines['left'].set_color('white')
ax.spines['bottom'].set_color('white')
ax.spines['right'].set_color('white')
ax.spines['top'].set_color('white')
sns.plt.tight_layout()
sns.plt.savefig('%s/diverse_club/figures/%s_all_%s.pdf'%(homedir,network,measure))
sns.plt.close()
def plot_similarity(network,network_objects=None,measure='nmi'):
def plot_pc_correlations(matrix,labels,nlabels,title,savestr,measure):
if measure == 'nmi': heatmap = sns.heatmap(pd.DataFrame(matrix,columns=labels),square=True,yticklabels=nlabels,xticklabels=nlabels,**{'vmin':0.0,'vmax':1.0})
else: heatmap = sns.heatmap(pd.DataFrame(matrix,columns=labels),square=True,yticklabels=nlabels,xticklabels=nlabels,cmap = "RdBu_r",**{'vmin':-1,'vmax':1.0})
heatmap.set_xticklabels(heatmap.axes.get_xticklabels(),rotation=90,fontsize=6)
heatmap.set_yticklabels(np.flip(heatmap.axes.get_xticklabels(),0),rotation=360,fontsize=6)
mean=np.nanmean(matrix[matrix!=1])
heatmap.set_title(title + ', mean=%s'%(np.around(mean,3)))
sns.plt.tight_layout()
sns.plt.savefig(savestr,dpi=600)
sns.plt.close()
# for each species, show similarity of pc across algorithms
if network != 'structural_networks':
if network_objects == None:
network_objects = []
for community_alg in algorithms:
network_objects.append(load_object('/%s/diverse_club/graphs/graph_objects/%s_0.8_%s.obj'%(homedir,network,community_alg)))
if network == 'human':
matrices = []
for task in tasks:
labels = []
alglabels = []
plot_network_objects = []
for i in range(len(network_objects)):
if algorithms[i] == 'louvain_res':
subsetiters = np.linspace(.4,.8,16)
elif algorithms[i] == 'walktrap_n':
subsetiters = np.array([5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
else:
subsetiters = costs
label_idx = 0
for j in range(len(network_objects[i].names)):
if task in network_objects[i].names[j] or task.lower() in network_objects[i].names[j]:
plot_network_objects.append(network_objects[i].networks[j])
labels.append(algorithms[i] + ',' + str(np.around(subsetiters[label_idx],4)))
alglabels.append(algorithms[i])
label_idx += 1
task_pc_matrix = np.zeros((len(plot_network_objects),len(plot_network_objects)))
for i in range(len(plot_network_objects)):
for j in range(len(plot_network_objects)):
if measure == 'nmi': task_pc_matrix[i,j] = normalized_mutual_info_score(plot_network_objects[i].community.membership,plot_network_objects[j].community.membership)
else: task_pc_matrix[i,j] = scipy.stats.spearmanr(plot_network_objects[i].pc,plot_network_objects[j].pc)[0]
matrices.append(task_pc_matrix)
savestr = '/%s/diverse_club/figures/individual/%s_similarity_algorithms_human_%s.pdf'%(homedir,measure,task)
plot_pc_correlations(task_pc_matrix,labels,4,'human (%s)'%(task.lower()),savestr,measure)
savestr = savestr.replace('figures/individual','results')
savestr = savestr.replace('pdf','npy')
np.save(savestr,task_pc_matrix)
savestr = '/%s/diverse_club/figures/%s_similarity_algorithms_human_mean.pdf'%(homedir,measure)
plot_pc_correlations(np.nanmean(matrices,axis=0),labels,4,'human, mean across tasks',savestr,measure)
savestr = savestr.replace('figures','results')
savestr = savestr.replace('pdf','npy')
np.save(savestr,np.nanmean(matrices,axis=0))
if network == 'f_c_elegans':
matrices = []
for worm in ['Worm1','Worm2','Worm3','Worm4']:
labels = []
alglabels = []
plot_network_objects = []
for i in range(len(network_objects)):
if algorithms[i] == 'louvain_res':
subsetiters = np.linspace(.4,.8,16)
elif algorithms[i] == 'walktrap_n':
subsetiters = np.array([5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
else:
subsetiters = costs
label_idx = 0
for j in range(len(network_objects[i].names)):
if worm in network_objects[i].names[j]:
plot_network_objects.append(network_objects[i].networks[j])
labels.append(algorithms[i] + ',' + str(np.around(subsetiters[label_idx],4)))
alglabels.append(algorithms[i])
label_idx += 1
task_pc_matrix = np.zeros((len(plot_network_objects),len(plot_network_objects)))
for i in range(len(plot_network_objects)):
for j in range(len(plot_network_objects)):
if measure == 'nmi': task_pc_matrix[i,j] = normalized_mutual_info_score(plot_network_objects[i].community.membership,plot_network_objects[j].community.membership)
else: task_pc_matrix[i,j] = scipy.stats.spearmanr(plot_network_objects[i].pc,plot_network_objects[j].pc)[0]
matrices.append(task_pc_matrix)
savestr = '/%s/diverse_club/figures/individual/%s_similarity_algorithms_f_c_elegans_%s.pdf'%(homedir,measure,worm)
plot_pc_correlations(task_pc_matrix,labels,4,'functional c elegans, %s'%(worm.lower()),savestr,measure)
savestr = savestr.replace('figures/individual','results')
savestr = savestr.replace('pdf','npy')
np.save(savestr,task_pc_matrix)
savestr = '/%s/diverse_club/figures/%s_similarity_algorithms_f_c_elegans_mean.pdf'%(homedir,measure)
plot_pc_correlations(np.nanmean(matrices,axis=0),labels,4,'functional c elegans, mean across worms',savestr,measure)
savestr = savestr.replace('figures','results')
savestr = savestr.replace('pdf','npy')
np.save(savestr,np.nanmean(matrices,axis=0))
if network == 'structural_networks':
matrices = []
for structural_network in ['macaque','c_elegans','US power grid','flight traffic']:
if structural_network == 'c_elegans':
structural_network = 'c elegans'
labels = []
alglabels = []
plot_network_objects = []
for i in range(len(algorithms)):
print algorithms[i]
if algorithms[i] == 'louvain_res':
subsetiters = np.linspace(.4,.8,16)
elif algorithms[i] == 'walktrap_n':
subsetiters = np.array([5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
else:
subsetiters = range(16)
label_idx = 0
network_object = load_object('/%s/diverse_club/graphs/graph_objects/%s_0.8_%s.obj'%(homedir,network,algorithms[i]))
for j in range(len(network_object.names)):
if structural_network in network_object.names[j]:
plot_network_objects.append(network_object.networks[j])
labels.append(algorithms[i] + ',' + str(np.around(subsetiters[label_idx],4)))
alglabels.append(algorithms[i])
label_idx += 1
pc_matrix = np.zeros((len(plot_network_objects),len(plot_network_objects)))
for i in range(len(plot_network_objects)):
for j in range(len(plot_network_objects)):
if measure == 'nmi': pc_matrix[i,j] = normalized_mutual_info_score(plot_network_objects[i].community.membership,plot_network_objects[j].community.membership)
else: pc_matrix[i,j] = scipy.stats.spearmanr(plot_network_objects[i].pc,plot_network_objects[j].pc)[0]
savestr = '/%s/diverse_club/figures/%s_similarity_algorithms_sturctural_%s.pdf'%(homedir,measure,structural_network)
plot_pc_correlations(pc_matrix,labels,4,structural_network,savestr,measure)
# if measure == 'nmi': heatmap = sns.heatmap(pc_matrix,square=True,cmap = "RdBu_r",**{'vmin':0.0,'vmax':1.0})
# else: heatmap = sns.heatmap(pc_matrix,square=True,cmap = "RdBu_r",**{'vmin':-1.0,'vmax':1.0})
# heatmap.set_xticklabels(algorithms,rotation=90,fontsize=6)
# heatmap.set_yticklabels(np.flip(algorithms,0),rotation=360,fontsize=6)
# mean=np.nanmean(pc_matrix[pc_matrix!=1])
# heatmap.set_title(title + ', mean=%s'%(np.around(mean,3)))
# sns.plt.tight_layout()
# sns.plt.savefig(savestr,dpi=600)
# sns.plt.close()
savestr = savestr.replace('figures','results')
savestr = savestr.replace('pdf','npy')
np.save(savestr,pc_matrix)
def plot_degree_distribution(network):
network_objects = []
network_objects.append(load_object('/%s/diverse_club/results/%s_0.8_%s.obj'%(homedir,network,'infomap')))
network_objects.append(load_object('/%s/diverse_club/results/%s_0.8_%s.obj'%(homedir,network,'walktrap_n')))
if network == 'f_c_elegans': iters = ['Worm1','Worm2','Worm3','Worm4']
if network == 'human': iters = tasks
if network == 'structural_networks': iters = ['c elegans','macaque','flight traffic','US power grid']
sns.set_style('dark')
sns.set(font='Helvetica',rc={'axes.facecolor':'.5','axes.grid': False})
nconditions = len(iters)
if network == 'f_c_elegans': nconditions = nconditions + 1
fig,subplots = sns.plt.subplots(int(np.ceil(nconditions/2.)),2,figsize=(mm_2_inches(183),mm_2_inches(61.75*np.ceil(nconditions/2.))))
subplots = subplots.reshape(-1)
for idx,name in enumerate(iters):
bw = 'scott'
if name =='US power grid': bw = 1
if name == 'flight traffic': bw = 5
if network != 'structural_networks':
degrees = []
for nidx,nn in enumerate(network_objects[0].networks):
if network_objects[0].names[nidx].split('_')[0] != '%s'%(name) and network_objects[0].names[nidx].split('_')[0] != '%s'%(name.lower()):
continue
degrees.append(nn.community.graph.strength(weights='weight'))
degrees = np.array(degrees)
colors = sns.light_palette("red",degrees.shape[0],reverse=True)
sns.plt.sca(subplots[idx])
means = []
for i in range(degrees.shape[0]):
f = sns.kdeplot(degrees[i],color=colors[i],bw=bw,**{'alpha':.5})
means.append(f.lines[0].get_data()[1])
mean = np.nanmean(means,axis=0)
m = sns.tsplot(mean,color='black',ax=subplots[idx].twiny(),**{'alpha':.5})
m.set_yticklabels('')
m.set_xticklabels('')
for nidx,nn in enumerate(network_objects[1].networks):
if network_objects[1].names[nidx].split('_')[0] != '%s'%(name) and network_objects[1].names[nidx].split('_')[0] != '%s'%(name.lower()):
continue
degree = nn.community.graph.strength(weights='weight')
if network != 'structural_networks':
d = sns.kdeplot(np.array(degree),ax=subplots[idx].twiny(),color='purple',bw=bw,**{'alpha':.5})
d.set_yticklabels('')
d.set_xticklabels('')
if network == 'structural_networks':
d = sns.kdeplot(np.array(degree),ax=subplots[idx],color='red',bw=bw,label='degree',**{'alpha':.5})
d.legend()
d.set_yticklabels('')
d.set_title(name.lower())
if network != 'structural_networks':
patches = []
for color,name in zip(colors,np.arange(5,21)*0.01):
patches.append(mpl.patches.Patch(color=color,label=name,alpha=.75))
patches.append(mpl.patches.Patch(color='black',label='mean, thresholded'))
patches.append(mpl.patches.Patch(color='purple',label='dense'))
ax = subplots[-1]
ax.legend(handles=patches,ncol=2,loc=10)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.set_axis_bgcolor("white")
ax.spines['left'].set_color('white')
ax.spines['bottom'].set_color('white')
ax.set_axis_bgcolor('white')
sns.despine()
if network != 'human':
ax = subplots[-2]
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.spines['left'].set_color('white')
ax.spines['bottom'].set_color('white')
ax.set_axis_bgcolor("white")
sns.despine()
ax.set_axis_bgcolor('white')
savestr = '/%s/diverse_club/figures/%s_degree.pdf'%(homedir,network)
sns.plt.tight_layout()
sns.plt.savefig(savestr)
# sns.plt.show()
sns.plt.close()
def plot_pc_distribution(network,network_objects=None):
bw = 0.05
# if network_objects == None:
# network_objects = []
# for community_alg in algorithms: network_objects.append(load_object('/%s/diverse_club/graphs/graph_objects/%s_0.8_%s.obj'%(homedir,network,community_alg)))
if network == 'f_c_elegans': iters = ['Worm1','Worm2','Worm3','Worm4']
if network == 'human': iters = tasks
if network == 'structural_networks': iters = ['macaque', 'c elegans', 'US power grid', 'flight traffic']
algs = algorithms
sns.set_style('dark')
sns.set(font='Helvetica',rc={'axes.facecolor':'.5','axes.grid': False})
nconditions = 10
for name_idx in iters:
fig,subplots = sns.plt.subplots(5,2,figsize=(mm_2_inches(183),mm_2_inches(61.75*np.ceil(nconditions/2.))))
subplots = subplots.reshape(-1)
plt.text(1.05, 1.13, name_idx.lower() + ' participation coefficient distributions', transform = subplots[0].transAxes, horizontalalignment='center', fontsize=12,)
for idx,n in enumerate(algorithms):
print n
n = load_object('/%s/diverse_club/graphs/graph_objects/%s_0.8_%s.obj'%(homedir,network,n))
pcs = []
for nidx,nn in enumerate(n.networks):
if n.names[nidx].split('_')[0] != '%s'%(name_idx) and n.names[nidx].split('_')[0] != '%s'%(name_idx.lower()):
continue
pcs.append(nn.pc)
pcs = np.array(pcs)
if algs[idx] == 'walktrap_n':
pcs = np.flip(pcs,axis=0)
n_community_sizes = []
for nidx,nn in enumerate(n.networks):
if n.names[nidx].split('_')[0] != '%s'%(name_idx) and n.names[nidx].split('_')[0] != '%s'%(name_idx.lower()):
continue
n_community_sizes.append(len(nn.community.sizes()))
if algs[idx] == 'louvain_res':
l_community_sizes = []
for nidx,nn in enumerate(n.networks):
if n.names[nidx].split('_')[0] != '%s'%(name_idx) and n.names[nidx].split('_')[0] != '%s'%(name_idx.lower()):
continue
l_community_sizes.append(len(nn.community.sizes()))
l_community_sizes.append(l_community_sizes[-1])
colors = sns.light_palette("red",pcs.shape[0],reverse=True)
sns.plt.sca(subplots[idx])
means = []
for i in range(pcs.shape[0]):
f = sns.kdeplot(pcs[i],color=colors[i],bw=bw,**{'alpha':.5})
means.append(f.lines[0].get_data()[1])
mean = np.nanmean(means,axis=0)
m = sns.tsplot(mean,color='black',ax=subplots[idx].twiny(),**{'alpha':.5})
m.set_yticklabels('')
m.set_xticklabels('')
f.set_title(algorithm_names[idx])
f.set_yticklabels('')
f.set_xticklabels(['',0,0.2,.4,.6,.8,''])
patches = []
if network != 'structural_networks':
colors = sns.light_palette("red",16,reverse=True)
for color,name,ls,ns, in zip(colors,np.arange(5,21)*0.01,l_community_sizes,np.flip(n_community_sizes,0)):
name = str(name) + ', ' + str(ls) + ', ' + str(ns)
patches.append(mpl.patches.Patch(color=color,label=name,alpha=.85))
else:
colors = sns.light_palette("red",16,reverse=True)
for color,name,ls,ns, in zip(colors,np.arange(0,16),l_community_sizes,np.flip(n_community_sizes,0)):
name = str(name) + ', ' + str(ls) + ', ' + str(ns)
patches.append(mpl.patches.Patch(color=color,label=name,alpha=.85))
patches.append(mpl.patches.Patch(color='black',label='mean'))
savestr = '/%s/diverse_club/figures/%s_dist_%s.pdf'%(homedir,'pc','%s_%s'%(network,name_idx))
ax = subplots[-1]
if network != 'structural_networks': ax.legend(handles=patches,ncol=2,loc=10,title='graph density,\n$\it{n}$ communities walktrap (n),\n$\it{n}$ communities louvain (resolution)')
else:ax.legend(handles=patches,ncol=2,loc=10,title='run,\n$\it{n}$ communities walktrap (n),\n$\it{n}$ communities louvain (resolution)')
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.set_axis_bgcolor("white")
ax.spines['left'].set_color('white')
ax.spines['bottom'].set_color('white')
ax.set_axis_bgcolor('white')
sns.despine()
sns.plt.tight_layout()
sns.plt.savefig(savestr)
sns.plt.close()
def club_intersect(vc,rankcut):
pc = vc.pc
assert np.isnan(pc).any() == False
mem = np.array(vc.community.membership)
deg = vc.community.graph.strength(weights='weight')
assert np.isnan(deg).any() == False
deg = np.argsort(deg)[rankcut:]
pc = np.argsort(pc)[rankcut:]
try:
overlap = float(len(np.intersect1d(pc,deg)))/len(deg)
except:
overlap = 0
return [overlap,len(np.unique(mem[pc]))/float(len(np.unique(mem))),len(np.unique(mem[deg]))/float(len(np.unique(mem)))]
def igraph_2_networkx(graph):
nxg = nx.Graph()
for edge,weight in zip(graph.get_edgelist(),graph.es['weight']):
nxg.add_edge(edge[0],edge[1],{'weight':weight})
return nxg
def clubness(variables):
network = variables[0]
name = variables[1]
community_alg = variables[2]
niters = variables[3]
randomize_topology = variables[4]
permute_strength = variables[5]
graph = network.community.graph
pc = np.array(network.pc)
assert np.min(graph.strength(weights='weight')) > 0
assert np.isnan(pc).any() == False
pc_emperical_phis = RC(graph, scores=pc).phis()
pc_randomized_phis = np.zeros((niters,graph.vcount()))
for i in range(niters):
pc_randomized_phis[i] = np.array(RC(preserve_strength(graph,randomize_topology=randomize_topology,permute_strength=permute_strength),scores=pc).phis())
pc_average_randomized_phis = np.nanmean(pc_randomized_phis,axis=0)
pc_normalized_phis = pc_emperical_phis/ pc_average_randomized_phis.astype(float)
pc_normalized_phis_std = pc_normalized_phis / np.std(pc_randomized_phis,axis=0).astype(float)
degree_emperical_phis = RC(graph, scores=graph.strength(weights='weight')).phis()
degree_randomized_phis = np.zeros((niters,graph.vcount()))
for i in range(niters):
degree_randomized_phis[i] = np.array(RC(preserve_strength(graph,randomize_topology=randomize_topology,permute_strength=permute_strength),scores=graph.strength(weights='weight')).phis())
degree_average_randomized_phis = np.nanmean(degree_randomized_phis,axis=0)
degree_normalized_phis = degree_emperical_phis / degree_average_randomized_phis.astype(float)
degree_normalized_phis_std = degree_normalized_phis / np.std(degree_randomized_phis,axis=0).astype(float)
return np.array(pc_normalized_phis),np.array(degree_normalized_phis),np.array(pc_normalized_phis_std),np.array(degree_normalized_phis_std)
def plot_clubness_by_club_value(network,network_objects=None):
sns.set(context="paper",font='Helvetica',style='white')
colors = np.zeros((9,3))
colors[np.ix_([0,1])] = sns.cubehelix_palette(8)[-3],sns.cubehelix_palette(8)[3]
colors[np.ix_([2,3,4,5,6,7,8])] = np.array(sns.color_palette("cubehelix", 18))[-7:]
if network == 'human':
condition_name = 'task'
percent_cutoff = .95
if network == 'structural_networks':
condition_name = 'network'
percent_cutoff = .95
if network == 'f_c_elegans':
condition_name = 'worm'
percent_cutoff = .95
if network == 'f_c_elegans' or network == 'structural_networks':
fig,subplots = sns.plt.subplots(9,4,figsize=(mm_2_inches(183),mm_2_inches(247)))
if network == 'human':
fig,subplots = sns.plt.subplots(9,7,figsize=(mm_2_inches(183),mm_2_inches(247)))
subplots = subplots.reshape(-1)
sidx = 0
for alg_idx,algorithm in enumerate(algorithms):
try: df = network_objects[alg_idx].clubness
except: df = load_object('/%s/diverse_club/results/%s_0.8_%s.obj'%(homedir,network,algorithm)).clubness
nconditions = len(np.unique(df[condition_name]))
df[condition_name] = df[condition_name].str.lower()
df['percentile'] = np.nan
if algorithm == 'walktrap_n': run_names = 'n_clusters'
elif algorithm == 'louvain_res': run_names = 'resolution'
else: run_names = 'cost'
for c in np.unique(df[condition_name]):
for n in np.unique(df[run_names]):
df.percentile[(df[condition_name] == c) &(df[run_names] ==n)] = df[(df[condition_name] == c) &(df[run_names] ==n)]['rank'].rank(pct=True)
# df.percentile[(df[condition_name] == c)] = df[(df[condition_name] == c)]['rank'].rank(pct=True)
df = df[df.permute_strength==False]
df = df[df.randomize_topology==True]
for diffnetwork in np.unique(df[condition_name]):
temp_df = df[(df[condition_name]==diffnetwork)].copy()
temp_df = temp_df[temp_df.percentile<percent_cutoff]
# if algorithm == 'walktrap_n':
# if diffnetwork != 'air traffic':
# if diffnetwork !='us power grid':
# temp_df = temp_df[temp_df.percentile<percent_cutoff]
# else: temp_df = temp_df[temp_df.percentile<percent_cutoff]
dcorr = str(np.array(scipy.stats.spearmanr(temp_df.clubness[temp_df.club=='diverse'],temp_df.club_value[temp_df.club=='diverse']))[0])[1:4]
rcorr = str(np.array(scipy.stats.spearmanr(temp_df.clubness[temp_df.club=='rich'],temp_df.club_value[temp_df.club=='rich']))[0])[1:4]
subplots[sidx].scatter(temp_df.clubness[temp_df.club=='diverse'],temp_df.club_value[temp_df.club=='diverse'],color=sns.color_palette()[0],alpha=.5)
subplots[sidx].get_yaxis().set_visible(False)
subplots[sidx].get_xaxis().set_visible(False)
twin = subplots[sidx].twinx()
twin.scatter(temp_df.clubness[temp_df.club=='rich'],temp_df.club_value[temp_df.club=='rich'],color=sns.color_palette()[1],alpha=.5)
patches = []
patches.append(mpl.patches.Patch(color=sns.color_palette()[0],label='r=%s'%(dcorr)))
patches.append(mpl.patches.Patch(color=sns.color_palette()[1],label='r=%s'%(rcorr)))
if float(sidx)/float(nconditions) == int(sidx/nconditions):
l = algorithm_names[np.where(algorithms==algorithm)[0][0]].replace(' ','\n')
subplots[sidx].set_ylabel(l)
subplots[sidx].set_yticklabels('')
subplots[sidx].get_yaxis().set_visible(True)
leg = twin.legend(handles=patches,loc=4,fontsize='xx-small',markerscale=.2,handlelength=0)
for legend_idx,text in enumerate(leg.get_texts()):
sns.plt.setp(text, color = sns.color_palette()[legend_idx])
for item in leg.legendHandles:
item.set_visible(False)
if sidx < nconditions:
subplots[sidx].set_title(np.unique(df[condition_name])[sidx])
subplots[sidx].get_xaxis().set_visible(False)
twin.get_yaxis().set_visible(False)
twin.get_xaxis().set_visible(False)
for spine in subplots[sidx].spines.values():
spine.set_edgecolor(colors[np.where(algorithms==algorithm)[0][0]])
for spine in twin.spines.values():
spine.set_edgecolor(colors[np.where(algorithms==algorithm)[0][0]])
sidx += 1
fig.text(0.0, 0.5, 'participation coefficient and strength for cutoff of club', va='center', rotation='vertical')
fig.text(.5, 0.00, 'clubness', va='bottom', rotation='horizontal')
sns.plt.tight_layout()
sns.plt.savefig('/%s/diverse_club/figures/values_by_clubness_%s.pdf'%(homedir,network))
sns.plt.show()
sns.plt.close()
class Network:
def __init__(self,networks,rankcut,names,subsets,community_alg):
"""
networks: the networks you want to analyze
rankcut: cutoff for the clubs, in percentile form.
names: the names for the different networks,
seperated by _ for different versions of same network
subsets: if different version of same network, names for the columns
e.g., names = ['WM_0.05','WM_0.1'], subsets = ['task','cost']
community_alg: algorithm used to partition the networks
"""
vcounts = []
for network in networks:
check_network(network)
vcounts.append(network.community.graph.vcount())
self.vcounts = np.array(vcounts)
self.networks = np.array(networks)
self.names = np.array(names)
self.subsets = np.array(subsets)
rankcuts = np.zeros((len(self.networks)))
for idx,network in enumerate(self.networks):
rankcuts[idx] = int(network.community.graph.vcount()*rankcut)
self.ranks = rankcuts.astype(int)
self.community_alg = community_alg
def calculate_clubness(self,niters,randomize_topology,permute_strength):
variables = []
pool = Pool(cores)
for idx, network in enumerate(self.networks):
variables.append([network,self.names[idx],self.community_alg,niters,randomize_topology,permute_strength])
results = pool.map(clubness,variables)
for idx, result in enumerate(results):
diverse_clubness,rich_clubness,diverse_clubness_std,rich_clubness_std = result[0],result[1],result[2],result[3]
temp_df = pd.DataFrame()
temp_df["rank"] = np.arange((self.vcounts[idx]))
temp_df['club_value'] = self.networks[idx].pc[np.argsort(self.networks[idx].pc)]
temp_df['clubness'] = diverse_clubness
temp_df['club'] = 'diverse'
temp_df['clubness_std'] = diverse_clubness_std
temp_df['randomize_topology'] = randomize_topology
temp_df['permute_strength'] = permute_strength
for cidx,c in enumerate(self.subsets):
temp_df[c] = self.names[idx].split('_')[cidx]
if idx == 0: df = temp_df.copy()
else: df = df.append(temp_df)
temp_df = pd.DataFrame()
temp_df["rank"] = np.arange((self.vcounts[idx]))
temp_df['club_value'] = np.array(self.networks[idx].community.graph.strength(weights='weight'))[np.argsort(self.networks[idx].community.graph.strength(weights='weight'))]
temp_df['clubness'] = rich_clubness
temp_df['club'] = 'rich'
temp_df['clubness_std'] = rich_clubness_std
temp_df['randomize_topology'] = randomize_topology
temp_df['permute_strength'] = permute_strength
for cidx,c in enumerate(self.subsets):
temp_df[c] = self.names[idx].split('_')[cidx]
df = df.append(temp_df)
df.clubness.loc[df.clubness==np.inf] = np.nan
if hasattr(self,'clubness'): self.clubness = self.clubness.append(df.copy())
else: self.clubness = df.copy()
def calculate_intersect(self):
for idx,network in enumerate(self.networks):
intersect_results = club_intersect(network,self.ranks[idx])
temp_df = pd.DataFrame(index=np.arange(1))
temp_df["percent overlap"] = intersect_results[0]
temp_df['percent community, diverse club'] = intersect_results[1]
temp_df['percent community, rich club'] = intersect_results[2]
temp_df['condition'] = self.names[idx].split("_")[0]
if idx == 0:
df = temp_df.copy()
continue
df = df.append(temp_df)
df["percent overlap"] = df["percent overlap"].astype(float)
df['percent community, diverse club'] = df['percent community, diverse club'].astype(float)
df['percent community, rich club'] = df['percent community, rich club'].astype(float)
self.intersect = df.copy()
def calculate_betweenness(self):
for idx,network in enumerate(self.networks):
degree = np.array(network.community.graph.strength(weights='weight'))
pc = network.pc
assert np.isnan(pc).any() == False
assert np.isnan(degree).any() == False
b = np.array(network.community.graph.betweenness())
temp_df = pd.DataFrame()
temp_df["betweenness"] = b[np.argsort(pc)[self.ranks[idx]:]]
temp_df['club'] = 'diverse'
temp_df['condition'] = self.names[idx].split("_")[0]
if idx == 0: df = temp_df.copy()
else: df = df.append(temp_df)
temp_df = pd.DataFrame()
temp_df["betweenness"] = b[np.argsort(degree)[self.ranks[idx]:]]
temp_df['club'] = 'rich'
temp_df['condition'] = self.names[idx].split("_")[0]
df = df.append(temp_df)
df.betweenness = df.betweenness.astype(float)
self.betweenness = df.copy()
def calculate_edge_betweenness(self):
for idx,network in enumerate(self.networks):
degree = np.array(network.community.graph.strength(weights='weight'))
pc = network.pc
assert np.isnan(pc).any() == False
assert np.isnan(degree).any() == False
pc_matrix = np.zeros((self.vcounts[idx],self.vcounts[idx]))
degree_matrix = np.zeros((self.vcounts[idx],self.vcounts[idx]))
between = network.community.graph.edge_betweenness()
edge_matrix = np.zeros((self.vcounts[idx],self.vcounts[idx]))
diverse_club = np.arange(self.vcounts[idx])[np.argsort(pc)[self.ranks[idx]:]]
rich_club = np.arange(self.vcounts[idx])[np.argsort(degree)[self.ranks[idx]:]]
for eidx,edge in enumerate(network.community.graph.get_edgelist()):
edge_matrix[edge[0],edge[1]] = between[eidx]
edge_matrix[edge[1],edge[0]] = between[eidx]
if edge[0] in diverse_club:
if edge[1] in diverse_club:
pc_matrix[edge[0],edge[1]] = 1
pc_matrix[edge[1],edge[0]] = 1
if edge[0] in rich_club:
if edge[1] in rich_club:
degree_matrix[edge[0],edge[1]] = 1
degree_matrix[edge[1],edge[0]] = 1
temp_df = pd.DataFrame()
temp_df["edge_betweenness"] = edge_matrix[pc_matrix>0]