def computeKnn(graph, knn_file, weight=None):
    G = nx.path_graph(4)
    G.edge[1][2]['weight'] = 3
    print nx.k_nearest_neighbors(G)
    knnfs = codecs.open(knn_file, 'w+', encoding='utf-8')
    knn = nx.average_degree_connectivity(graph)
    print graph, 'knn as follows:'
    print knn
    sumknn = sum(knn.values())
    minknn = min(knn.keys())
    maxknn = max(knn.keys())
    index = maxknn
    currentSum = 0.0
    while index >= minknn:
        if index in knn.keys():
            currentSum = knn[index]

        else:
            index -= 1
            continue
        freq = currentSum * 1.0 / sumknn
        knnfs.write(str(index) + ',' + str(freq) + '\r\n')
        print index, freq
        index -= 1
    #for (key, value) in knn.items():
    #    knnfs.write(str(key)+ ',' + str(value) + '\r\n')
    knnfs.flush()
    knnfs.close()
示例#2
0
def computeKnn(graph, knn_file, weight=None):
    G = nx.path_graph(4)
    G.edge[1][2]['weight'] = 3
    print nx.k_nearest_neighbors(G)
    knnfs = codecs.open(knn_file, 'w+', encoding='utf-8')
    knn = nx.average_degree_connectivity(graph)
    print graph, 'knn as follows:'
    print knn
    for (key, value) in knn.items():
        knnfs.write(str(key) + ',' + str(value) + '\r\n')
    knnfs.flush()
    knnfs.close()
示例#3
0
def apply_knn(lcn, hccs, opts):
    num_accounts = lcn.number_of_nodes()
    w_property = opts.weight_property
    k = int(round(math.log(num_accounts)))
    log('Choosing k of %d (%d users)' % (k, num_accounts))
    knns = nx.k_nearest_neighbors(lcn, weight=w_property)
    closest_k = k if k in knns else find_closest_knn(k, knns)
    log('using closest_k: %d' % closest_k)
    knn = knns[closest_k]  #if k in knns else knns[find_closest_knn(k, knns)]
    log('KNN: %s' % knn)

    knn_nodes = [n for n, d in lcn.degree() if d > knn]

    def prep_node_attrs(n):
        return dict([(k, lcn.nodes[k]) for k in lcn.nodes[k]])

    for u in knn_nodes:
        for v in lcn[u]:  # u's neighbours
            if v in knn_nodes:  # v qualifies
                if u not in hccs: hccs.add_node(u, **lcn.nodes[u])
                if v not in hccs: hccs.add_node(v, **lcn.nodes[v])
                if not hccs.has_edge(u, v):
                    hccs.add_edge(u, v, **lcn.edges[u, v])

    return hccs
    def test_sparse_sym(self):
        A = np.array([[0, 1, 1, 0, 1],
                [1, 0, 1, 1, 0],
                [1, 1, 0, 0, 0],
                [0, 1, 0, 0, 1],
                [1, 0, 0, 1, 0]])
        
        A_nx = nx.convert_matrix.from_numpy_array(A)

        # sparse matrix conversion
        A = scipy.sparse.csr_matrix(A)

        rows, cols = A.nonzero()
        print(rows, cols)
        A[cols,rows] = A[rows, cols]


        k = sample.out_degree(A)

        knn_sample = sample.nearest_neighbour_degree_undirected(A)
        # knn_nx = nx.degree_assortativity_coefficient(A_nx)
        knn_nx = nx.k_nearest_neighbors(A_nx)

        # debug check
        """
        print(k)
        print('\n')
        print(knn_sample)
        print(knn_nx)
        """

        self.assertTrue(knn_sample == knn_nx)
def list_degree_average(G):
    davg_dic={}
    num_nodes=nx.number_of_nodes(G)
    degree=nx.k_nearest_neighbors(G, weight='weight')
    for i in range(num_nodes):
        if str(i) in degree.keys():
            davg_dic[i]=degree[str(i)]
    return davg_dic
