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


Python networkx.single_source_dijkstra方法代码示例

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


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

示例1: get_path_two

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def get_path_two(start,end):
    v1 = start.split('-')
    v2 = end.split('-')

    if v1[1] == 'B':
        or1 = 'REV'
    else:
        or1 = 'FOW'

    if v2[1] == 'B':
        or2 = 'FOW'
    else:
        or2 = 'REV'
    start = v1[0]+'$'+or1
    end = v2[0] + '$'+or2
    paths = nx.single_source_dijkstra(OVl_G,source=start,target=end)

    paths = paths[1]
    path = []
    if end in paths:
        path = paths[end]
    else:
        return "NO PATH FOUND"
    ret = []
    for node in path:
        n = node.split('$')
        if n[1] == 'REV':
            ret.append(n[0]+'-E')
            ret.append(n[0]+'-B')
        else:
            ret.append(n[0]+'-B')
            ret.append(n[0]+'-E')
    return ret 
开发者ID:marbl,项目名称:SALSA,代码行数:35,代码来源:layout_unitigs.py

示例2: test_negative_edge_cycle

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def test_negative_edge_cycle(self):
        G = nx.cycle_graph(5, create_using=nx.DiGraph())
        assert_equal(nx.negative_edge_cycle(G), False)
        G.add_edge(8, 9, weight=-7)
        G.add_edge(9, 8, weight=3)
        graph_size = len(G)
        assert_equal(nx.negative_edge_cycle(G), True)
        assert_equal(graph_size, len(G))
        assert_raises(ValueError, nx.single_source_dijkstra_path_length, G, 8)
        assert_raises(ValueError, nx.single_source_dijkstra, G, 8)
        assert_raises(ValueError, nx.dijkstra_predecessor_and_distance, G, 8)
        G.add_edge(9, 10)
        assert_raises(ValueError, nx.bidirectional_dijkstra, G, 8, 10) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:15,代码来源:test_weighted.py

示例3: test_absent_source

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def test_absent_source(self):
        # the check is in _dijkstra_multisource, but this will provide
        # regression testing against later changes to any of the "client"
        # Dijkstra or Bellman-Ford functions
        G = nx.path_graph(2)
        for fn in (nx.dijkstra_path,
                   nx.dijkstra_path_length,
                   nx.single_source_dijkstra_path,
                   nx.single_source_dijkstra_path_length,
                   nx.single_source_dijkstra,
                   nx.dijkstra_predecessor_and_distance,):
            assert_raises(nx.NodeNotFound, fn, G, 3, 0) 
开发者ID:holzschu,项目名称:Carnets,代码行数:14,代码来源:test_weighted.py

示例4: dijkstra_path

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def dijkstra_path(G, source, target, weight='weight'):
    """Returns the shortest path from source to target in a weighted graph G.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node

    target : node
       Ending node

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight

    Returns
    -------
    path : list
       List of nodes in a shortest path.

    Raises
    ------
    NetworkXNoPath
       If no path exists between source and target.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.dijkstra_path(G,0,4))
    [0, 1, 2, 3, 4]

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    bidirectional_dijkstra()
    """
    (length, path) = single_source_dijkstra(G, source, target=target,
                                            weight=weight)
    try:
        return path[target]
    except KeyError:
        raise nx.NetworkXNoPath(
            "node %s not reachable from %s" % (source, target)) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:50,代码来源:weighted.py

示例5: single_source_dijkstra_path

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_dijkstra_path(G, source, cutoff=None, weight='weight'):
    """Compute shortest path between source and all other reachable
    nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight

    cutoff : integer or float, optional
       Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    paths : dictionary
       Dictionary of shortest path lengths keyed by target.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> path=nx.single_source_dijkstra_path(G,0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    single_source_dijkstra()

    """
    (length, path) = single_source_dijkstra(
        G, source, cutoff=cutoff, weight=weight)
    return path 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:44,代码来源:weighted.py

