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


Python networkx.single_source_dijkstra_path_length方法代码示例

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


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

示例1: neighborhoods_weights_to_root

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def neighborhoods_weights_to_root(adjacency, sequence, size):
    def _neighborhoods_weights_to_root(adjacency, sequence):
        graph = nx.from_numpy_matrix(adjacency)

        neighborhoods = np.zeros((sequence.shape[0], size), dtype=np.int32)
        neighborhoods.fill(-1)

        for i in xrange(0, sequence.shape[0]):
            n = sequence[i]
            if n < 0:
                break

            shortest = nx.single_source_dijkstra_path_length(graph, n).items()
            shortest = sorted(shortest, key=lambda v: v[1])
            shortest = shortest[:size]

            for j in xrange(0, min(size, len(shortest))):
                neighborhoods[i][j] = shortest[j][0]

        return neighborhoods

    return tf.py_func(_neighborhoods_weights_to_root, [adjacency, sequence],
                      tf.int32, stateful=False,
                      name='neighborhoods_weights_to_root') 
开发者ID:rusty1s,项目名称:graph-based-image-classification,代码行数:26,代码来源:neighborhood_assembly.py

示例2: _straightness_centrality

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def _straightness_centrality(G, weight, normalized=True):
    """
    Calculates straightness centrality.
    """
    straightness_centrality = {}

    for n in G.nodes():
        straightness = 0
        sp = nx.single_source_dijkstra_path_length(G, n, weight=weight)

        if len(sp) > 0 and len(G) > 1:
            for target in sp:
                if n != target:
                    network_dist = sp[target]
                    euclidean_dist = _euclidean(n, target)
                    straightness = straightness + (euclidean_dist / network_dist)
            straightness_centrality[n] = straightness * (1.0 / (len(G) - 1.0))
            # normalize to number of nodes-1 in connected part
            if normalized:
                if len(sp) > 1:
                    s = (len(G) - 1.0) / (len(sp) - 1.0)
                    straightness_centrality[n] *= s
                else:
                    straightness_centrality[n] = 0
        else:
            straightness_centrality[n] = 0.0
    return straightness_centrality 
开发者ID:martinfleis,项目名称:momepy,代码行数:29,代码来源:graph.py

示例3: weiner_index

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def weiner_index(G, weight=None):
    # compute sum of distances between all node pairs
    # (with optional weights)
    weiner=0.0
    if weight is None:
        for n in G:
            path_length=nx.single_source_shortest_path_length(G,n)
            weiner+=sum(path_length.values())
    else:
        for n in G:
            path_length=nx.single_source_dijkstra_path_length(G,
                    n,weight=weight)
            weiner+=sum(path_length.values())
    return weiner 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:16,代码来源:vitality.py

示例4: all_pairs_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
    """ Compute shortest path lengths between all nodes in a weighted graph.

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

    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
    -------
    distance : dictionary
       Dictionary, keyed by source and target, of shortest path lengths.

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

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

    The dictionary returned only has keys for reachable node pairs.
    """
    length = single_source_dijkstra_path_length
    # TODO This can be trivially parallelized.
    return {n: length(G, n, cutoff=cutoff, weight=weight) for n in G} 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:39,代码来源:weighted.py

示例5: test_single_source_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def test_single_source_dijkstra_path_length(self):
        pl = nx.single_source_dijkstra_path_length
        assert_equal(pl(self.MXG4, 0)[2], 4)
        spl = pl(self.MXG4, 0, cutoff=2)
        assert_false(2 in spl) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:7,代码来源:test_weighted.py

示例6: test_negative_edge_cycle

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

示例7: test_single_source_shortest_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def test_single_source_shortest_path_length(self):
        l=nx.shortest_path_length(self.cycle,0)
        assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        assert_equal(l,nx.single_source_shortest_path_length(self.cycle,0))
        l=nx.shortest_path_length(self.grid,1)
        assert_equal(l[16],6)
        # now with weights
        l=nx.shortest_path_length(self.cycle,0,weight='weight')
        assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        assert_equal(l,nx.single_source_dijkstra_path_length(self.cycle,0))
        l=nx.shortest_path_length(self.grid,1,weight='weight')
        assert_equal(l[16],6) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:14,代码来源:test_generic.py

示例8: test_absent_source

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

示例9: test_single_source_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def test_single_source_dijkstra_path_length(self):
        pl = nx.single_source_dijkstra_path_length
        assert_equal(dict(pl(self.MXG4, 0))[2], 4)
        spl = pl(self.MXG4, 0, cutoff=2)
        assert_false(2 in spl) 
开发者ID:holzschu,项目名称:Carnets,代码行数:7,代码来源:test_weighted.py