示例#6
0
def gen_graph_stats (graph):
	G = nx.read_graphml(graph)
	stats = {}

	edges, nodes = 0,0
	for e in G.edges_iter(): edges += 1
	for n in G.nodes_iter(): nodes += 1
	stats['Edges'] = (edges,'The number of edges within the Graph')
	stats['Nodes'] = (nodes, 'The number of nodes within the Graph')
	print "%i edges, %i nodes" % (edges, nodes)


	# Accessing the highest degree node
	center, degree = sorted(G.degree().items(), key=itemgetter(1), reverse=True)[0]
	stats['Center Node'] = ('%s: %0.5f' % (center,degree),'The center most node in the graph. Which has the highest degree')


	hairball = nx.subgraph(G, [x for x in nx.connected_components(G)][0])
	print "Average shortest path: %0.4f" % nx.average_shortest_path_length(hairball)
	stats['Average Shortest Path Length'] = (nx.average_shortest_path_length(hairball), '')
	# print "Center: %s" % G[center]

	# print "Shortest Path to Center: %s" % p


	print "Degree: %0.5f" % degree
	stats['Degree'] = (degree,'The node degree is the number of edges adjacent to that node.')

	print "Order: %i" % G.number_of_nodes()
	stats['Order'] = (G.number_of_nodes(),'The number of nodes in the graph.')

	print "Size: %i" % G.number_of_edges()
	stats['Size'] = (G.number_of_edges(),'The number of edges in the graph.')

	print "Clustering: %0.5f" % nx.average_clustering(G)
	stats['Average Clustering'] = (nx.average_clustering(G),'The average clustering coefficient for the graph.')

	print "Transitivity: %0.5f" % nx.transitivity(G)
	stats['Transitivity'] = (nx.transitivity(G),'The fraction of all possible triangles present in the graph.')

	part = community.best_partition(G)
	# values = [part.get(node) for node in G.nodes()]

	# nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
	# plt.show()

	mod = community.modularity(part,G)
	print "modularity: %0.5f" % mod
	stats['Modularity'] = (mod,'The modularity of a partition of a graph.')

	knn = nx.k_nearest_neighbors(G)
	print knn
	stats['K Nearest Neighbors'] = (knn,'the average degree connectivity of graph.\nThe average degree connectivity is the average nearest neighbor degree of nodes with degree k. For weighted graphs, an analogous measure can be computed using the weighted average neighbors degre')


	return G, stats
示例#7
0
 def test_degree_barrat(self):
     G = nx.star_graph(5)
     G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
     G[0][5]["weight"] = 5
     nd = nx.average_degree_connectivity(G)[5]
     assert nd == 1.8
     nd = nx.average_degree_connectivity(G, weight="weight")[5]
     assert nd == pytest.approx(3.222222, abs=1e-5)
     nd = nx.k_nearest_neighbors(G, weight="weight")[5]
     assert nd == pytest.approx(3.222222, abs=1e-5)
示例#8
0
 def test_degree_barrat(self):
     G=nx.star_graph(5)
     G.add_edges_from([(5,6),(5,7),(5,8),(5,9)])
     G[0][5]['weight']=5
     nd = nx.average_degree_connectivity(G)[5]
     assert_equal(nd,1.8)
     nd = nx.average_degree_connectivity(G,weight='weight')[5]
     assert_almost_equal(nd,3.222222,places=5)
     nd = nx.k_nearest_neighbors(G,weight='weight')[5]
     assert_almost_equal(nd,3.222222,places=5)
示例#9
0
 def test_degree_barrat(self):
     G=nx.star_graph(5)
     G.add_edges_from([(5,6),(5,7),(5,8),(5,9)])
     G[0][5]['weight']=5
     nd = nx.average_degree_connectivity(G)[5]
     assert_equal(nd,1.8)
     nd = nx.average_degree_connectivity(G,weight='weight')[5]
     assert_almost_equal(nd,3.222222,places=5)
     nd = nx.k_nearest_neighbors(G,weight='weight')[5]
     assert_almost_equal(nd,3.222222,places=5)
