• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python networkx.diameter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkx.diameter函数的典型用法代码示例。如果您正苦于以下问题:Python diameter函数的具体用法?Python diameter怎么用?Python diameter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了diameter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: compare_graphs

def compare_graphs(graph):
    n = nx.number_of_nodes(graph)
    m = nx.number_of_edges(graph)
    k = np.mean(list(nx.degree(graph).values()))
    erdos = nx.erdos_renyi_graph(n, p=m/float(n*(n-1)/2))
    barabasi = nx.barabasi_albert_graph(n, m=int(k)-7)
    small_world = nx.watts_strogatz_graph(n, int(k), p=0.04)
    print(' ')
    print('Compare the number of edges')
    print(' ')
    print('My network: ' + str(nx.number_of_edges(graph)))
    print('Erdos: ' + str(nx.number_of_edges(erdos)))
    print('Barabasi: ' + str(nx.number_of_edges(barabasi)))
    print('SW: ' + str(nx.number_of_edges(small_world)))
    print(' ')
    print('Compare average clustering coefficients')
    print(' ')
    print('My network: ' + str(nx.average_clustering(graph)))
    print('Erdos: ' + str(nx.average_clustering(erdos)))
    print('Barabasi: ' + str(nx.average_clustering(barabasi)))
    print('SW: ' + str(nx.average_clustering(small_world)))
    print(' ')
    print('Compare average path length')
    print(' ')
    print('My network: ' + str(nx.average_shortest_path_length(graph)))
    print('Erdos: ' + str(nx.average_shortest_path_length(erdos)))
    print('Barabasi: ' + str(nx.average_shortest_path_length(barabasi)))
    print('SW: ' + str(nx.average_shortest_path_length(small_world)))
    print(' ')
    print('Compare graph diameter')
    print(' ')
    print('My network: ' + str(nx.diameter(graph)))
    print('Erdos: ' + str(nx.diameter(erdos)))
    print('Barabasi: ' + str(nx.diameter(barabasi)))
    print('SW: ' + str(nx.diameter(small_world)))
开发者ID:feygina,项目名称:social-network-VK-analysis,代码行数:35,代码来源:functions_for_vk_users.py


示例2: testRun

    def testRun(self):
        sim = watts_strogatz.WS()
        sim.run(
            steps=self.starting_network_size,
            rewiring_probability=self.rewiring_probability,
            lattice_connections=self.lattice_connections,
            starting_network_size=self.starting_network_size)

        with sim.graph.handle as graph:
            self.assertEqual(
                self.comparison_graph.number_of_nodes(),
                graph.number_of_nodes())
            self.assertEqual(
                self.comparison_graph.number_of_edges(),
                graph.number_of_edges())

            if False:
                self.assertAlmostEqual(
                    nx.diameter(self.comparison_graph),
                    nx.diameter(graph),
                    delta=1.
                )
                self.assertAlmostEqual(
                    nx.average_shortest_path_length(self.comparison_graph),
                    nx.average_shortest_path_length(graph),
                    delta=1.
                )
开发者ID:rik0,项目名称:pynetsym,代码行数:27,代码来源:test_sw.py


