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


Python networkx.shortest_path_length方法代码示例

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


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

示例1: calculate_max_depth_over_max_width

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def calculate_max_depth_over_max_width(comment_tree):
    comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())

    if len(comment_tree_nx) == 0:
        max_depth_over_max_width = 0.0
    else:
        node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)
        depth_to_nodecount = collections.defaultdict(int)

        for k, v in node_to_depth.items():
            depth_to_nodecount[v] += 1

        max_depth = max(node_to_depth.values())
        max_width = max(depth_to_nodecount.values())

        max_depth_over_max_width = max_depth/max_width

    return max_depth_over_max_width 
开发者ID:MKLab-ITI,项目名称:news-popularity-prediction,代码行数:20,代码来源:comment_tree.py

示例2: calculate_comment_tree_hirsch

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def calculate_comment_tree_hirsch(comment_tree):
    comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())

    if len(comment_tree_nx) == 0:
        comment_tree_hirsch = 0.0
    else:
        node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)

        depth_to_nodecount = collections.defaultdict(int)

        for k, v in node_to_depth.items():
            depth_to_nodecount[v] += 1

        comment_tree_hirsch = max(node_to_depth.values())
        while True:
            if depth_to_nodecount[comment_tree_hirsch] >= comment_tree_hirsch:
                break
            else:
                comment_tree_hirsch -= 1

    return comment_tree_hirsch 
开发者ID:MKLab-ITI,项目名称:news-popularity-prediction,代码行数:23,代码来源:comment_tree.py

示例3: get_topic_distance

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def get_topic_distance(self, sg, topic):
        """

        :param sg: an egocentric subgraph in networkx format
        :param topic: a networkx graph of nodes representing the topic
        :return: a dictionary of key node name and value distance as integer
        """
        distances = dict()

        # get all the distances
        for tnode in topic.nodes():
            if tnode in sg.nodes():
                distances[tnode] = nx.shortest_path_length(sg, source=tnode)

        # get the smallest distance per key
        min_dist = dict()
        for key in distances:
            for node in distances[key]:
                if node not in min_dist:
                    min_dist[node] = distances[key][node]
                elif distances[key][node] < min_dist[node]:
                    min_dist[node] = distances[key][node]

        # Return the dict
        return min_dist 
开发者ID:vz-risk,项目名称:Verum,代码行数:27,代码来源:neo4j.py

示例4: add_cycle_edges_by_path

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def add_cycle_edges_by_path(g,number_of_edges,path_length = 5):
	number = 0
	num_nodes = g.number_of_nodes()
	nodes = g.nodes()
	extra_edges = []
	while number < number_of_edges:
		u,v = np.random.randint(0,num_nodes,2)
		u = nodes[u]
		v = nodes[v]
		if nx.has_path(g,u,v):
			length = nx.shortest_path_length(g,source = u,target = v)
			if length <= path_length:
				extra_edges.append((v,u))
				number += 1
		if nx.has_path(g,v,u):
			length = nx.shortest_path_length(g,source = v,target = u)
			if length <= path_length:
				extra_edges.append((u,v))
				number += 1
	print("# extra edges added with path length <= %d: %d" % (path_length,len(extra_edges)))
	return extra_edges 
开发者ID:zhenv5,项目名称:breaking_cycles_in_noisy_hierarchies,代码行数:23,代码来源:introduce_cycles_to_DAG.py

示例5: distance

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def distance(self, type, node1, node2):
        if node1 in self.Dual[type].nodes() and node2 in self.Dual[type].nodes():
            return nx.shortest_path_length(self.Dual[type], node1, node2)
        elif node1 in self.Dual[type].nodes() and node2 not in self.Dual[type].nodes():
            node2 = self.External[type][node2]['measure']
            return nx.shortest_path_length(self.Dual[type], node1, node2) + 1
        elif node1 not in self.Dual[type].nodes() and node2 in self.Dual[type].nodes():
            node1 = self.External[type][node1]['measure']
            return nx.shortest_path_length(self.Dual[type], node1, node2) + 1
        else:
            node1 = self.External[type][node1]['measure']
            node2 = self.External[type][node2]['measure']
            return nx.shortest_path_length(self.Dual[type], node1, node2) + 2


    # Re-initializes Measurement qubits 
