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


Python networkx.all_pairs_dijkstra_path_length方法代码示例

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


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

示例1: test_all_pairs_shortest_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def test_all_pairs_shortest_path_length(self):
        ans = dict(nx.shortest_path_length(self.cycle))
        assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans, dict(nx.all_pairs_shortest_path_length(self.cycle)))
        ans = dict(nx.shortest_path_length(self.grid))
        assert_equal(ans[1][16], 6)
        # now with weights
        ans = dict(nx.shortest_path_length(self.cycle, weight='weight'))
        assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans, dict(nx.all_pairs_dijkstra_path_length(self.cycle)))
        ans = dict(nx.shortest_path_length(self.grid, weight='weight'))
        assert_equal(ans[1][16], 6)
        # weights and method specified
        ans = dict(nx.shortest_path_length(self.cycle, weight='weight',
                                           method='dijkstra'))
        assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans, dict(nx.all_pairs_dijkstra_path_length(self.cycle)))
        ans = dict(nx.shortest_path_length(self.cycle, weight='weight',
                                           method='bellman-ford'))
        assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        assert_equal(ans,
                     dict(nx.all_pairs_bellman_ford_path_length(self.cycle))) 
开发者ID:holzschu,项目名称:Carnets,代码行数:24,代码来源:test_generic.py

示例2: _compute_all_pairs

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def _compute_all_pairs(self, graph, weight=None, normalize=False):
        lengths = nx.all_pairs_dijkstra_path_length(graph, weight=weight)
        lengths = dict(lengths)
        max_length = max([max(lengths[i].values()) for i in lengths])
        if normalize:
            for i in lengths:
                for j in lengths[i]:
                    lengths[i][j] = float(lengths[i][j]) / max_length
        return lengths 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:11,代码来源:graph_layout.py

示例3: _get_unique_path_lengths

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def _get_unique_path_lengths(G, paths=None):
    """
    Compute the unique path lengths.

    Parameters
    ----------
    G (nx.Graph or DiGraph):
        a graph.

    paths (list):
        list of paths.

    Returns
    -------
    unique_path_lengths (list):
        sorted unique path lengths.
    """

    if paths is None:
        paths = list(nx.all_pairs_dijkstra_path_length(G))

    unique_path_lengths = set()

    for starting_node, dist_dict in paths:
        unique_path_lengths |= set(dist_dict.values())

    unique_path_lengths = sorted(list(unique_path_lengths))
    return unique_path_lengths 
开发者ID:netsiphd,项目名称:netrd,代码行数:30,代码来源:portrait_divergence.py

示例4: all_pairs_dijkstra_path_length

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

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

示例6: test_all_pairs_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def test_all_pairs_dijkstra_path_length(self):
        cycle = nx.cycle_graph(7)
        pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
        assert_equal(pl[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})

        cycle[1][2]['weight'] = 10
        pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
        assert_equal(pl[0], {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}) 
开发者ID:holzschu,项目名称:Carnets,代码行数:10,代码来源:test_weighted.py

示例7: test_all_pairs_dijkstra_path_length

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def test_all_pairs_dijkstra_path_length(self):
        cycle=nx.cycle_graph(7)
        pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
        assert_equal(pl[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})

        cycle[1][2]['weight'] = 10
        pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
        assert_equal(pl[0], {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}) 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:10,代码来源:test_weighted.py

示例8: test_all_pairs_shortest_path_length

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

示例9: define_neighborhoods

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def define_neighborhoods(self, **kwargs):

        # Overwriting the global settings, if required
        if 'node_distance_metric' in kwargs:
            self.node_distance_metric = kwargs['node_distance_metric']

        if 'neighborhood_radius_type' in kwargs:
            self.neighborhood_radius_type = kwargs['neighborhood_radius_type']

        if 'neighborhood_radius' in kwargs:
            self.neighborhood_radius = kwargs['neighborhood_radius']

        # Make sure that the settings are still valid
        self.validate_config()

        all_shortest_paths = {}
        neighborhoods = np.zeros([self.graph.number_of_nodes(), self.graph.number_of_nodes()], dtype=int)

        if self.node_distance_metric == 'euclidean':
            x = list(dict(self.graph.nodes.data('x')).values())
            nr = self.neighborhood_radius * (np.max(x) - np.min(x))

            x = np.matrix(self.graph.nodes.data('x'))[:, 1]
            y = np.matrix(self.graph.nodes.data('y'))[:, 1]

            node_coordinates = np.concatenate([x, y], axis=1)
            node_distances = squareform(pdist(node_coordinates, 'euclidean'))

            neighborhoods[node_distances < nr] = 1

        else:

            if self.node_distance_metric == 'shortpath_weighted_layout':
                # x = np.matrix(self.graph.nodes.data('x'))[:, 1]
                x = list(dict(self.graph.nodes.data('x')).values())
                nr = self.neighborhood_radius * (np.max(x) - np.min(x))
                all_shortest_paths = dict(nx.all_pairs_dijkstra_path_length(self.graph,
                                                                            weight='length', cutoff=nr))
            elif self.node_distance_metric == 'shortpath':
                nr = self.neighborhood_radius
                all_shortest_paths = dict(nx.all_pairs_dijkstra_path_length(self.graph, cutoff=nr))

            neighbors = [(s, t) for s in all_shortest_paths for t in all_shortest_paths[s].keys()]

            for i in neighbors:
                neighborhoods[i] = 1

        # Set diagonal to zero (a node is not part of its own neighborhood)
        # np.fill_diagonal(neighborhoods, 0)

        # Calculate the average neighborhood size
        num_neighbors = np.sum(neighborhoods, axis=1)

        if self.verbose:
            print('Node distance metric: %s' % self.node_distance_metric)
            print('Neighborhood definition: %.2f x %s' % (self.neighborhood_radius, self.neighborhood_radius_type))
            print('Number of nodes per neighborhood (mean +/- std): %.2f +/- %.2f' % (np.mean(num_neighbors), np.std(num_neighbors)))

        self.neighborhoods = neighborhoods 