示例3: make_graph

 def make_graph(self,save_graph=True):
     graph = nx.DiGraph()
     all_tweets = [tweet for page in self.results for tweet in page['results']]
     for tweet in all_tweets:
         rt_sources = self.get_rt_sources(tweet["text"])
         if not rt_sources: continue 
         for rt_source in rt_sources:
             graph.add_edge(rt_source, tweet["from_user"], {"tweet_id": tweet["id"]})
     #--Calculate graph summary statistics
     if nx.is_connected(graph.to_undirected()):
         diameter  = nx.diameter(graph.to_undirected())         
         average_shortest_path = nx.average_shortest_path_length(graph.to_undirected())
         print 'Diameter: ', diameter
         print 'Average Shortest Path: ',average_shortest_path
     else:
          print "Graph is not connected so calculating the diameter and average shortest path length on all connected components."
          diameter = []
          average_shortest_path = []
          for subgraph in nx.connected_component_subgraphs(graph.to_undirected()):
              diameter.append(nx.diameter(subgraph))
              average_shortest_path.append(nx.average_shortest_path_length(subgraph))
          from numpy import median
          from scipy.stats import scoreatpercentile
          print 'Diameter: ',median(diameter),u'\xB1',str(scoreatpercentile(diameter,75)-scoreatpercentile(diameter,25))
          print 'Average Path Length :',median(average_shortest_path),u'\xB1',str(scoreatpercentile(average_shortest_path,75)-scoreatpercentile(average_shortest_path,25))
     degree_sequence=sorted(nx.degree(graph).values(),reverse=True) # degree sequence
        
     import matplotlib.pyplot as plt
     plt.loglog(degree_sequence,'b-',marker='o')
     plt.title("Distribution of Degrees for %s tweets" %(self.drug_name), fontsize=20)
     plt.ylabel("Degree", fontsize=20)
     plt.xlabel("Rank", fontsize=20)
     
     # draw graph in inset
     ax = plt.axes([0.35,0.25,0.55,0.55])
     plt.axis('off')
     nx.draw(graph, ax=ax, alpha=0.8, with_labels=False)
     
     plt.savefig("degree_distribution_%s.png"%(self.drug_name.replace(' ','_')), dpi=300)
     plt.close()
     if save_graph:
         output_file = self.drug_name.replace(' ','_') + '.dot'
         try:
             nx.drawing.write_dot(graph,output_file)
             print 'Graph saved as ',output_file
         except (ImportError, UnicodeEncodeError) as e:
             dot = ['"%s" -> "%s" [tweetid=%s]' % (node1,node2,graph[node1][node2]['tweet_id']) 
                     for node1,node2, in graph.edges()]
             with codecs.open(output_file,'w', encoding='utf-8') as f:
                 f.write('strict digraph G{\n%s\n}' % (';\n'.join(dot),))
                 print 'Saved ',output_file,' by brute force'
     return diameter, average_shortest_path
                 
开发者ID:charudatta-navare,项目名称:ToxTweet,代码行数:52,代码来源:twitterQuery.py


示例4: attaccoPercent

def attaccoPercent(compagnia, steps):
    adiacenzaFinal = numpy.genfromtxt(("/home/protoss/Documenti/Siscomp_datas/data/AdiacenzaEuclidea_{0}.csv".format(compagnia)),delimiter=',',dtype='int')
    grafoFinal = networkx.Graph(adiacenzaFinal)

    graphSize = networkx.number_of_nodes(grafoFinal)
    passo = networkx.number_of_nodes(grafoFinal)/steps

    i = 0
    ascisse.append(i)
    aziendaFinal.append(compagnia)
    diametro.append(2)
    relSizeGC.append(1)

    while (networkx.number_of_nodes(grafoFinal) > passo):
        gradiFinal = pandas.DataFrame(grafoFinal.degree().items(), columns=['index', 'grado'])
        gradiFinal.sort(["grado"], ascending=[False], inplace=True)
        sortedIDnode = gradiFinal['index'].values

#        grafoFinal.remove_nodes_from(sortedIDnode[0:passo])
        for identificativo in sortedIDnode:
            if (networkx.number_of_nodes(grafoFinal) > len(sortedIDnode) - passo):
                   grafoFinal.remove_node(identificativo)

        giantCluster = max(networkx.connected_component_subgraphs(grafoFinal), key = len)
        
        i += 100/float(steps)
        ascisse.append(i)
        aziendaFinal.append(compagnia)

        graphSize = networkx.number_of_nodes(grafoFinal)
        diametro.append(networkx.diameter(giantCluster, e=None))
        relSizeGC.append((networkx.number_of_nodes(giantCluster))/(float(graphSize)))
开发者ID:FedericoMuciaccia,项目名称:SistemiComplessi,代码行数:32,代码来源:Attack+&+Failure.py


示例5: calc_D

def calc_D(G):
    '''
    A function to calculate the diameter
    
    input parameters:
          G:      A graph in networkX format.
    
    returns:
          D:      The diameter, which is the largest diameter among all the sub
                  components.
    '''

    subD = []
    subGs = list(nx.connected_component_subgraphs(G))
    indsubG = 1
    for H in subGs:
        if len(H.nodes())>1:
            print('D: Subgraph '+str(indsubG)+' with '+str(len(H.nodes()))+' nodes')
            subD.append(nx.diameter(H))
        else:
            subD.append(0)
        indsubG += 1
    # returning the maximum diameter among all the sub components
    D = np.max(subD)
    return D
开发者ID:sathayas,项目名称:fMRIConnectome,代码行数:25,代码来源:NetStats.py


示例6: min_connectivity

 def min_connectivity(self, graph):
     apnc = nx.all_pairs_node_connectivity(graph)
     # start with graph diameter; minimum won't be larger than this
     mc = nx.diameter(graph)
     for targets in apnc.itervalues():
         mc = min(min(targets.itervalues()), mc)
     return mc