示例6: single_source_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_dijkstra_path_length(G, source, cutoff=None,
                                       weight='weight'):
    """Compute the shortest path length between source and all other
    reachable nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node label
       Starting node for path

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight.

    cutoff : integer or float, optional
       Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    length : dictionary
       Dictionary of shortest lengths keyed by target.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> length=nx.single_source_dijkstra_path_length(G,0)
    >>> length[4]
    4
    >>> print(length)
    {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    single_source_dijkstra()

    """
    if G.is_multigraph():
        get_weight = lambda u, v, data: min(
            eattr.get(weight, 1) for eattr in data.values())
    else:
        get_weight = lambda u, v, data: data.get(weight, 1)

    return _dijkstra(G, source, get_weight, cutoff=cutoff) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:51,代码来源:weighted.py

示例7: test_dijkstra

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def test_dijkstra(self):
        (D, P) = nx.single_source_dijkstra(self.XG, 's')
        validate_path(self.XG, 's', 'v', 9, P['v'])
        assert_equal(D['v'], 9)

        validate_path(
            self.XG, 's', 'v', 9, nx.single_source_dijkstra_path(self.XG, 's')['v'])
        assert_equal(
            nx.single_source_dijkstra_path_length(self.XG, 's')['v'], 9)

        validate_path(
            self.XG, 's', 'v', 9, nx.single_source_dijkstra(self.XG, 's')[1]['v'])
        validate_path(
            self.MXG, 's', 'v', 9, nx.single_source_dijkstra_path(self.MXG, 's')['v'])

        GG = self.XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight'] = 2
        (D, P) = nx.single_source_dijkstra(GG, 's')
        validate_path(GG, 's', 'v', 8, P['v'])
        assert_equal(D['v'], 8)     # uses lower weight of 2 on u<->x edge
        validate_path(GG, 's', 'v', 8, nx.dijkstra_path(GG, 's', 'v'))
        assert_equal(nx.dijkstra_path_length(GG, 's', 'v'), 8)

        validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3))
        validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3))
        assert_equal(nx.dijkstra_path_length(self.XG3, 0, 3), 15)
        validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2))
        assert_equal(nx.dijkstra_path_length(self.XG4, 0, 2), 4)
        validate_path(self.MXG4, 0, 2, 4, nx.dijkstra_path(self.MXG4, 0, 2))
        validate_path(
            self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's', 'v')[1]['v'])
        validate_path(
            self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's')[1]['v'])

        validate_path(self.G, 's', 'v', 2, nx.dijkstra_path(self.G, 's', 'v'))
        assert_equal(nx.dijkstra_path_length(self.G, 's', 'v'), 2)

        # NetworkXError: node s not reachable from moon
        assert_raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, 's', 'moon')
        assert_raises(
            nx.NetworkXNoPath, nx.dijkstra_path_length, self.G, 's', 'moon')

        validate_path(self.cycle, 0, 3, 3, nx.dijkstra_path(self.cycle, 0, 3))
        validate_path(self.cycle, 0, 4, 3, nx.dijkstra_path(self.cycle, 0, 4))

        assert_equal(
            nx.single_source_dijkstra(self.cycle, 0, 0), ({0: 0}, {0: [0]})) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:51,代码来源:test_weighted.py

示例8: single_source_bellman_ford_path

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_bellman_ford_path(G, source, weight='weight'):
    """Compute shortest path between source and all other reachable
    nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight

    Returns
    -------
    paths : dictionary
       Dictionary of shortest path lengths keyed by target.

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> path=nx.single_source_bellman_ford_path(G,0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    single_source_dijkstra(), single_source_bellman_ford()

    """
    (length, path) = single_source_bellman_ford(
        G, source, weight=weight)
    return path 
开发者ID:holzschu,项目名称:Carnets,代码行数:46,代码来源:weighted.py

