當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。