开发者ID:geistwriter,项目名称:sawtooth-core,代码行数:7,代码来源:stats_utils.py


示例7: printStats

def printStats(filename):
	'''
	Converts json adjacency list into networkx to calculate and print the
	graphs's 
	  - average clustering coefficient
	  - overall clustering coefficient
	  - maximum diameter
	  - average diameter
	  - number of paritions using community.best_parition
	  - modularity of community.best_partition
	'''
	g = makeGraphFromJSON(filename)
	
	print "Average Clustering Coefficient: %f" % nx.average_clustering(g)
	print "Overall Clustering Coefficient: %f" % nx.transitivity(g)
	
	connected_subgraphs = list(nx.connected_component_subgraphs(g))
	largest = max(nx.connected_component_subgraphs(g), key=len)
	print "# Connected Components: %d" % len(connected_subgraphs)
	print "    Maximal Diameter: %d" % nx.diameter(largest)
	print "    Average Diameter: %f" % nx.average_shortest_path_length(largest)

	# Find partition that maximizes modularity using Louvain's algorithm
	part = community.best_partition(g)	
	print "# Paritions: %d" % (max(part.values()) + 1)
	print "Louvain Modularity: %f" % community.modularity(part, g)
开发者ID:azercephi,项目名称:kraftwerk,代码行数:26,代码来源:analyze.py


示例8: strongly_connected_components

def strongly_connected_components():
    conn = sqlite3.connect("zhihu.db")     
    #following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 50000) and user_url in (select user_url from User where agree_num > 50000)', conn)        
    following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 10000) and user_url in (select user_url from User where agree_num > 10000)', conn)        
    conn.close()
    
    G = nx.DiGraph()
    cnt = 0
    for d in following_data.iterrows():
        G.add_edge(d[1][0],d[1][1])
        cnt += 1
    print 'links number:', cnt

    scompgraphs = nx.strongly_connected_component_subgraphs(G)
    scomponents = sorted(nx.strongly_connected_components(G), key=len, reverse=True)
    print 'components nodes distribution:', [len(c) for c in scomponents]
    
    #plot graph of component, calculate saverage_shortest_path_length of components who has over 1 nodes
    index = 0
    print 'average_shortest_path_length of components who has over 1 nodes:'
    for tempg in scompgraphs:
        index += 1
        if len(tempg.nodes()) != 1:
            print nx.average_shortest_path_length(tempg)
            print 'diameter', nx.diameter(tempg)
            print 'radius', nx.radius(tempg)
        pylab.figure(index)
        nx.draw_networkx(tempg)
        pylab.show()

    # Components-as-nodes Graph
    cG = nx.condensation(G)
    pylab.figure('Components-as-nodes Graph')
    nx.draw_networkx(cG)
    pylab.show()    
开发者ID:TSOTDeng,项目名称:zhihu-analysis-python,代码行数:35,代码来源:zhihu_analysis.py


示例9: ltDecomposeTestBatFull

def ltDecomposeTestBatFull(dsName, path, outfile, cd, wccOnly, revEdges, undir, diaF, fillF):
    origNet = loadNw(dsName, path, cd, wccOnly, revEdges, undir)
    prodNet = origNet
    # prodNet = copy.deepcopy(origNet)
    # print("dc")
    outfile = open(path + outfile + ".csv", "w")
    intFlag = False
    print("NW-WIDE MEASURES:\n")

    nodeStr = str(origNet.number_of_nodes())
    edgeStr = str(origNet.number_of_edges())
    avgDeg = str(float(origNet.number_of_edges()) / float(origNet.number_of_nodes()))
    dens = str(nx.density(origNet))
    avgCl = "--"
    # avgCl = str(nx.average_clustering(origNet))

    if diaF:
        print("  Starting dia calc")
        diameter = str(nx.diameter(origNet))
        print("  --> done w. dia calc")
    else:
        diameter = "---"

        # outfile.write("Dataset,NumNodes,NumEdges,avgDeg,dens,avgCl,diameter\n")
        # outfile.write(dsName+","+nodeStr+","+edgeStr+","+avgDeg+","+dens+","+avgCl+","+diameter+"\n")
        # if fillF:
        # 	print("FULL THRESH TEST\n")
        # outfile.write("Dataset,ThreshType,ThreshVal,PercSize,NumNodes,NumEdges,TimeAlg,TimeAlgAndSetup,Check\n")
        # thresh=1.0
        # outfile.write(ltDecomposeNoSetWithCheck(prodNet,thresh,dsName,intFlag,origNet))

    outfile.close()
    print("Done.")