示例9: single_source_bellman_ford_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_bellman_ford_path_length(G, source, weight='weight'):
    """Compute the shortest path length between source and all other
    reachable nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node label
       Starting node for path

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight.

    Returns
    -------
    length : iterator
        (target, shortest path length) iterator

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = dict(nx.single_source_bellman_ford_path_length(G, 0))
    >>> length[4]
    4
    >>> for node in [0, 1, 2, 3, 4]:
    ...     print('{}: {}'.format(node, length[node]))
    0: 0
    1: 1
    2: 2
    3: 3
    4: 4

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    single_source_dijkstra(), single_source_bellman_ford()

    """
    weight = _weight_function(G, weight)
    return _bellman_ford(G, [source], weight) 
开发者ID:holzschu,项目名称:Carnets,代码行数:52,代码来源:weighted.py

示例10: test_dijkstra

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def test_dijkstra(self):
        (D, P) = nx.single_source_dijkstra(self.XG, 's')
        validate_path(self.XG, 's', 'v', 9, P['v'])
        assert_equal(D['v'], 9)

        validate_path(
            self.XG, 's', 'v', 9, nx.single_source_dijkstra_path(self.XG, 's')['v'])
        assert_equal(dict(
            nx.single_source_dijkstra_path_length(self.XG, 's'))['v'], 9)

        validate_path(
            self.XG, 's', 'v', 9, nx.single_source_dijkstra(self.XG, 's')[1]['v'])
        validate_path(
            self.MXG, 's', 'v', 9, nx.single_source_dijkstra_path(self.MXG, 's')['v'])

        GG = self.XG.to_undirected()
        # make sure we get lower weight
        # to_undirected might choose either edge with weight 2 or weight 3
        GG['u']['x']['weight'] = 2
        (D, P) = nx.single_source_dijkstra(GG, 's')
        validate_path(GG, 's', 'v', 8, P['v'])
        assert_equal(D['v'], 8)     # uses lower weight of 2 on u<->x edge
        validate_path(GG, 's', 'v', 8, nx.dijkstra_path(GG, 's', 'v'))
        assert_equal(nx.dijkstra_path_length(GG, 's', 'v'), 8)

        validate_path(self.XG2, 1, 3, 4, nx.dijkstra_path(self.XG2, 1, 3))
        validate_path(self.XG3, 0, 3, 15, nx.dijkstra_path(self.XG3, 0, 3))
        assert_equal(nx.dijkstra_path_length(self.XG3, 0, 3), 15)
        validate_path(self.XG4, 0, 2, 4, nx.dijkstra_path(self.XG4, 0, 2))
        assert_equal(nx.dijkstra_path_length(self.XG4, 0, 2), 4)
        validate_path(self.MXG4, 0, 2, 4, nx.dijkstra_path(self.MXG4, 0, 2))
        validate_path(
            self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's', 'v')[1])
        validate_path(
            self.G, 's', 'v', 2, nx.single_source_dijkstra(self.G, 's')[1]['v'])

        validate_path(self.G, 's', 'v', 2, nx.dijkstra_path(self.G, 's', 'v'))
        assert_equal(nx.dijkstra_path_length(self.G, 's', 'v'), 2)

        # NetworkXError: node s not reachable from moon
        assert_raises(nx.NetworkXNoPath, nx.dijkstra_path, self.G, 's', 'moon')
        assert_raises(
            nx.NetworkXNoPath, nx.dijkstra_path_length, self.G, 's', 'moon')

        validate_path(self.cycle, 0, 3, 3, nx.dijkstra_path(self.cycle, 0, 3))
        validate_path(self.cycle, 0, 4, 3, nx.dijkstra_path(self.cycle, 0, 4))

        assert_equal(nx.single_source_dijkstra(self.cycle, 0, 0), (0, [0])) 
开发者ID:holzschu,项目名称:Carnets,代码行数:50,代码来源:test_weighted.py