def analyze_graphs(my_df, report_dict, layer):
    #G=nx.Graph()
    G = nx.from_pandas_edgelist(my_data,
                                'Source_Names',
                                'Destination_Names',
                                edge_attr=None,
                                create_using=None)

    report_dict['knearestscore'].append(nx.k_nearest_neighbors(G))
    report_dict['knearestscore'].append(nx.average_degree_connectivity(G))
    purchase = my_data.loc[my_data['Etype'] == 5]
    report_dict['Source_Names'].append(purchase['Source_Names'].iloc[0])
    report_dict['Destination_Names'].append(
        purchase['Destination_Names'].iloc[0])
    report_dict['full_date'].append(purchase['full_date'].iloc[0])
    report_dict['layer'].append(layer)
    def assortativity(self):
        result = {}
        result['average_degree_connectivity'] = nx.average_degree_connectivity(
            self.graph)
        result['k_nearest_neighbors'] = nx.k_nearest_neighbors(self.graph)

        # k degree distribution
        k_degree = []
        for k in result['average_degree_connectivity'].keys():
            k_degree.append((k, result['average_degree_connectivity'][k],
                             result['k_nearest_neighbors'][k]))

        k_degree.insert(
            0,
            ['degree k', 'average_degree_connectivity', 'k_nearest_neighbors'])

        return k_degree
def graph_stats(G):
    density = nx.density(G)
    try:
        corr = nx.degree_pearson_correlation_coefficient(G)
    except:
        corr = 0
    avg_neighbor_degree = nx.average_neighbor_degree(G)  #dict
    k_nearest_neighbors = nx.k_nearest_neighbors(G)  #dict
    degree_centrality = nx.degree_centrality(G)  #dict
    info = nx.info(G)
    return {
        'density': density,
        'corr': corr,
        'avg_neighbor_degree': avg_neighbor_degree,
        'k_nearest_neighbors': k_nearest_neighbors,
        'degree_centrality': degree_centrality,
        'info': info
    }
示例#13
0
    def assortativity(self):
        result = {}
        result[
            'degree_assortativity_coefficient'] = nx.degree_assortativity_coefficient(
                self.graph)

        if self.directed == 'undirected':
            result[
                'degree_pearson_correlation_coefficient'] = nx.degree_pearson_correlation_coefficient(
                    self.graph)

        result['average_neighbor_degree'] = nx.average_neighbor_degree(
            self.graph)
        result['average_degree_connectivity'] = nx.average_degree_connectivity(
            self.graph)
        result['k_nearest_neighbors'] = nx.k_nearest_neighbors(self.graph)

        fname_assort = self.DIR + '/assortativity.json'
        with open(fname_assort, "w") as f:
            json.dump(result, f, cls=SetEncoder, indent=2)
        print(fname_assort)
    def test_array_inin(self):
        A = np.array([[0, 0, 1, 0, 1],
                [1, 0, 0, 1, 0],
                [1, 1, 0, 0, 0],
                [0, 1, 1, 0, 1],
                [1, 0, 0, 1, 0]])
        
        A_nx = nx.convert_matrix.from_numpy_array(A, create_using=nx.DiGraph())
        k = sample.in_degree(A)

        knn_sample = sample.nearest_neighbour_degree_inin(A)
        # knn_nx = nx.degree_assortativity_coefficient(A_nx)
        knn_nx = nx.k_nearest_neighbors(A_nx, source='in', target='in')

        # debug check
        """
        print(k)
        print('\n')
        print(knn_sample)
        print(knn_nx)
        """

        self.assertTrue(knn_sample == knn_nx)
    def test_array_sym(self):
        A = np.array([[0, 1, 1, 0, 1],
                [1, 0, 1, 1, 0],
                [1, 1, 0, 0, 0],
                [0, 1, 0, 0, 1],
                [1, 0, 0, 1, 0]])
        
        A_nx = nx.convert_matrix.from_numpy_array(A)
        k = sample.out_degree(A)

        knn_sample = sample.nearest_neighbour_degree_undirected(A)
        # knn_nx = nx.degree_assortativity_coefficient(A_nx)
        knn_nx = nx.k_nearest_neighbors(A_nx)

        # debug check
        """
        print(k)
        print('\n')
        print(knn_sample)
        print(knn_nx)
        """

        self.assertTrue(knn_sample == knn_nx)
    edge_list = os.path.join(input_data_folder, edgelist_filename)
    if not os.path.exists(edge_list):
        continue

    new_graph = nx.read_weighted_edgelist(edge_list)
    graph_dict[graph_name] = new_graph


