Пример #1
0
 def test_eigenvector_centrality_weighted(self):
     G = self.G
     alpha = self.G.alpha
     p = networkx.katz_centrality_numpy(G, alpha)
     print p.values()
     for (a, b) in zip(list(p.values()), self.G.evc):
         assert_almost_equal(a, b)
Пример #2
0
 def test_eigenvector_v_katz_random(self):
     G = nx.gnp_random_graph(10,0.5, seed=1234)
     l = float(max(eigvals(nx.adjacency_matrix(G).todense())))
     e = nx.eigenvector_centrality_numpy(G)
     k = nx.katz_centrality_numpy(G, 1.0/l)
     for n in G:
         assert_almost_equal(e[n], k[n])
Пример #3
0
def create_centralities_list(G,maxiter=2000,pphi=5,centList=[]):
    if len(centList)==0:
        centList=['degree_centrality','closeness_centrality','betweenness_centrality',
    'eigenvector_centrality','katz_centrality','page_rank']
    cenLen=len(centList)
    valus={}
    # plt.figure(figsize=figsi)
    for uu,centr in enumerate(centList):
        if centr=='degree_centrality':
            cent=nx.degree_centrality(G)
            sstt='Degree Centralities'
            ssttt='degree centrality'
            valus[centr]=cent
        elif centr=='closeness_centrality':
            cent=nx.closeness_centrality(G)
            sstt='Closeness Centralities'
            ssttt='closeness centrality'
            valus[centr]=cent

        elif centr=='betweenness_centrality':
            cent=nx.betweenness_centrality(G)
            sstt='Betweenness Centralities'
            ssttt='betweenness centrality'
            valus[centr]=cent

        elif centr=='eigenvector_centrality':
            try:
                cent=nx.eigenvector_centrality(G,max_iter=maxiter)
                sstt='Eigenvector Centralities'
                ssttt='eigenvector centrality'
                valus[centr]=cent

            except:
                valus[centr]=None

                continue
        elif centr=='katz_centrality':
            phi = (1+math.sqrt(pphi))/2.0 # largest eigenvalue of adj matrix
            cent=nx.katz_centrality_numpy(G,1/phi-0.01)
            sstt='Katz Centralities'
            ssttt='Katz centrality'
            valus[centr]=cent

        elif centr=='page_rank':
            try:
                cent=nx.pagerank(G)
                sstt='PageRank'
                ssttt='pagerank'
                valus[centr]=cent

            except:
                valus[centr]=None

                continue
        print '%s done!!!' %sstt

    return valus
Пример #4
0
 def test_beta_as_dict(self):
     alpha = 0.1
     beta = {0: 1.0, 1: 1.0, 2: 1.0}
     b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449,
                 2: 0.5598852584152162}
     G = nx.path_graph(3)
     b = nx.katz_centrality_numpy(G, alpha, beta)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n], places=4)
Пример #5
0
 def test_P3_unweighted(self):
     """Katz centrality: P3"""
     alpha = 0.1
     G = nx.path_graph(3)
     b_answer = {0: 0.5598852584152165, 1: 0.6107839182711449,
                 2: 0.5598852584152162}
     b = nx.katz_centrality_numpy(G, alpha, weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n], places=4)