开发者ID:jacobmarks,项目名称:QTop,代码行数:18,代码来源:common.py

示例6: dendritic_graph

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

示例7: node_distance

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def node_distance(G):
    """
    Return an NxN matrix that consists of histograms of shortest path
    lengths between nodes i and j. This is useful for eventually taking
    information theoretic distances between the nodes.

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

    Returns
    -------
    out (np.ndarray): a matrix of binned node distance values.

    """

    N = G.number_of_nodes()
    a = np.zeros((N, N))

    dists = nx.shortest_path_length(G)
    for idx, row in enumerate(dists):
        counts = Counter(row[1].values())
        a[idx] = [counts[l] for l in range(1, N + 1)]

    return a / (N - 1) 
开发者ID:netsiphd,项目名称:netrd,代码行数:27,代码来源:dmeasure.py

示例8: furtherest_node_miles

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def furtherest_node_miles(self, *args):
        """
        Returns the maximum eccentricity from the source, in miles.

        .. warning:: Not working....
        """
        if args:
            if len(args) == 1:
                _net = args[0]
                _src = self.source
            elif len(args) == 2:
                _net, _src = args
        else:
            _net = self.G.graph
            _src = self.source
        dist = {}
        _net = _net.copy()
        if not _net.has_node(_src):
            _sp = nx.shortest_path(self.G.graph, _src, list(_net.nodes())[0])
            for n1, n2 in zip(_sp[:-1], _sp[1:]):
                _net.add_edge(n1, n2, length=self.G.graph[n1][n2]["length"])
        for node in _net.nodes():
            dist[node] = nx.shortest_path_length(_net, _src, node, weight="length")
        return np.max(list(dist.values())) * 0.000621371  # Convert length to miles 
开发者ID:NREL,项目名称:ditto,代码行数:26,代码来源:network_analysis.py

示例9: bell_reweighting

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def bell_reweighting(tree, root, sublinear=False):
    # convert the hierarchy to a tree if make_bfs_tree is true

    distance_by_target = nx.shortest_path_length(tree, source=root)

    level_count = defaultdict(int)
    for val in distance_by_target.values():
        level_count[val] += 1

    for edge in tree.edges():
        parent, child = edge
        if sublinear:
            # use smoothed logarithm
            tree[parent][child]['weight'] = 1.0 / log(1 + level_count[distance_by_target[child]], 10)
        else:
            tree[parent][child]['weight'] = 1.0 / level_count[distance_by_target[child]]

    return tree 
开发者ID:quadflor,项目名称:Quadflor,代码行数:20,代码来源:SpreadingActivation.py

示例10: find_best_mapping

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def find_best_mapping(alignments, query_length,  parent, coords_to_exclude, children_dict, previous_gene_start, copy_tag):
    children = children_dict[parent.id]
    children_coords = liftoff_utils.merge_children_intervals(children)
    node_dict, aln_graph = intialize_graph()
    head_nodes = add_single_alignments(node_dict, aln_graph, alignments, children_coords, parent, coords_to_exclude,
                                       previous_gene_start)
    chain_alignments(head_nodes, node_dict, aln_graph, coords_to_exclude, parent, children_coords)
    add_target_node(aln_graph, node_dict, query_length, children_coords, parent)
    shortest_path = nx.shortest_path(aln_graph, source=0, target=len(node_dict) - 1,
                                     weight=lambda u, v, d: get_weight(u, v, d, aln_graph))
    shortest_path_weight = nx.shortest_path_length(aln_graph, source=0, target=len(node_dict) - 1,
                                                   weight=lambda u, v, d: get_weight(u, v, d, aln_graph))

    shortest_path_nodes = []
    for i in range  (1,len(shortest_path)-1):
        node_name = shortest_path[i]
        shortest_path_nodes.append(node_dict[node_name])
    if len(shortest_path_nodes) == 0:
        return {}, shortest_path_weight, 0,0

    mapped_children, alignment_coverage, seq_id = convert_all_children_coords(shortest_path_nodes, children, parent, copy_tag)
    return mapped_children, shortest_path_weight, alignment_coverage, seq_id 