# %%
knn_dict = {}
degree_dict = {}

for graph in graph_dict.keys():
    print(graph)
    knn_dict[graph] = nx.k_nearest_neighbors(graph_dict[graph], weight='weight')
    degree_dict[graph] = {(x):y for (x,y) in graph_dict[graph].degree(weight='weight')}

    


# %%
# split dict to weekend vs weekday
weekday_knn = {}
weekend_knn = {}

for key in knn_dict.keys():
    
    day_type = key.split("_")[1]
    day_hour = int(key.split("_")[-1])
    
示例#17
0
            print('Calculating: clustering (this may take a while)')
            dict_clustering = nx.clustering(Gtc, weight='weight')
            nx.set_node_attributes(Gtc,
                                   name='clustering',
                                   values=dict_clustering)

            print('Calculating: average neighbor degree')
            dict_average_neighbor_degree = nx.average_neighbor_degree(
                Gtc, weight='weight')
            nx.set_node_attributes(Gtc,
                                   name='average_neighbor_degree',
                                   values=dict_average_neighbor_degree)

            print('Calculating: k nearest neighbors')
            dict_k_nearest_neighbors = nx.k_nearest_neighbors(Gtc,
                                                              weight='weight')
            nx.set_node_attributes(Gtc,
                                   name='k_nearest_neighbors',
                                   values=dict_k_nearest_neighbors)

            print('Calculating: eccentricity')
            dict_eccentricity = nx.eccentricity(Gtc)
            nx.set_node_attributes(Gtc,
                                   name='eccentricity',
                                   values=dict_eccentricity)

            print('Calculating: core number')
            dict_core_number = nx.core_number(Gtc)
            nx.set_node_attributes(Gtc,
                                   name='core_number',
                                   values=dict_core_number)
示例#18
0
def _compute_avg_degree_connectivity(G: nx.Graph) -> Dict[int, float]:
    """
    Source: https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.assortativity.k_nearest_neighbors.html#networkx.algorithms.assortativity.k_nearest_neighbors
    """
    return nx.k_nearest_neighbors(G)
示例#19
0
def graphinfo(G):
    nodenum = G.number_of_nodes()
    edgenum = G.size()
    connectivity = approx.node_connectivity(G)
    avgdegree = nx.k_nearest_neighbors(G)
示例#20
0
import networkx as nx
import matplotlib.pyplot as plt
import scipy as sp

# GRAPH CO-EFFICIENT

#G = nx.gnp_random_graph(1000,0.02)

G = nx.read_edgelist("../../Data/SNAP/facebook_combined.txt")

A = nx.to_scipy_sparse_matrix(G);
fig=plt.figure()
plt.spy(A)
fig.show()

r = nx.degree_assortativity_coefficient(G)

print("Degree Assortativity Coefficient = ", r)

