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


Python networkx.diameter方法代码示例

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


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

示例1: calc_diameter

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def calc_diameter(nodes):
    """
    Warning : this only works on tree graphs !!

    For arbitrary graphs, we need to compute the shortest path between any
    two vertices and take the length of the greatest of these paths
    :param nodes:
    :return:
    """

    # Calculate the diameter of a graph made of variables and relations

    # first pick a random node in the tree and use a BFS to find the furthest
    # node in the graph
    root = random.choice(nodes)
    node, distance = find_furthest_node(root, nodes)

    _, distance = find_furthest_node(node, nodes)

    return distance 
开发者ID:Orange-OpenSource,项目名称:pyDcop,代码行数:22,代码来源:graphs.py

示例2: graph_diameter

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def graph_diameter(variables, relations):
    """
    Compute the graph diameter(s).
    If the graph contains several independent sub graph, returns a list the
    diamater of each of the subgraphs.

    :param variables:
    :param relations:
    :return:
    """
    diams = []
    g = as_networkx_graph(variables, relations)
    components  = (g.subgraph(c).copy() for c in nx.connected_components(g))
    for c in components:
        diams.append(nx.diameter(c))

    return diams 
开发者ID:Orange-OpenSource,项目名称:pyDcop,代码行数:19,代码来源:graphs.py