示例11: ego_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
    """Returns induced subgraph of neighbors centered at node n within
    a given radius.

    Parameters
    ----------
    G : graph
      A NetworkX Graph or DiGraph

    n : node
      A single node

    radius : number, optional
      Include all neighbors of distance<=radius from n.

    center : bool, optional
      If False, do not include center node in graph

    undirected : bool, optional
      If True use both in- and out-neighbors of directed graphs.

    distance : key, optional
      Use specified edge data key as distance.  For example, setting
      distance='weight' will use the edge weight to measure the
      distance from the node n.

    Notes
    -----
    For directed graphs D this produces the "out" neighborhood
    or successors.  If you want the neighborhood of predecessors
    first reverse the graph with D.reverse().  If you want both
    directions use the keyword argument undirected=True.

    Node, edge, and graph attributes are copied to the returned subgraph.
    """
    if undirected:
        if distance is not None:
            sp, _ = nx.single_source_dijkstra(G.to_undirected(),
                                              n, cutoff=radius,
                                              weight=distance)
        else:
            sp = dict(nx.single_source_shortest_path_length(G.to_undirected(),
                                                            n, cutoff=radius))
    else:
        if distance is not None:
            sp, _ = nx.single_source_dijkstra(G,
                                              n, cutoff=radius,
                                              weight=distance)
        else:
            sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))

    H = G.subgraph(sp).copy()
    if not center:
        H.remove_node(n)
    return H 
开发者ID:holzschu,项目名称:Carnets,代码行数:57,代码来源:ego.py

示例12: single_source_dijkstra_path

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_dijkstra_path(G, source, cutoff=None, weight='weight'):
    """Find shortest weighted paths in G from a source node.

    Compute shortest path between source and all other reachable
    nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    cutoff : integer or float, optional
       Depth to stop the search. Only return paths with length <= cutoff.

    weight : string or function
       If this is a string, then edge weights will be accessed via the
       edge attribute with this key (that is, the weight of the edge
       joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
       such edge attribute exists, the weight of the edge is assumed to
       be one.

       If this is a function, the weight of an edge is the value
       returned by the function. The function must accept exactly three
       positional arguments: the two endpoints of an edge and the
       dictionary of edge attributes for that edge. The function must
       return a number.

    Returns
    -------
    paths : dictionary
       Dictionary of shortest path lengths keyed by target.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> path=nx.single_source_dijkstra_path(G,0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    The weight function can be used to hide edges by returning None.
    So ``weight = lambda u, v, d: 1 if d['color']=="red" else None``
    will find the shortest red path.

    See Also
    --------
    single_source_dijkstra(), single_source_bellman_ford()

    """
    return multi_source_dijkstra_path(G, {source}, cutoff=cutoff,
                                      weight=weight) 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:59,代码来源:weighted.py

示例13: single_source_bellman_ford_path

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_bellman_ford_path(G, source, cutoff=None, weight='weight'):
    """Compute shortest path between source and all other reachable
    nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight

    cutoff : integer or float, optional
       Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    paths : dictionary
       Dictionary of shortest path lengths keyed by target.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> path=nx.single_source_bellman_ford_path(G,0)
    >>> path[4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    single_source_dijkstra(), single_source_bellman_ford()

    """
    (length, path) = single_source_bellman_ford(
        G, source, cutoff=cutoff, weight=weight)
    return path 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:44,代码来源:weighted.py

示例14: single_source_bellman_ford_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra [as 别名]
def single_source_bellman_ford_path_length(G, source,
                                           cutoff=None, weight='weight'):
    """Compute the shortest path length between source and all other
    reachable nodes for a weighted graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node label
       Starting node for path

    weight: string, optional (default='weight')
       Edge data key corresponding to the edge weight.

    cutoff : integer or float, optional
       Depth to stop the search. Only paths of length <= cutoff are returned.

    Returns
    -------
    length : iterator
        (target, shortest path length) iterator

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = dict(nx.single_source_bellman_ford_path_length(G, 0))
    >>> length[4]
    4
    >>> for node in [0, 1, 2, 3, 4]:
    ...     print('{}: {}'.format(node, length[node]))
    0: 0
    1: 1
    2: 2
    3: 3
    4: 4

    Notes
    -----
    Edge weight attributes must be numerical.
    Distances are calculated as sums of weighted edges traversed.

    See Also
    --------
    single_source_dijkstra(), single_source_bellman_ford()

    """
    weight = _weight_function(G, weight)
    return _bellman_ford(G, [source], weight, cutoff=cutoff) 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:51,代码来源:weighted.py


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