n = nx.average_neighbor_degree(G)
k = nx.k_nearest_neighbors(G)
示例#21
0
def processa(nomeEntrada, toStdOut=False):
    """Processa arquivo da rede, pondo as saídas na pasta com o nome 'out/<rede>'
    Saídas:
        - ?
    """
    pastaSaída = criaPastaSaída(nomeEntrada)
    with open(pastaSaída + '/stats.txt', 'w') as arq:

        def printa(*args):
            """Escreve a saída no arquivo de estatísticas, pliz"""
            if toStdOut:
                print(nomeEntrada, '\t', *args)
            else:
                arq.write(' '.join(map(str, args)))
                arq.write('\n')

        # lê a rede do arquivo de entrada
        G = nx.read_weighted_edgelist(nomeEntrada, nodetype=int, comments='%')
        # e acha o maior componente
        maiorComponente = max(nx.connected_component_subgraphs(G), key=len)

        distribuiçãoDeGraus = list(map(lambda t: t[1], G.degree()))

        # knn, assortatividade e talz
        knn = nx.k_nearest_neighbors(G)
        distribuiçãoKnn = list(knn.values())
        ks = list(knn.keys())
        assortatividade = nx.degree_assortativity_coefficient(G)
        printa("Assortatividade:", assortatividade)
        printa("Pearson:", stats.pearsonr(ks, distribuiçãoKnn)[0])
        printa("Spearman:", stats.spearmanr(ks, distribuiçãoKnn)[0])

        # Centralidades; TODO: descobrir se rola o 'G' ou o 'maiorComponente' nessas medidas
        betweenness = list(nx.betweenness_centrality(G).values())
        eigenvector = list(nx.eigenvector_centrality_numpy(G).values())
        closeness = list(nx.closeness_centrality(G).values())
        pageRank = list(nx.pagerank_numpy(G).values())

        caminhada = caminhadaleatoria(G)

    ##  Plots  ##
    def histograma(fig, distribuição, título):
        """Plota um histograma, pra todos ficarem do mesmo jeito =]"""
        plt.figure(fig)
        plt.clf()
        plt.title(título or fig)
        plt.hist(distribuição, bins=100, histtype='step', log=True)
        plt.xlabel('i')
        plt.ylabel('{}(i)'.format(fig))
        plt.savefig('{}/{}.png'.format(pastaSaída, fig))

    # plot dos histogramas
    histograma('k', distribuiçãoDeGraus,
               'Distribuição de probabilidade do grau')
    histograma('bet', betweenness,
               'Distribuição de probabilidade do Betweenness centrality')
    histograma('eig', eigenvector,
               'Distribuição de probabilidade do Eigenvector centrality')
    histograma('CC', closeness,
               'Distribuição de probabilidade do Closeness centrality')
    histograma('pagerank', pageRank,
               'Distribuição de probabilidade do PageRank')

    # plot do 'k vs knn'
    plt.figure('k X knn(k)')
    plt.clf()
    plt.plot(distribuiçãoKnn, 'bo')
    plt.title('Distribuição do grau X Knn(k)')
    plt.xlabel('k')
    plt.ylabel('knn (k)')
    plt.savefig(pastaSaída + '/kXknn.png')
    # plot do k(i) vs bet(i)
    plt.figure('k(i) X betweenness(i)')
    plt.clf()
    pirso = stats.pearsonr(distribuiçãoDeGraus, betweenness)[0]
    plt.loglog(distribuiçãoDeGraus,
               betweenness,
               'bo',
               label='Pearson: ' + str(pirso))
    plt.legend(loc='lower right', scatterpoints=0)
    plt.title('Distribuição de grau X Betweenness centrality')
    plt.xlabel('k(i)')
    plt.ylabel('bet(i)')
    plt.savefig(pastaSaída + '/kXbet.png')
    # plot do eigenvector X pagerank
    plt.figure('eigen X pagerank')
    plt.clf()
    pirso = stats.pearsonr(eigenvector, pageRank)[0]
    plt.loglog(eigenvector, pageRank, 'bo', label='Pearson: ' + str(pirso))
    plt.legend(loc='lower right', scatterpoints=0)
    plt.xlabel('eigenvector (i)')
    plt.ylabel('pagerank (i)')
    plt.title('Eigenvector centrality X Page rank')
    plt.savefig(pastaSaída + '/eigXpagerank.png')
    # plot do k vs caminhada
    plt.figure('k X caminhada aleatória')
    plt.clf()
    pirso = stats.pearsonr(distribuiçãoDeGraus, caminhada)[0]
    plt.plot(distribuiçãoDeGraus,
             caminhada,
             'bo',
             label='Pearson: ' + str(pirso))
    plt.legend(loc='lower right', scatterpoints=0)
    plt.title('Distribuição do grau X Caminhada aleatória')
    plt.xlabel('k (i)')
    plt.ylabel('caminhada (i)')
    plt.savefig(pastaSaída + '/kXcaminhada.png')
    # plot do eigenvector vs caminhada
    plt.figure('eigenvector X caminhada aleatória')
    plt.clf()
    pirso = stats.pearsonr(eigenvector, caminhada)[0]
    plt.plot(eigenvector, caminhada, 'bo', label='Pearson: ' + str(pirso))
    plt.legend(loc='lower right', scatterpoints=0)
    plt.title('Eigenvector centrality X Caminhada aleatória')
    plt.xlabel('eigenvector (i)')
    plt.ylabel('caminhada (i)')
    plt.savefig(pastaSaída + '/eigXcaminhada.png')