开发者ID:agshumate,项目名称:Liftoff,代码行数:24,代码来源:find_best_mapping.py

示例11: descendants

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def descendants(G, source):
    """Return all nodes reachable from `source` in G.

    Parameters
    ----------
    G : NetworkX DiGraph
    source : node in G

    Returns
    -------
    des : set()
        The descendants of source in G
    """
    if not G.has_node(source):
        raise nx.NetworkXError("The node %s is not in the graph." % source)
    des = set(nx.shortest_path_length(G, source=source).keys()) - set([source])
    return des 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:19,代码来源:dag.py

示例12: ancestors

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def ancestors(G, source):
    """Return all nodes having a path to `source` in G.

    Parameters
    ----------
    G : NetworkX DiGraph
    source : node in G

    Returns
    -------
    ancestors : set()
        The ancestors of source in G
    """
    if not G.has_node(source):
        raise nx.NetworkXError("The node %s is not in the graph." % source)
    anc = set(nx.shortest_path_length(G, target=source).keys()) - set([source])
    return anc 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:19,代码来源:dag.py

示例13: test_eccentricity

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def test_eccentricity(self):
        assert_equal(networkx.eccentricity(self.G,1),6)
        e=networkx.eccentricity(self.G)
        assert_equal(e[1],6)
        sp=networkx.shortest_path_length(self.G)
        e=networkx.eccentricity(self.G,sp=sp)
        assert_equal(e[1],6)
        e=networkx.eccentricity(self.G,v=1)
        assert_equal(e,6)
        e=networkx.eccentricity(self.G,v=[1,1])  #This behavior changed in version 1.8 (ticket #739)
        assert_equal(e[1],6)
        e=networkx.eccentricity(self.G,v=[1,2])
        assert_equal(e[1],6)
        # test against graph with one node
        G=networkx.path_graph(1)
        e=networkx.eccentricity(G)
        assert_equal(e[0],0)
        e=networkx.eccentricity(G,v=0)
        assert_equal(e,0)
        assert_raises(networkx.NetworkXError, networkx.eccentricity, G, 1)
        # test against empty graph
        G=networkx.empty_graph()
        e=networkx.eccentricity(G)
        assert_equal(e,{}) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:26,代码来源:test_distance_measures.py

示例14: descendants

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def descendants(G, source):
    """Returns all nodes reachable from `source` in `G`.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)
    source : node in `G`

    Returns
    -------
    set()
        The descendants of `source` in `G`
    """
    if not G.has_node(source):
        raise nx.NetworkXError("The node %s is not in the graph." % source)
    des = set(n for n, d in nx.shortest_path_length(G, source=source).items())
    return des - {source} 
开发者ID:holzschu,项目名称:Carnets,代码行数:20,代码来源:dag.py

示例15: ancestors

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import shortest_path_length [as 别名]
def ancestors(G, source):
    """Returns all nodes having a path to `source` in `G`.

    Parameters
    ----------
    G : NetworkX DiGraph
        A directed acyclic graph (DAG)
    source : node in `G`

    Returns
    -------
    set()
        The ancestors of source in G
    """
    if not G.has_node(source):
        raise nx.NetworkXError("The node %s is not in the graph." % source)
    anc = set(n for n, d in nx.shortest_path_length(G, target=source).items())
    return anc - {source} 
开发者ID:holzschu,项目名称:Carnets,代码行数:20,代码来源:dag.py


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