开发者ID:baryshnikova-lab,项目名称:safepy,代码行数:61,代码来源:safe.py

示例10: weighted_portrait

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def weighted_portrait(G, paths=None, binedges=None):
    """Compute weighted portrait, using Dijkstra's algorithm for finding
    shortest paths.

    Parameters
    ----------
    G (nx.Graph or nx.DiGraph):
        a graph.

    paths (list):
        a list of all pairs of paths.

    binedges (list):
        sampled path lengths.

    Returns
    -------
    B (np.ndarray):
        a matrix :math:`B` where :math:`B_{i,j}` is the number of starting
        nodes in graph with :math:`j` nodes at distance :math:`d_i < d <
        d_{i+1}`.

    """

    # all pairs path lengths
    if paths is None:
        paths = list(nx.all_pairs_dijkstra_path_length(G))

    if binedges is None:
        unique_path_lengths = _get_unique_path_lengths(G, paths=paths)
        sampled_path_lengths = np.percentile(unique_path_lengths, np.arange(0, 101, 1))
    else:
        sampled_path_lengths = binedges

    UPL = np.array(sampled_path_lengths)

    l_s_v = []
    for i, (s, dist_dict) in enumerate(paths):
        distances = np.array(list(dist_dict.values()))
        s_v, e = np.histogram(distances, bins=UPL)
        l_s_v.append(s_v)

    M = np.array(l_s_v)

    B = np.zeros((len(UPL) - 1, G.number_of_nodes() + 1))

    for i in range(len(UPL) - 1):
        col = M[:, i]  # ith col = numbers of nodes at d_i <= distance < d_i+1

        for n, c in Counter(col).items():
            B[i, n] += c

    return B 
开发者ID:netsiphd,项目名称:netrd,代码行数:55,代码来源:portrait_divergence.py

示例11: all_pairs_dijkstra_path_length

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

示例12: run

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 别名]
def run(self):
        """
        Run the monte carlo simulation
        @return:
        """
        self.progress_signal.emit(0.0)

        n = len(self.grid.buses)

        if self.use_ptdf:
            self.progress_text.emit('Analyzing PTDF...')

            # the PTDF matrix will be scaled to 0, 1 to be able to train
            self.X_train = Normalizer().fit_transform(self.ptdf_results.flows_sensitivity_matrix)

            metric = 'euclidean'
        else:
            self.progress_text.emit('Exploring Dijkstra distances...')
            # explore
            g = self.build_weighted_graph()
            k = 0
            for i, distances_dict in nx.all_pairs_dijkstra_path_length(g):
                for j, d in distances_dict.items():
                    self.X_train[i, j] = d

                self.progress_signal.emit((k+1) / n * 100.0)
                k += 1
            metric = 'precomputed'

        # compute the sample sigma
        self.sigma = np.std(self.X_train)
        max_distance = self.sigma * self.sigmas

        # construct groups
        self.progress_text.emit('Building groups with DBSCAN...')

        # Compute DBSCAN
        model = DBSCAN(eps=max_distance,
                       min_samples=self.min_group_size,
                       metric=metric)

        db = model.fit(self.X_train)

        # get the labels that are greater than -1
        labels = list({i for i in db.labels_ if i > -1})
        self.groups_by_name = [list() for k in labels]
        self.groups_by_index = [list() for k in labels]

        # fill in the groups
        for i, (bus, group_idx) in enumerate(zip(self.grid.buses, db.labels_)):
            if group_idx > -1:
                self.groups_by_name[group_idx].append(bus.name)
                self.groups_by_index[group_idx].append(i)

        # display progress
        self.progress_text.emit('Done')
        self.progress_signal.emit(0.0)
        self.done_signal.emit() 
开发者ID:SanPen,项目名称:GridCal,代码行数:60,代码来源:topology_driver.py


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