示例#22
0
文件: UE-4.1.py 项目: Damanu/CS-UE
def main(argv):
	mode=argv[1]
	path="net.net"
	G=nx.read_pajek(path)
	G=nx.Graph(G)
#-------------1--------------------------	
	Nnodes = G.number_of_nodes()
	Nedges = G.number_of_edges()

	
	degree=list(G.degree().values())
	meandeg=0
	for x in degree:
		meandeg+=x
	meandeg=meandeg/float(Nnodes)
	if mode=="1":
		print "number of nodes: ", Nnodes
		print "number of links: ",Nedges
		print "average degree: ", meandeg
		plt.title("degree distribution")
		plt.hist(degree)	
#------------------------------------------------
	
#------------------2---------------------------
	clustering=list(nx.clustering(G).values())
	ave_cluster=nx.average_clustering(G)
	if mode=="2":
		print "average clustering: ",ave_cluster
		print "-------------------------"
		print "-----ER-Network--------------"
		print "average degree: ", 2*Nedges/float(Nnodes)
		print "-------------------------"
		plt.title("clustering distribution")
		plt.bar(np.linspace(0,18,19),clustering)
	
	cluster_degree=[]
	i=0
	for x in degree:
		if x > 1:
			cluster_degree.append(x)
		else:
			clustering.pop(i)
		i+=1
	
	if mode == "3":	
		plt.title("degree over clustering coefficient")
		plt.plot(clustering,cluster_degree,'o')
#-----------------4---------------------
	neighbours=list(nx.k_nearest_neighbors(G).values())
	if mode=="4":
		print("average neares neighbour degree: ",sum(neighbours)/float(Nnodes))
#------------------5---------------------------
	r=nx.degree_pearson_correlation_coefficient(G)
	if mode=="5":
		print("r: ",r)
#-------------------6-------------------------
	eig_cent=list(nx.eigenvector_centrality(G).values())
	eig_top=sorted(range(len(eig_cent)), key=lambda i:eig_cent[i])[-7:]
	deg_top=sorted(range(len(degree)), key=lambda i:degree[i])[-7:]
	if mode=="6":
		print("degree top 7:",deg_top)
		print("eigenvector centrality top 7: ", eig_top)
#-----------------7--------------------
	pagerank_1=list(nx.pagerank(G,alpha=0.1).values())
	pagerank_2=list(nx.pagerank(G,alpha=0.85).values())
	pagerank_3=list(nx.pagerank(G,alpha=0.99).values())
	if mode=="7":
		plt.plot(range(Nnodes),pagerank_1,'r')
		plt.plot(range(Nnodes),pagerank_2,'g')
		plt.plot(range(Nnodes),pagerank_3,'y')
		
	
	if mode=="8":
		Gcc=sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)[0]
		pos=nx.spring_layout(Gcc)
		nx.draw_networkx_nodes(Gcc,pos,node_size=20)
		nx.draw_networkx_edges(Gcc,pos,alpha=0.4)

	
	plt.show()