Пример #6
0
def draw_centralities(G,centr,pos,with_edgewidth=False,withLabels=True,pernode_dict={},title_st='', labfs=10,valpha=0.4,ealpha=0.4):

    plt.figure(figsize=(12,12))
    if centr=='degree_centrality':
        cent=nx.degree_centrality(G)
        sstt='Degree Centralities'
        ssttt='degree centrality'
    elif centr=='closeness_centrality':
        cent=nx.closeness_centrality(G)
        sstt='Closeness Centralities'
        ssttt='closeness centrality'
    elif centr=='betweenness_centrality':
        cent=nx.betweenness_centrality(G)
        sstt='Betweenness Centralities'
        ssttt='betweenness centrality'
    elif centr=='eigenvector_centrality':
        cent=nx.eigenvector_centrality(G,max_iter=1000)
        sstt='Eigenvector Centralities'
        ssttt='eigenvector centrality'
    elif centr=='katz_centrality':
        phi = (1+math.sqrt(5))/2.0 # largest eigenvalue of adj matrix
        cent=nx.katz_centrality_numpy(G,1/phi-0.01)
        sstt='Katz Centralities'
        ssttt='Katz centrality'
    elif centr=='page_rank':
        cent=nx.pagerank(G)
        sstt='PageRank'
        ssttt='pagerank'
    cs={}
    for k,v in cent.items():
        if v not in cs:
            cs[v]=[k]
        else:
            cs[v].append(k)
    for k in sorted(cs,reverse=True):
        for v in cs[k]:
            print 'Node %s has %s = %.4f' %(v,ssttt,k)

    if withLabels:
        if len(pernode_dict)>1:
            labels={i:v for v,i in pernode_dict.items() if i in G.nodes()}
            labe=nx.draw_networkx_labels(G,pos=pos,labels=labels,font_size=20)
        else:
            labe=nx.draw_networkx_labels(G,pos=pos,font_size=labfs)
    nx.draw_networkx_nodes(G,pos=pos,nodelist=cent.keys(), #with_labels=withLabels,
                           node_size = [d*4000 for d in cent.values()],node_color=cent.values(),
                           cmap=plt.cm.Reds,alpha=valpha)
    if with_edgewidth:
        edgewidth=[]
        for (u,v,d) in G.edges(data=True):
            edgewidth.append(d['weight'])
    else:
        edgewidth=[1 for i in G.edges()]
    nx.draw_networkx_edges(G,pos=pos,edge_color='b',width=edgewidth, alpha=ealpha)
    plt.title(title_st+' '+ sstt,fontsize=20)
    kk=plt.axis('off')
Пример #7
0
def centrailtyM(A,num=5):
    G=nx.DiGraph(A)
    ranks=np.zeros((num,8))
    ranks[:,0]=np.argsort(nx.in_degree_centrality(G).values())[::-1][:num]
    ranks[:,1]=np.argsort(nx.closeness_centrality(G).values())[::-1][:num]
    ranks[:,2]=np.argsort(nx.betweenness_centrality(G).values())[::-1][:num]
    ranks[:,3]=np.argsort(nx.eigenvector_centrality_numpy(G).values())[::-1][:num]
    ranks[:,4]=np.argsort(nx.katz_centrality_numpy(G,weight=None).values())[::-1][:num]
    ranks[:,5]=np.argsort(nx.pagerank_numpy(G,weight=None).values())[::-1][:num]
    return ranks
def displayCentralities():
	print("---------------------------")
	print("Degree centrality (the number of links incident upon a node) => LIKELIHOOD TO CATCH AN INFORMATION")
	print(sorted(list(nx.degree_centrality(G).items()),key=operator.itemgetter(1),reverse=True))
	print("---------------------------")
	print("---------------------------")
	print("Betweenness centrality (quantifies the number of times a node acts as a bridge along the shortest path between two other nodes) => CONTROL ON OTHERS")
	print(sorted(list(nx.betweenness_centrality(G).items()),key=operator.itemgetter(1),reverse=True))
	print("---------------------------")
	print("---------------------------")
	print("Eigenvector centrality (a measure of the influence of a node in a network)")
	print(sorted(list(nx.eigenvector_centrality(G).items()),key=operator.itemgetter(1),reverse=True))
	print("---------------------------")
	print("---------------------------")
	print("Katz centrality (relative influence of a node)")
	print(sorted(list(nx.katz_centrality_numpy(G).items()),key=operator.itemgetter(1),reverse=True))
	print("---------------------------")