示例3: decode_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [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

示例4: dendritic_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def dendritic_graph(self):
        """
        Builds skeleton of the topological representation (used internally)
        """
        diam = networkx.diameter(self.gl)
        g3 = networkx.Graph()
        dicdend = {}
        for n in range(diam-1):
            nodedist = []
            for k in self.pl:
                dil = networkx.shortest_path_length(self.gl, self.root, k)
                if dil == n:
                    nodedist.append(str(k))
            g2 = self.gl.subgraph(nodedist)
            dicdend[n] = sorted(networkx.connected_components(g2))
            for n2, yu in enumerate(dicdend[n]):
                g3.add_node(str(n) + '_' + str(n2))
                if n > 0:
                    for n3, yu2 in enumerate(dicdend[n-1]):
                        if networkx.is_connected(self.gl.subgraph(list(yu)+list(yu2))):
                            g3.add_edge(str(n) + '_' + str(n2), str(n-1) + '_' + str(n3))
        return g3, dicdend 
开发者ID:CamaraLab,项目名称:scTDA,代码行数:24,代码来源:main.py

示例5: get_diameters

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def get_diameters(graph):
    r"""
    Compute histogram of connected components diameters for a graph.
    
    :param graph: graph representation in networkx format: nx.from_numpy_matrix(A)
    :return: list of connected components diameters
    """
    diams = []
    for g in nx.connected_component_subgraphs(graph):
        diams.append(nx.diameter(g))
    diams = list(filter(lambda a: a != 0, diams))
    return np.array(diams) 
开发者ID:davide-belli,项目名称:generative-graph-transformer,代码行数:14,代码来源:statistics.py

示例6: network_node_dispersion

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def network_node_dispersion(G):
    """
    This function calculates the network node dispersion of a graph G. This
    function also returns the average of the each node-distance distribution.

    Parameters
    ----------
    G (nx.Graph): the graph in question.

    Returns
    -------
    nnd (float): the nearest node dispersion
    nd_vec (np.ndarray): a vector of averages of the
                         node-distance distributions

    """

    N = G.number_of_nodes()
    nd = node_distance(G)
    pdfm = np.mean(nd, axis=0)

    # NOTE: the paper says that the normalization is the diameter plus one,
    # but the previous implementation uses the number of nonzero entries in the
    # node-distance matrix. This number should typically be the diameter plus
    # one anyway.
    norm = np.log(nx.diameter(G) + 1)

    ndf = nd.flatten()
    # calculate the entropy, with the convention that 0/0 = 0
    entr = -1 * sum(ndf * np.log(ndf, out=np.zeros_like(ndf), where=(ndf != 0)))

    nnd = max([0, entropy(pdfm) - entr / N]) / norm

    return nnd, pdfm 
开发者ID:netsiphd,项目名称:netrd,代码行数:36,代码来源:dmeasure.py

示例7: split_network_into_feeders

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def split_network_into_feeders(self):
        """
        This function splits the network into subnetworks corresponding to the feeders.

        .. note:: add_feeder_information should be called first
        """
        if self.feeder_names is None or self.feeder_nodes is None:
            raise ValueError(
                "Cannot split the network into feeders because feeders are unknown. Call add_feeder_information first."
            )

        for cpt, feeder_name in enumerate(self.feeder_names):
            feeder_node_list = self.feeder_nodes[cpt]
            self.feeder_networks[feeder_name] = self.G.graph.subgraph(feeder_node_list)

            # If the feeder information is perfect, that is the end of the story.
            # But, most of the time, some nodes are missing from the feeder information.
            # This means that we get disconnected feeder networks which will cause some
            # issues later (when computing the diameter for example)
            # For this reason, the following code is trying to infer the missing nodes
            # and edges such that the feeder networks are all connected in the end.
            while not nx.is_connected(self.feeder_networks[feeder_name]):
                self.connect_disconnected_components(feeder_name)
                feeder_node_list = self.feeder_nodes[cpt]
                self.feeder_networks[feeder_name] = self.G.graph.subgraph(
                    feeder_node_list
                )

            # Build the node_feeder_mapping
            # for node in self.feeder_nodes[cpt]:
            for node in self.feeder_networks[feeder_name].nodes():
                self.node_feeder_mapping[node] = feeder_name 
开发者ID:NREL,项目名称:ditto,代码行数:34,代码来源:network_analysis.py

示例8: diameter

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def diameter(self, *args):
        """Returns the diameter of the network."""
        if args:
            return nx.diameter(args[0])
        else:
            return nx.diameter(self.G.graph) 
开发者ID:NREL,项目名称:ditto,代码行数:8,代码来源:network_analysis.py

示例9: test_diameter

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def test_diameter(self):
        assert_equal(networkx.diameter(self.G),6) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:4,代码来源:test_distance_measures.py

示例10: test_radius_exception

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def test_radius_exception(self):
        G=networkx.Graph()
        G.add_edge(1,2)
        G.add_edge(3,4)
        assert_raises(networkx.NetworkXError, networkx.diameter, G) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:7,代码来源:test_distance_measures.py

示例11: test_diameter

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def test_diameter(self):
        assert_equal(networkx.diameter(self.G), 6) 
开发者ID:holzschu,项目名称:Carnets,代码行数:4,代码来源:test_distance_measures.py

示例12: test_bound_diameter

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def test_bound_diameter(self):
        assert_equal(networkx.diameter(self.G, usebounds=True), 6) 
开发者ID:holzschu,项目名称:Carnets,代码行数:4,代码来源:test_distance_measures.py

示例13: test_radius_exception

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def test_radius_exception(self):
        G = networkx.Graph()
        G.add_edge(1, 2)
        G.add_edge(3, 4)
        assert_raises(networkx.NetworkXError, networkx.diameter, G) 
开发者ID:holzschu,项目名称:Carnets,代码行数:7,代码来源:test_distance_measures.py

示例14: Graph_synthetic

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import diameter [as 别名]
def Graph_synthetic(seed):
    G = nx.Graph()
    np.random.seed(seed)
    base = np.repeat(np.eye(5), 20, axis=0)
    rand = np.random.randn(100, 5) * 0.05
    node_features = base + rand

    # # print('node features')
    # for i in range(node_features.shape[0]):
    #     print(np.around(node_features[i], decimals=4))

    node_distance_l1 = np.ones((node_features.shape[0], node_features.shape[0]))
    node_distance_np = np.zeros((node_features.shape[0], node_features.shape[0]))
    for i in range(node_features.shape[0]):
        for j in range(node_features.shape[0]):
            if i != j:
                node_distance_l1[i,j] = np.sum(np.abs(node_features[i] - node_features[j]))
                # print('node distance', node_distance_l1[i,j])
                node_distance_np[i, j] = 1 / np.sum(np.abs(node_features[i] - node_features[j]) ** 2)

    print('node distance max', np.max(node_distance_l1))
    print('node distance min', np.min(node_distance_l1))
    node_distance_np_sum = np.sum(node_distance_np, axis=1, keepdims=True)
    embedding_dist = node_distance_np / node_distance_np_sum

    # generate the graph
    average_degree = 9
    for i in range(node_features.shape[0]):
        for j in range(i + 1, embedding_dist.shape[0]):
            p = np.random.rand()
            if p < embedding_dist[i, j] * average_degree:
                G.add_edge(i, j)

    G.remove_nodes_from(nx.isolates(G))
    print('num of nodes', G.number_of_nodes())
    print('num of edges', 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', sum(G_deg_sum) / G.number_of_nodes())
    print('average path length', nx.average_shortest_path_length(G))
    print('diameter', nx.diameter(G))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient', sum(G_cluster) / len(G_cluster))
    print('Graph generation complete!')
    # node_features = np.concatenate((node_features, np.zeros((1,node_features.shape[1]))),axis=0)

    return G, node_features

# G = Graph_synthetic(10)



# return adj and features from a single graph 
开发者ID:JiaxuanYou,项目名称:graph-generation,代码行数:56,代码来源:data.py


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