示例#23
0
import util
import networkx as nx
from networkx.algorithms import approximation
from networkx.algorithms import connectivity
state_ = 15
input_ = 4
output_ = 1
file_name = 'test.kiss2'
repeated = 5
experiment = 10

util.create_fsm(state_, input_, output_, file_name)
G, g_data = util.create_graph(file_name)

print(nx.average_neighbor_degree(G))
print(approximation.max_clique(G))
print(nx.k_nearest_neighbors(G))
print(nx.min_edge_cover(G))
示例#24
0
文件: TNtools.py 项目: Tsel/TNT
    #
    # outdegree of node
    print(G.in_degree())
    print(G.out_degree())
    print(G.degree)
    # Kanten ausgeben
    for e in G.edges(data=True):
        print('Edge :', e)

    print(att_to_list(G, att="DOG"))
    #
    # Hier haben wir ein directory von allen ausgehenden Kanten von 208... mit den zugehoerigen Informationen
    print(G['208000000000000'])
    print(nx.degree_assortativity_coefficient(G, x='out', y='in'))
    # TODO: Change node name by degree
    # if you want to change all the keys:
    # d = {'x':1, 'y':2, 'z':3}
    # d1 = {'x':'a', 'y':'b', 'z':'c'}
    # In [10]: dict((d1[key], value) for (key, value) in d.items())
    # Out[10]: {'a': 1, 'b': 2, 'c': 3}
    print(nx.average_neighbor_degree(G, target='in'))
    print(nx.k_nearest_neighbors(G, target='in'))
    # data = att_to_list(G, att="VOL")
    # sns.set_style('whitegrid')
    # sns.distplot(np.log10(np.array(data)), rug=True)
    # plt.show()

    # for e in G.edges(data=True):
    #     s,t,att = e
    #     if att.get("FREQ") > 1:
    #         print(e)
# %% [markdown]
# This is a fairly large network

# %%
# here we calculate some network-level statistics to describe the network
# node / edge count
node_count = len(G.nodes)
edge_count = len(G.edges)
# calculate network density
graph_density = nx.density(G)
# average clustering coefficient
graph_avg_clustering_coef = nx.average_clustering(G)
# average neighbour degree
graph_avg_neighbour_deg = nx.average_neighbor_degree(G)
# k-nearest-neighbour
knn = nx.k_nearest_neighbors(G)
# average shortest path
graph_avg_shortest_path = nx.average_shortest_path_length(G)


# %%

print(f"The network has {node_count} nodes, {edge_count} edges, with average density of {graph_density}.\nAverage clustering coefficient = {graph_avg_clustering_coef}\nAverage shortest path length = {graph_avg_shortest_path}")

# %% [markdown]
# Many more network statistics are node-based or edge-based, i.e. the statistics describe individual node/edge in the network. For example, KNN, or average degree of nearest neighbours of k-degree nodes, is used to understand degree correlation and graph assortativity. By plotting KNN against k, we can understand if k-degree nodes tend to connect with nodes of similar degrees.

# %%
knn_df = pd.DataFrame.from_dict(knn,orient='index',columns=['KNN'])
knn_df.sort_index(inplace=True)
knn_df.head()
示例#26
0
c = nx.clustering(G)
print("Clustering co-efficient = ", c)
a = nx.average_clustering(G)
print("Average Clustering co-efficient = ", a)
print("")

print("------------------")
print("Twitter - directed")
print("------------------")

#G2 = nx.read_edgelist(twitter,create_using=nx.DiGraph())
G2 = nx.read_edgelist(twitter)
print("Nodes: ", len(G2))

# Draw the graph
draw_graph(G2)

r = nx.degree_assortativity_coefficient(G2)
print("Degree Assortativity Coefficient = ", r)

n = nx.average_neighbor_degree(G2)
k = nx.k_nearest_neighbors(G2)
c = nx.clustering(G2)
print("Clustering co-efficient = ", c)
a = nx.average_clustering(G2)
print("Average Clustering co-efficient = ", a)
print("")