Пример #9
0
 def test_multiple_alpha(self):
     alpha_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
     for alpha in alpha_list:
         b_answer = {0.1: {0: 0.5598852584152165, 1: 0.6107839182711449,
                           2: 0.5598852584152162},
                     0.2: {0: 0.5454545454545454, 1: 0.6363636363636365,
                           2: 0.5454545454545454},
                     0.3: {0: 0.5333964609104419, 1: 0.6564879518897746,
                           2: 0.5333964609104419},
                     0.4: {0: 0.5232045649263551, 1: 0.6726915834767423,
                           2: 0.5232045649263551},
                     0.5: {0: 0.5144957746691622, 1: 0.6859943117075809,
                           2: 0.5144957746691622},
                     0.6: {0: 0.5069794004195823, 1: 0.6970966755769258,
                           2: 0.5069794004195823}}
         G = nx.path_graph(3)
         b = nx.katz_centrality_numpy(G, alpha)
         for n in sorted(G):
             assert_almost_equal(b[n], b_answer[alpha][n], places=4)
Пример #10
0
 def test_empty_numpy(self):
     e = networkx.katz_centrality_numpy(networkx.Graph(), 0.1)
Пример #11
0
 def test_katz_centrality_unweighted(self):
     G = self.H
     alpha = self.H.alpha
     p = nx.katz_centrality_numpy(G, alpha)
     for (a, b) in zip(list(p.values()), self.G.evc):
         assert_almost_equal(a, b)
def calculate_katz(g):
    return nx.katz_centrality_numpy(g)
Пример #13
0
 def test_bad_beta_numbe(self):
     G = nx.Graph([(0,1)])
     e = nx.katz_centrality_numpy(G, 0.1,beta='foo')
Пример #14
0
 def test_bad_beta(self):
     G = nx.Graph([(0,1)])
     beta = {0:77}
     e = nx.katz_centrality_numpy(G, 0.1,beta=beta)
Пример #15
0
import matplotlib.pyplot as plt
import pygraphviz
import math

edges = pd.read_csv('fulllist.csv', encoding = 'utf-8')

#edges[(edges.name_x == 'Zadie Smith') | (edges.name_y == 'Zadie Smith')]
H = nx.DiGraph()
#phil = edges[(edges.phil_x == 1) & (edges.phil_y == 1)]
#phil = phil.dropna(subset = ['name_x', 'name_y'])
#H.add_edges_from(numpy.array(phil[['name_x', 'name_y']]))
edges = edges.dropna(subset = ['name_x', 'name_y'])
H.add_edges_from(numpy.array(edges[['name_x', 'name_y']]))

d = nx.degree(H)
k = nx.katz_centrality_numpy(H.reverse(), alpha = 0.075, beta = 1)
#b = nx.betweenness_centrality(H)
s = pd.Series(k, name = 'kc_score')
s.index.name = 'name'
s.reset_index()
s.sort('kc_score', ascending=False)
print (s[0:60])


