当前位置: 首页>>代码示例>>Python>>正文


Python networkx.degree方法代码示例

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


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

示例1: decode_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
开发者ID:JiaxuanYou,项目名称:graph-generation,代码行数:23,代码来源:utils.py

示例2: dataset_reader

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def dataset_reader(path):
    """
    Function to read the graph and features from a json file.
    :param path: The path to the graph json.
    :return graph: The graph object.
    :return features: Features hash table.
    :return name: Name of the graph.
    """
    name = path.strip(".json").split("/")[-1]
    data = json.load(open(path))
    graph = nx.from_edgelist(data["edges"])

    if "features" in data.keys():
        features = data["features"]
    else:
        features = nx.degree(graph)

    features = {int(k): v for k, v in features.items()}
    return graph, features, name 
开发者ID:benedekrozemberczki,项目名称:graph2vec,代码行数:21,代码来源:graph2vec.py

示例3: hub_dominance

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def hub_dominance(graph, communities, **kwargs):
    """Hub dominance.

    The hub dominance of a community is defined as the ratio of the degree of its most connected node w.r.t. the theoretically maximal degree within the community.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.hub_dominance(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: max([x[1] for x in
                                                      list(nx.degree(nx.subgraph(graph, coms)))]) / (len(coms) - 1),
                             **kwargs) 
开发者ID:GiulioRossetti,项目名称:cdlib,代码行数:25,代码来源:fitness.py

示例4: test_info

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info(self):
        G=nx.path_graph(5)
        info=nx.info(G)
        expected_graph_info='\n'.join(['Name: path_graph(5)',
                                       'Type: Graph',
                                       'Number of nodes: 5',
                                       'Number of edges: 4',
                                       'Average degree:   1.6000'])
        assert_equal(info,expected_graph_info)

        info=nx.info(G,n=1)
        expected_node_info='\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 0 2'])
        assert_equal(info,expected_node_info) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:18,代码来源:test_function.py

示例5: test_info_digraph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info_digraph(self):
        G=nx.DiGraph(name='path_graph(5)')
        G.add_path([0,1,2,3,4])
        info=nx.info(G)
        expected_graph_info='\n'.join(['Name: path_graph(5)',
                                       'Type: DiGraph',
                                       'Number of nodes: 5',
                                       'Number of edges: 4',
                                       'Average in degree:   0.8000',
                                       'Average out degree:   0.8000'])
        assert_equal(info,expected_graph_info)

        info=nx.info(G,n=1)
        expected_node_info='\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info,expected_node_info)

        assert_raises(nx.NetworkXError,nx.info,G,n=-1) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:22,代码来源:test_function.py

示例6: test_info

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info(self):
        G = nx.path_graph(5)
        G.name = "path_graph(5)"
        info = nx.info(G)
        expected_graph_info = '\n'.join(['Name: path_graph(5)',
                                         'Type: Graph',
                                         'Number of nodes: 5',
                                         'Number of edges: 4',
                                         'Average degree:   1.6000'])
        assert_equal(info, expected_graph_info)

        info = nx.info(G, n=1)
        expected_node_info = '\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 0 2'])
        assert_equal(info, expected_node_info) 
开发者ID:holzschu,项目名称:Carnets,代码行数:19,代码来源:test_function.py

示例7: test_info_digraph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def test_info_digraph(self):
        G = nx.DiGraph(name='path_graph(5)')
        nx.add_path(G, [0, 1, 2, 3, 4])
        info = nx.info(G)
        expected_graph_info = '\n'.join(['Name: path_graph(5)',
                                         'Type: DiGraph',
                                         'Number of nodes: 5',
                                         'Number of edges: 4',
                                         'Average in degree:   0.8000',
                                         'Average out degree:   0.8000'])
        assert_equal(info, expected_graph_info)

        info = nx.info(G, n=1)
        expected_node_info = '\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info, expected_node_info)

        assert_raises(nx.NetworkXError, nx.info, G, n=-1) 
开发者ID:holzschu,项目名称:Carnets,代码行数:22,代码来源:test_function.py

示例8: _mean_node_degree

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def _mean_node_degree(graph, degree):
    """
    Calculates mean node degree in a graph.
    """
    return np.mean(list(dict(graph.nodes(degree)).values())) 
开发者ID:martinfleis,项目名称:momepy,代码行数:7,代码来源:graph.py

示例9: _modularity_generator

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def _modularity_generator(self):
        """Calculating the sparse modularity matrix."""
        degs = nx.degree(self._graph)
        e_count = self._graph.number_of_edges()
        n_count = self._graph.number_of_nodes()
        modularity_mat_shape = (n_count, n_count)
        indices_1 = np.array([edge[0] for edge in self._graph.edges()] + [edge[1] for edge in self._graph.edges()])
        indices_2 = np.array([edge[1] for edge in self._graph.edges()] + [edge[0] for edge in self._graph.edges()])
        scores = [1.0-(float(degs[e[0]]*degs[e[1]])/(2*e_count)) for e in self._graph.edges()]
        scores = scores + [1.0-(float(degs[e[1]]*degs[e[0]])/(2*e_count)) for e in self._graph.edges()]
        mod_matrix = coo_matrix((scores, (indices_1, indices_2)), shape=modularity_mat_shape)
        return mod_matrix 
开发者ID:benedekrozemberczki,项目名称:karateclub,代码行数:14,代码来源:mnmf.py

示例10: watts_strogatz_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def watts_strogatz_graph(N, deg, dia, dim, domain):
    '''
    Parameters of the graph:
    n (int) – The number of nodes
    k (int) – Each node is joined with its k nearest neighbors in a ring topology.
    p (float) – The probability of rewiring each edge

    Average Degree is solely decided by k
    Diameter depends on the value of p
    :return: Graph Object
    '''
    strt_time = time()

    p = 0.2

    G = nx.watts_strogatz_graph(n=N, k=deg, p=p)

    lcc, _ = graph_util.get_nk_lcc_undirected(G)

    best_G = lcc

    best_diam = nx.algorithms.diameter(best_G)

    best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))

    end_time = time()

    print('Graph_Name: Watts_Strogatz_Graph')
    print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
    print('TIME: ', end_time - strt_time)

    return best_G, best_avg_deg, best_diam

######################################################################## 
开发者ID:palash1992,项目名称:GEM-Benchmark,代码行数:36,代码来源:graph_gens.py

示例11: powerlaw_cluster_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def powerlaw_cluster_graph(N, deg, dia, dim, domain):
    '''
    Parameters of the graph:
    n (int) – the number of nodes
    m (int) – the number of random edges to add for each new node
    p (float,) – Probability of adding a triangle after adding a random edge
    Formula for m:  (m^2)- (Nm)/2 + avg_deg * (N/2) = 0  =>  From this equation we need to find m :
    p : Does not vary the average degree or diameter so much. : Higher value of p may cause average degree to overshoot intended average_deg
    so we give the control of average degree to parameter m: by setting a lower value of p: 0.1
    :return: Graph Object
    '''

    ## Calculating thof nodes: 10\nNumber of edges: 16\nAverage degree:   3.2000'
    strt_time = time()

    m = int(round((N - np.sqrt(N ** 2 - 4 * deg * N)) / 4))
    p = 0.2

    ## G at center:
    G = nx.powerlaw_cluster_graph(n=N, m=m, p=p)

    lcc, _ = graph_util.get_nk_lcc_undirected(G)

    best_G = lcc

    best_diam = nx.algorithms.diameter(best_G)

    best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))


    end_time = time()
    print('Graph_Name: powerlaw_cluster_graph')
    print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
    print('TIME: ', end_time - strt_time)
    return best_G, best_avg_deg, best_diam

##################################################################### 
开发者ID:palash1992,项目名称:GEM-Benchmark,代码行数:39,代码来源:graph_gens.py

示例12: node_degree

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def node_degree(graph, name="degree"):
    """
    Calculates node degree for each node.

    Wrapper around ``networkx.degree()``.

    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    name : str (default 'degree')
        calculated attribute name

    Returns
    -------
    Graph
        networkx.Graph

    Examples
    --------
    >>> network_graph = mm.node_degree(network_graph)
    """
    netx = graph.copy()

    degree = dict(nx.degree(netx))
    nx.set_node_attributes(netx, degree, name)

    return netx 
开发者ID:martinfleis,项目名称:momepy,代码行数:31,代码来源:graph.py

示例13: _proportion

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def _proportion(graph, degree):
    """
    Calculates the proportion of intersection types in a graph.
    """
    import collections

    values = list(dict(graph.nodes(degree)).values())
    counts = collections.Counter(values)
    return counts 
开发者ID:martinfleis,项目名称:momepy,代码行数:11,代码来源:graph.py

示例14: fields_degree

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def fields_degree(self, topk):
        degree = nx.degree(self.__G)
        sorted_degree = sorted(degree.items(), key=operator.itemgetter(1))
        sorted_degree.reverse()
        topk_nodes = sorted_degree[:topk]
        return topk_nodes 
开发者ID:mitdbg,项目名称:aurum-datadiscovery,代码行数:8,代码来源:fieldnetwork.py

示例15: write_summary_file

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import degree [as 别名]
def write_summary_file(self,path,append=True):
        '''
        Writes summary information about this network to a file
        
        **Optional Arguments**
         - *append* = True if summary information should be appended to the file. If so the file is written as a csv spreadsheet. 
           Default is true. If False is passed, a single, detailed summary is written for this network.
        '''
        if append: #write summary information in spreadsheet formant
            exists = os.path.exists(path)
            f = open(path,"a")
            
            if not exists: #write header
                f.write("name,#nodes,#edges\n") #todo add other stuff here
                
            #write data
            f.write("%s,%s,%s\n" % (self.basename,self.graph.number_of_nodes(),self.graph.number_of_edges()))
        
            f.close()
        else: #write detailed information
            import networkx as nx
            
            f = open(path,"w")
            f.write("Summary:")
            f.write("Name: %s\n" % self.basename)
            f.write("#nodes: %s\n" % self.graph.number_of_nodes())
            f.write("#edges: %s\n" % self.graph.number_of_edges())
            f.write("Detail")
            f.write("Degree sequence: %s" % str(list(nx.degree(self.graph).values())))
            f.write("Node list: %s" % str(self.graph.nodes(data=False)))
            f.write("Edge list: %s" % str(self.graph.edges(data=False)))
            f.write("Node attributes: %s" % str(self.graph.nodes(data=True)))
            f.write("Edge attributes: %s" % str(self.graph.edges(data=True)))
            
            f.close() 
开发者ID:cgre-aachen,项目名称:pynoddy,代码行数:37,代码来源:output.py


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