示例10: test_single_source_shortest_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def test_single_source_shortest_path_length(self):
        l = dict(nx.shortest_path_length(self.cycle,0))
        assert_equal(l,{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        assert_equal(l, dict(nx.single_source_shortest_path_length(self.cycle,0)))
        l = dict(nx.shortest_path_length(self.grid,1))
        assert_equal(l[16],6)
        # now with weights
        l = dict(nx.shortest_path_length(self.cycle, 0, weight='weight'))
        assert_equal(l, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(l, dict(nx.single_source_dijkstra_path_length(
            self.cycle, 0)))
        l = dict(nx.shortest_path_length(self.grid, 1, weight='weight'))
        assert_equal(l[16], 6) 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:15,代码来源:test_generic.py

示例11: neighborhoods_grid_spiral

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def neighborhoods_grid_spiral(adjacency, sequence, size):
    def _neighborhoods_grid_spiral(adjacency, sequence):
        graph = nx.from_numpy_matrix(adjacency)

        neighborhoods = np.zeros((sequence.shape[0], size), dtype=np.int32)
        neighborhoods.fill(-1)

        # Note: This method just works properly on planar graphs where nodes
        # are placed in a grid like layout and are weighted by distance.
        #
        # Add root to arr => [root]
        # Find nearest neighbor x to root
        # Add x => arr = [root, x]
        # Find nearest neighbor y with n(x, y) and min w(x,y) + w(root, y)
        # that is not already in arr.
        # set x = y
        # repeat until arr.length == size

        for i in xrange(0, sequence.shape[0]):
            root = sequence[i]
            if root < 0:
                break

            # Add root node to the beginning of the neighborhood.
            neighborhoods[i][0] = root
            x = root

            ws = nx.single_source_dijkstra_path_length(graph, root)
            ws = list(ws.items())

            for j in xrange(1, size):
                if x == -1:
                    break

                y = -1
                weight = float('inf')
                for _, n, d, in graph.edges_iter(x, data=True):
                    if n in neighborhoods[i]:
                        continue

                    w = ws[n][1] + d['weight']
                    if w < weight:
                        y = n
                        weight = w

                neighborhoods[i][j] = y
                x = y

        return neighborhoods

    return tf.py_func(_neighborhoods_grid_spiral, [adjacency, sequence],
                      tf.int32, stateful=False,
                      name='neighborhoods_grid_spiral') 
开发者ID:rusty1s,项目名称:graph-based-image-classification,代码行数:55,代码来源:neighborhood_assembly.py

示例12: average_shortest_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def average_shortest_path_length(G, weight=None):
    r"""Return the average shortest path length.

    The average shortest path length is

    .. math::

       a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}

    where `V` is the set of nodes in `G`,
    `d(s, t)` is the shortest path from `s` to `t`,
    and `n` is the number of nodes in `G`.

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

    weight : None or string, optional (default = None)
       If None, every edge has weight/distance/cost 1.
       If a string, use this edge attribute as the edge weight.
       Any edge attribute not present defaults to 1.

    Raises
    ------
    NetworkXError:
       if the graph is not connected.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.average_shortest_path_length(G))
    2.0

    For disconnected graphs you can compute the average shortest path
    length for each component:
    >>> G=nx.Graph([(1,2),(3,4)])
    >>> for g in nx.connected_component_subgraphs(G):
    ...     print(nx.average_shortest_path_length(g))
    1.0
    1.0

    """
    if G.is_directed():
        if not nx.is_weakly_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    else:
        if not nx.is_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    avg=0.0
    if weight is None:
        for node in G:
            path_length=nx.single_source_shortest_path_length(G, node)
            avg += sum(path_length.values())
    else:
        for node in G:
            path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight)
            avg += sum(path_length.values())
    n=len(G)
    return avg/(n*(n-1)) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:61,代码来源:generic.py

示例13: dijkstra_path_length

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

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

    source : node label
       starting node for path

    target : node label
       ending node for path

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

    Returns
    -------
    length : number
        Shortest path length.

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

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.dijkstra_path_length(G,0,4))
    4

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

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

示例14: single_source_dijkstra_path_length

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

示例15: all_pairs_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import single_source_dijkstra_path_length [as 别名]
def all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
    """Compute shortest path lengths between all nodes in a weighted graph.

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

    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
    -------
    distance : iterator
        (source, dictionary) iterator with dictionary keyed by target and
        shortest path length as the key value.

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

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

    The dictionary returned only has keys for reachable node pairs.
    """
    length = single_source_dijkstra_path_length
    for n in G:
        yield (n, length(G, n, cutoff=cutoff, weight=weight)) 
开发者ID:holzschu,项目名称:Carnets,代码行数:57,代码来源:weighted.py


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