#nx.ancestors(H, 'Plato')
#plt.figure(figsize = (50,50))
#try:
#pos=nx.graphviz_layout(H, prog='dot')
#except:
#        pos=nx.spring_layout(H,iterations=20)
#pos = nx.spring_layout(H,iterations=20)
Пример #16
0
def create_centralities_list(G,maxiter=2000,pphi=5,centList=[]):
    if len(centList)==0:
        centList=['degree_centrality','closeness_centrality','betweenness_centrality',
    'eigenvector_centrality','katz_centrality','page_rank']
    cenLen=len(centList)
    valus={}
    # plt.figure(figsize=figsi)
    for uu,centr in enumerate(centList):
        if centr=='degree_centrality':
            cent=nx.degree_centrality(G)
            sstt='Degree Centralities'
            ssttt='degree centrality'
            valus[centr]=cent
        elif centr=='closeness_centrality':
            cent=nx.closeness_centrality(G)
            sstt='Closeness Centralities'
            ssttt='closeness centrality'
            valus[centr]=cent

        elif centr=='betweenness_centrality':
            cent=nx.betweenness_centrality(G)
            sstt='Betweenness Centralities'
            ssttt='betweenness centrality'
            valus[centr]=cent

        elif centr=='eigenvector_centrality':
            try:
                cent=nx.eigenvector_centrality(G,max_iter=maxiter)
                sstt='Eigenvector Centralities'
                ssttt='eigenvector centrality'
                valus[centr]=cent

            except:
                valus[centr]=None

                continue
        elif centr=='katz_centrality':
            phi = (1+math.sqrt(pphi))/2.0 # largest eigenvalue of adj matrix
            cent=nx.katz_centrality_numpy(G,1/phi-0.01)
            sstt='Katz Centralities'
            ssttt='Katz centrality'
            valus[centr]=cent

        elif centr=='page_rank':
            try:
                cent=nx.pagerank(G)
                sstt='PageRank'
                ssttt='pagerank'
                valus[centr]=cent

            except:
                valus[centr]=None

                continue
        print '%s done!!!' %sstt

        # cs={}
        # for k,v in cent.items():
        #     if v not in cs:
        #         cs[v]=[k]
        #     else:
        #         cs[v].append(k)
        # nodrank=[]
        # uui=0
        # for k in sorted(cs,reverse=True):
        #     for v in cs[k]:
        #         if uui<5:
        #             nodrank.append(v)
        #             uui+=1
        # nodeclo=[]
        # for k,v in cent.items():
        #     if k in  nodrank :
        #         nodeclo.append(v)
        #     else:
        #         nodeclo.append(0.)
        # plt.subplot(1+cenLen/2.,2,uu+1).set_title(sstt)
        # if withLabels:
        #     labe=nx.draw_networkx_labels(G,pos=pos,font_size=labfs)
        # nx.draw_networkx_nodes(G,pos=pos,nodelist=cent.keys(),
        #                        node_color=nodeclo,
        #                        cmap=plt.cm.Reds,alpha=valpha)
        # nx.draw_networkx_edges(G,pos=pos,edge_color='b', alpha=ealpha)
        # plt.title(sstt,fontsize=20)
        # kk=plt.axis('off')
    # if vals:
    return valus
Пример #17
0
import networkx as nx
import plot_multigraph
import matplotlib.pylab as plt
from matplotlib import pylab as plt

n = 80
p = 10. / n
G = nx.fast_gnp_random_graph(n, p, seed=42)

def to_list(dict_):
  return [dict_[k] for k in G.nodes()]

graph_colors = [
  ("degree", to_list(nx.degree_centrality(G))),
  ("betweenness", to_list(nx.betweenness_centrality(G))),
  ("load", to_list(nx.load_centrality(G))),
  ("eigenvector", to_list(nx.eigenvector_centrality_numpy(G))),
  ("closeness_centrality", to_list(nx.closeness_centrality(G))),
  ("current_flow_closeness", to_list(nx.current_flow_closeness_centrality(G))),
  ("current_flow_betweenness", to_list(nx.current_flow_betweenness_centrality(G))),
  ("katz", to_list(nx.katz_centrality_numpy(G))),
  ("communicability", to_list(nx.communicability_centrality(G))),
]