#print("Displaying the chart")
#display_degseq.plot_degseq(G2, False)
#print("Chart done")
示例#27
0
# rates.plot.box(ylabel=r'Initial growth rate $(d^{-1})$')
# final.plot.box(ylabel=r'Total affected population $(fraction)$',
#                positions=clust)
# plt.violinplot(final,  positions=clust)

# %%
# assortativity (NOT RELEVANT)
sbpx = [221, 222, 223, 224]
nets = [rando, watts, barab, holme]
# nets = latti
fig05 = plt.figure(figsize=(6.4, 4.8), dpi=300)
for i in range(4):
    net = nets[i]
    sbp = sbpx[i]
    fig05.add_subplot(sbp)
    knn = nx.k_nearest_neighbors(net.G)
    net.G.knn = [knn[i] for i in np.unique(net.G.degree_sequence)]

    x = np.unique(net.G.degree_sequence)
    y = np.array(net.G.knn)
    R = nx.degree_assortativity_coefficient(net.G)

    plt.scatter(x, y, alpha=0.5)
    plt.xlabel('k')
    plt.ylabel(r'$\langle k_{nn} \rangle$')
    # plt.ylim([net.G.k_min, net.G.k_max])
    plt.text(net.G.k_min,
             np.min(y),
             'r = ' + str(np.round(R, 2)),
             color='red',
             alpha=0.7)
示例#28
0
B=nx.Graph()
B.add_weighted_edges_from(makenodes)
labels1 = nx.get_edge_attributes(B,'weight')
pos1=nx.bipartite_layout(B,iot_nodes)
pos = nx.circular_layout(B)
nx.draw_networkx_nodes(B ,pos1, node_size=2000, nodelist=edge_nodes, node_color='g')
nx.draw_networkx_nodes(B, pos1, node_size=3000, nodelist=iot_nodes, node_color='b')
nx.draw_networkx_edges(B,pos1,  alpha=0.5, width=3)
nx.draw_networkx_edge_labels(B,pos1,font_color='k',edge_labels=labels1)
nx.draw_networkx_labels(B,pos1,font_color='w')
plt.show()



#nearest neibhour 
print(nx.k_nearest_neighbors(B,nodes=iot_nodes, weight='weight'))





#complete bipartite between edge and iot and edge device clique

initial_graph=nx.compose(B,ete)
labels1 = nx.get_edge_attributes(initial_graph,'weight')
pos1=nx.spring_layout(initial_graph)
pos = nx.circular_layout(initial_graph)
nx.draw_networkx_nodes(initial_graph ,pos1, node_size=2000, nodelist=edge_nodes, node_color='g')
nx.draw_networkx_nodes(initial_graph, pos1, node_size=3000, nodelist=iot_nodes, node_color='b')
nx.draw_networkx_edges(initial_graph,pos1,  alpha=0.5, width=3)
nx.draw_networkx_edge_labels(initial_graph,pos1,font_color='k',edge_labels=labels1)
示例#29
0
print "degree_pearson_correlation_coefficient"
print nx.degree_pearson_correlation_coefficient(G)  
#print nx.k_nearest_neighbors(G)


print "bipartite.closeness_centrality"
print bipartite.closeness_centrality(G,G.node)

print "degree_centrality"
print nx.degree_centrality(G)

print "betweenness_centrality"
print nx.betweenness_centrality(G)

print "k_nearest_neighbors"
print nx.k_nearest_neighbors(G)

#print nx.current_flow_closeness_centrality(G, normalized=True, weight='weight', dtype='float', solver='lu')

#centrality=nx.eigenvector_centrality(G)
#print(['%s %0.2f'%(node,centrality[node]) for node in centrality])
#print nx.eigenvector_centrality(G, max_iter=100, tol=1e-02, nstart=None)

#print nx.communicability(G)

#print nx.triangles(G)
#directed Graphでなくてはだめ

#print(nx.clustering(G,0))
#print nx.average_clustering(G)
示例#30
0
def knn(graph):
    knn = list(nx.k_nearest_neighbors(graph).values())
    k = list(nx.k_nearest_neighbors(graph).keys())
    return knn, k