开发者ID:joeyh321,项目名称:ORCA,代码行数:33,代码来源:ltDecomp3.py


示例10: topologyNetx

def topologyNetx(gestore):
    adiacenza = numpy.genfromtxt("/home/protoss/Documenti/Siscomp_datas/data/AdiacenzaEuclidea_{0}.csv".format(gestore),delimiter=',',dtype='int') 
    grafo = networkx.Graph(adiacenza)
    c = networkx.average_clustering(grafo)
    d = networkx.diameter(grafo)
    l = networkx.average_shortest_path_length(grafo)
    return c, d, l
开发者ID:FedericoMuciaccia,项目名称:SistemiComplessi,代码行数:7,代码来源:Adiacenza,+grafo+e+grado.py


示例11: NetStats

def NetStats(G):
    return { 'radius': nx.radius(G),
             'diameter': nx.diameter(G),
             'connected_components': nx.number_connected_components(G),
             'density' : nx.density(G),
             'shortest_path_length': nx.shortest_path_length(G),
             'clustering': nx.clustering(G)}
开发者ID:CSB-IG,项目名称:NinNX,代码行数:7,代码来源:__init__.py


示例12: get_diameters

def get_diameters(graph):
    connected_components = nx.connected_component_subgraphs(graph)
    print "number of connected components: ", len(connected_components)
    diameters = []
    for subgraph in connected_components:
        diameters.append((len(subgraph), nx.diameter(subgraph)))
    print "diameters: ", diameters
开发者ID:jessieduan,项目名称:cs224w-jays,代码行数:7,代码来源:get_graph_stats.py


示例13: getDiameter

 def getDiameter(self):
     graph = self.getGraph()
     try:
         diameter = nx.diameter(graph)
     # NetworkX will throw an exception if the graph is not connected (~ infinite diameter)
     except nx.NetworkXError:
         return -1
开发者ID:ellyn,项目名称:bitcointopology,代码行数:7,代码来源:network.py


示例14: write_network_characteristics

    def write_network_characteristics(g):
        nodes = len(g.nodes())
        edges = len(g.edges())
        avg_degree = float(2*edges)/nodes
        max_conn = (nodes*(nodes-1))/2
        clustering = nx.average_clustering(g)
        density = nx.density(g)
        diameter = nx.diameter(g)
        a_p_l = nx.average_shortest_path_length(g)
        conn = nx.is_connected(g)
        n_comp_con = nx.number_connected_components(g)
        # write them on file
        out = open("statistics_giant.csv", "w")
        out.write("#Nodes,#Edges,Avg_Degree, Max Connection, Clustering Coefficient, Density, Diameter , Average Shortest Path ,  Is Connected? , Number Connected Component\n")
        out.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n" % (nodes, edges, avg_degree , max_conn, clustering, density ,diameter ,a_p_l, conn , n_comp_con))

        g = read_graph("dataset/cutted_graph(0.15).csv")

        degree_distribution(g0)

        #Extract max Giant component
        cc=sorted(nx.connected_component_subgraphs(g), key = len, reverse=True)
        g0=gcc[0]

        write_network_characteristics(g0)
开发者ID:pigna90,项目名称:lico_network_analysis,代码行数:25,代码来源:giant.py


示例15: write_network

def write_network(network, time, targets, seed, filename="network.dat"):
    print("\tDetermining network type.")
    if isinstance(network,nx.DiGraph):
        network_type = "Directed"
    else:
        network_type = "Undirected"

    print("\tCalculaing edges and vertices.")
    edges = network.number_of_edges()
    vertices = network.number_of_nodes()
    undirected = network.to_undirected()

    print("\tFinding subgraphs.")
    subgraphs = nx.connected_component_subgraphs(undirected)

    print("\tFinding network diameter.")
    diameter = nx.diameter(subgraphs[0])

    print("\tStoring network parameters")

    out = open(filename, "w")
    out.write("Simulation name: {0}\n\n".format(time))
    out.write("Network properties\n===============\n")
    out.write("Network type: {0}\n".format(network_type))
    out.write("Number of vertices: {0}\n".format(vertices))
    out.write("Number of edges: {0}\n".format(edges))
    out.write("Diameter: {0}\n".format(diameter))

    out.close()