fig = plot_multigraph.plot_color_multigraph(G, graph_colors, 3, 3, node_size=50)
plt.savefig('graphs/centrality.png', facecolor=fig.get_facecolor())
Пример #18
0
def draw_centralities_subplots(G,pos,withLabels=True,labfs=10,valpha=0.4,ealpha=0.4,figsi=(12,12),vals=False):
    centList=['degree_centrality','closeness_centrality','betweenness_centrality',
    'eigenvector_centrality','katz_centrality','page_rank']
    cenLen=len(centList)
    valus={}
    plt.figure(figsize=figsi)
    for uu,centr in enumerate(centList):
        if centr=='degree_centrality':
            cent=nx.degree_centrality(G)
            sstt='Degree Centralities'
            ssttt='degree centrality'
            valus[centr]=cent
        elif centr=='closeness_centrality':
            cent=nx.closeness_centrality(G)
            sstt='Closeness Centralities'
            ssttt='closeness centrality'
            valus[centr]=cent

        elif centr=='betweenness_centrality':
            cent=nx.betweenness_centrality(G)
            sstt='Betweenness Centralities'
            ssttt='betweenness centrality'
            valus[centr]=cent

        elif centr=='eigenvector_centrality':
            try:
                cent=nx.eigenvector_centrality(G,max_iter=2000)
                sstt='Eigenvector Centralities'
                ssttt='eigenvector centrality'
                valus[centr]=cent

            except:
                valus[centr]=None

                continue
        elif centr=='katz_centrality':
            phi = (1+math.sqrt(5))/2.0 # largest eigenvalue of adj matrix
            cent=nx.katz_centrality_numpy(G,1/phi-0.01)
            sstt='Katz Centralities'
            ssttt='Katz centrality'
            valus[centr]=cent

        elif centr=='page_rank':
            try:
                cent=nx.pagerank(G)
                sstt='PageRank'
                ssttt='pagerank'
                valus[centr]=cent

            except:
                valus[centr]=None

                continue
        cs={}
        for k,v in cent.items():
            if v not in cs:
                cs[v]=[k]
            else:
                cs[v].append(k)
        nodrank=[]
        uui=0
        for k in sorted(cs,reverse=True):
            for v in cs[k]:
                if uui<5:
                    nodrank.append(v)
                    uui+=1
        nodeclo=[]
        for k,v in cent.items():
            if k in  nodrank :
                nodeclo.append(v)
            else:
                nodeclo.append(0.)
        plt.subplot(1+cenLen/2.,2,uu+1).set_title(sstt)
        if withLabels:
            labe=nx.draw_networkx_labels(G,pos=pos,font_size=labfs)
        nx.draw_networkx_nodes(G,pos=pos,nodelist=cent.keys(),
                               node_color=nodeclo,
                               cmap=plt.cm.Reds,alpha=valpha)
        nx.draw_networkx_edges(G,pos=pos,edge_color='b', alpha=ealpha)
        plt.title(sstt,fontsize=20)
        kk=plt.axis('off')
    if vals:
        return valus
Пример #19
0
 def test_multigraph_numpy(self):
     e = networkx.katz_centrality_numpy(networkx.MultiGraph(), 0.1)
Пример #20
0
print('Page rank',pager )

plt.bar(range(len(pager)), pager.values(), align='center')
plt.xticks(range(len(pager)), pager.keys())
plt.show()

centrality = nx.eigenvector_centrality(G,100000)
print(['%s %0.2f'%(node,centrality[node]) for node in centrality])
#plt.plot(node,centrality[node])

plt.bar(range(len(centrality)), centrality.values(), align='center')
plt.xticks(range(len(centrality)), centrality.keys())
plt.show()

#plt.savefig("./assignment3/eigenvectorcentralityRG.png")
kz=nx.katz_centrality_numpy(G,0.62)
print('Katz centrality', kz)
plt.bar(range(len(kz)), kz.values(), align='center')
plt.xticks(range(len(kz)), kz.keys())
plt.show()

loops = G.selfloop_edges()
# remove parallel edges and self-loops
graph = nx.Graph(G)
graph.remove_edges_from(loops)
# get largest connected component
# unfortunately, the iterator over the components is not guaranteed to be sorted by size
components = sorted(nx.connected_components(graph), key=len, reverse=True)
lcc = graph.subgraph(components[0])
pos=nx.spring_layout(lcc)
d = nx.degree(lcc)
Пример #21
0
def create_tex_sum_central(G,tem_dici,dici_tem,dic_of_nodes_multi,outfile_name='scent_out.tex'):
    print outfile_name
    # print list_ofNod,dic_of_nodes_multi
    fop=open(outfile_name,'w')
    lat=r'''\documentclass[10pt]{article}

\usepackage{lscape}
\usepackage{adjustbox}
\begin{document}
 %\global\pdfpageattr\expandafter{\the\pdfpageattr/Rotate 90}

\begin{table}[ht]
\centering
\begin{adjustbox}{width=1\textwidth,center=\textwidth}
\small
\begin{tabular}{|c||r|r|r|r|r|r|r|r|r||} \hline 
    Node/Centralities & In & Out & Degree  & Closeness  & Betweenness & Eigenvector  & Katz & PageRank & Communicability  \\ 
    \hline \hline'''.decode('utf-8')
    fop.write(lat)
    fop.write('\n')
    degce=nx.degree_centrality(G)
    cloce=cent=nx.closeness_centrality(G)
    becen=nx.betweenness_centrality(G)
    eigce=nx.eigenvector_centrality(G,max_iter=2000)
    katce=nx.katz_centrality_numpy(G)#,1/phi-0.01)
    pagce=nx.pagerank(G)
    # comce=nx.communicability_centrality(G)
    comce=nx.communicability_centrality_exp(G)
    from scipy import stats
    dic_of_nodes_multi_r={ii:i for i,v in dic_of_nodes_multi.items() for ii in v}
    # print stats.pearsonr(degce.values(),dici_tem.values())
    # lats=r'|'
    cent_dics={}
    latl=r'   '
    for i in dici_tem:
        latl+='%i & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f ' %(i, dici_tem[i]/15.,
            tem_dici[i]/15.,degce[i],cloce[i],becen[i],eigce[i],katce[i],pagce[i],comce[i])+r'''\\  \hline
'''.decode('utf-8')
        cent_dics[i]=(i, dici_tem[i]/15.,
            tem_dici[i]/15.,degce[i],cloce[i],becen[i],eigce[i],katce[i],pagce[i],comce[i],dic_of_nodes_multi_r[i])
    fop.write(latl)
    fop.write('In & %.6f  &   & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f ' %(sum(dici_tem.values()), stats.pearsonr(degce.values(),dici_tem.values())[0]
        ,stats.pearsonr(cloce.values(),dici_tem.values())[0],stats.pearsonr(becen.values(),dici_tem.values())[0],
        stats.pearsonr(eigce.values(),dici_tem.values())[0],stats.pearsonr(katce.values(),dici_tem.values())[0],
        stats.pearsonr(pagce.values(),dici_tem.values())[0],stats.pearsonr(comce.values(),dici_tem.values())[0]) +r'''\\  \hline
'''.decode('utf-8'))
    fop.write('Out &   &  %.6f  & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f & %.6f ' %(sum(tem_dici.values()), stats.pearsonr(degce.values(),tem_dici.values())[0]
        ,stats.pearsonr(cloce.values(),tem_dici.values())[0],stats.pearsonr(becen.values(),tem_dici.values())[0],
        stats.pearsonr(eigce.values(),tem_dici.values())[0],stats.pearsonr(katce.values(),tem_dici.values())[0],
        stats.pearsonr(pagce.values(),tem_dici.values())[0],stats.pearsonr(comce.values(),tem_dici.values())[0]) +r'''\\  \hline
'''.decode('utf-8'))


    # # print steady_dict
    # # print len()
    # for i in list_ofNod:
    #     if i =='Node/Node':# or kk==0:
    #         continue

    #     for kk,j in enumerate(list_ofNod[1:]):

    #         # print steady_dict[i],j,kk
    #     # for j in steady_dict[i]:
    #         if j not in dici_tem:

    #             dici_tem[j]=steady_dict[i][kk]
    #         else:
    #             dici_tem[j]+=steady_dict[i][kk]
    # # print dici_tem
    # # print steady_dict
    # # latll=r''
    # for kk,i in enumerate(list_ofNod):
    #     sumout=0
    #     if i =='Node/Node':
    #         continue
    #     else:
    #         # for 
    #         for ii in steady_dict[i]:
    #             sumout+=ii
    #     tem_dici[i]=sumout
    #     latl+='%s & %.6f & %.6f & %.6f & %.6f' %(i,dici_tem[i] ,sumout,dici_tem[i]/len(list_ofNod[1:]),sumout/len(list_ofNod[1:]))
    #         # latll=latll[:-2]
    #     if i ==dic_of_nodes_multi[0][-1]:
    #         latl+='\\\ \n \hline \hline'+'\n'
    #     else:
    #         latl+='\\\ \n \hline '+'\n'
    # fop.write(latl)
    fop.write(r'''\hline 
\end{tabular}
\end{adjustbox}
\end{table}

\end{document}'''.decode('utf-8'))
    fop.close()
    return cent_dics