开发者ID:mananshah99,项目名称:diseasenetworks,代码行数:29,代码来源:simulator.py


示例16: diameter

def diameter(connected_component_graphs, file_name):       
    max_diameter = 0
    for connected_component in connected_component_graphs:
        diameter  = nx.diameter(connected_component)
        if max_diameter < diameter:
            max_diameter = diameter
    file_name.write("Diameter: " + str(max_diameter) + "\n")
开发者ID:pekzeki,项目名称:SNAofYelp,代码行数:7,代码来源:graph_analysis.py


示例17: run

    def run(self, graph, all_disconnected_nodes,a1,a2,node=None):
        '''
        Assign weight to node depending on degree
    '''
        weights = {}
        oweights={}
        
        
        #calculate maximum and minimum degrees of nodes
        #use it for calculating assortativity
        
        d=len(graph.nodes())
        if nx.is_connected(graph):
            d=nx.diameter(graph)
        
       
        #calculate similarity of nodes based on their degrees
        for nodes in all_disconnected_nodes:
            if nx.has_path(graph,node,nodes):
                metric=nx.shortest_path_length(graph, node, nodes)/(d)
            else:
                metric=1

            weights[nodes]=a1*(1-metric)
            oweights[nodes]=a2*(metric)
            
        return Weights(weights,oweights)   
开发者ID:stephelena,项目名称:NetAttack,代码行数:27,代码来源:DefenderAgent.py


示例18: obca

def obca(g):
    diameter = nx.diameter(g)
    lb_max = diameter + 1

    # Rank the nodes according to their degree
    results = nx.degree_centrality(g)
    nodes = next(zip(*sorted(results.items(), key=operator.itemgetter(1))))
    results = dict()

    for lb in range(2, lb_max):
        covered_frequency = [0] * len(g.nodes())
        boxes = list()

        for i in range(0, len(nodes)):
            node = nodes[i]

            if covered_frequency[i] > 0:
                continue

            box = list(nx.single_source_shortest_path_length(g, node, lb-1).keys())

            # Verify that all paths within the box have the length less then lb
            index = 0
            while True:
                node = box[index]
                for j in range(index+1, len(box)):
                    neighbor = box[j]

                    if nx.shortest_path_length(g, node, neighbor) >= lb:
                        box.remove(neighbor)

                index += 1
                if index >= len(box):
                    break

            for node in box:
                node_index = nodes.index(node)
                covered_frequency[node_index] += 1

            boxes.append(box)

        for box in boxes:
            redundant_box = True

            for node in box:
                node_index = nodes.index(node)
                if covered_frequency[node_index] == 1:
                    redundant_box = False
                    break

            if redundant_box:
                for node in box:
                    node_index = nodes.index(node)
                    covered_frequency[node_index] -= 1
                boxes.remove(box)

        print("lb: {}, boxes: {}, cf: {}".format(lb, boxes, covered_frequency))
        results[lb] = boxes

    return results
开发者ID:computational-center,项目名称:complexNetworksMeasurements,代码行数:60,代码来源:OBCA.py


示例19: init_tracks

def init_tracks(T, root, node_to_tm, edge_to_rate,
        primary_to_tol, Q_primary,
        primary_track, tolerance_tracks, interaction_map):
    """
    Initialize trajectories of all tracks.

    """
    # Initialize blink history and events.
    for track in tolerance_tracks:
        init_blink_history(T, track)
        init_complete_blink_events(T, node_to_tm, edge_to_rate, track)
        track.remove_self_transitions()

    # Initialize the primary trajectory with many incomplete events.
    diameter = nx.diameter(Q_primary)
    ev_to_P_nx = init_incomplete_primary_events(T, node_to_tm, edge_to_rate,
            primary_track, diameter)

    # Sample the state of the primary track.
    sample_primary_transitions(T, root, node_to_tm, edge_to_rate,
            primary_to_tol, ev_to_P_nx,
            primary_track, tolerance_tracks)

    # Remove self-transition events from the primary track.
    primary_track.remove_self_transitions()
开发者ID:argriffing,项目名称:npblink,代码行数:25,代码来源:raoteh.py


示例20: calculate

def calculate(network):
    try:
        n = nx.diameter(network)
    except:
        return 0
 
    return round(n, 7) 
开发者ID:bt3gl,项目名称:NetAna-Complex-Network-Analysis,代码行数:7,代码来源:diameter.py



注:本文中的networkx.diameter函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.difference函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.dfs_tree函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap