Python networkx.all_pairs_shortest_path_length() Examples

The following are 14 code examples of networkx.all_pairs_shortest_path_length(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: coupling.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def _compute_distance_matrix(self):
        """Compute the full distance matrix on pairs of nodes.

        The distance map self._dist_matrix is computed from the graph using
        all_pairs_shortest_path_length.
        """
        if not self.is_connected():
            raise CouplingError("coupling graph not connected")
        lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True))
        lengths = dict(lengths)
        size = len(lengths)
        cmap = np.zeros((size, size))
        for idx in range(size):
            cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter(
                lengths[idx].values(), dtype=int)
        self._dist_matrix = cmap 
Example #2
Source File: dmeasure.py    From netrd with MIT License 6 votes vote down vote up
def shortest_path_matrix(G):
    """
    Return a matrix of pairwise shortest path lengths between nodes.

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

    Returns
    -------
    pmat (np.ndarray): a matrix of shortest paths between nodes in G

    """

    N = G.number_of_nodes()
    pmat = np.zeros((N, N)) + N

    paths = nx.all_pairs_shortest_path_length(G)
    for node_i, node_ij in paths:
        for node_j, length_ij in node_ij.items():
            pmat[node_i, node_j] = length_ij

    pmat[pmat == np.inf] = N

    return pmat 
Example #3
Source File: utils.py    From P-GNN with MIT License 6 votes vote down vote up
def precompute_dist_data(edge_index, num_nodes, approximate=0):
        '''
        Here dist is 1/real_dist, higher actually means closer, 0 means disconnected
        :return:
        '''
        graph = nx.Graph()
        edge_list = edge_index.transpose(1,0).tolist()
        graph.add_edges_from(edge_list)

        n = num_nodes
        dists_array = np.zeros((n, n))
        # dists_dict = nx.all_pairs_shortest_path_length(graph,cutoff=approximate if approximate>0 else None)
        # dists_dict = {c[0]: c[1] for c in dists_dict}
        dists_dict = all_pairs_shortest_path_length_parallel(graph,cutoff=approximate if approximate>0 else None)
        for i, node_i in enumerate(graph.nodes()):
            shortest_dist = dists_dict[node_i]
            for j, node_j in enumerate(graph.nodes()):
                dist = shortest_dist.get(node_j, -1)
                if dist!=-1:
                    # dists_array[i, j] = 1 / (dist + 1)
                    dists_array[node_i, node_j] = 1 / (dist + 1)
        return dists_array 
Example #4
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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))) 
Example #5
Source File: calc_network.py    From MD-TASK with GNU General Public License v3.0 5 votes vote down vote up
def calc_shortest_path(protein_graph, prefix, generate_plots=True, xmgrace=False):
    num_nodes = len(protein_graph.nodes())
    nodes_axis = range(1, num_nodes + 1)

    path_dict = nx.all_pairs_shortest_path_length(protein_graph)
    dj_path_matrix = np.zeros((num_nodes, num_nodes))

    for i in range(num_nodes):
        for j in range(num_nodes):
            try:
                dj_path_matrix[i,j] = path_dict[i][j]
            except KeyError as ke:
                raise nx.exception.NetworkXNoPath("\nERROR::type=orphan_node:message=No link between %d and %d:exception=%s\n" % (i, j, str(ke)))

    np.savetxt("%s_L.dat" % prefix, dj_path_matrix)

    avg_L_per_node = np.sum(dj_path_matrix, axis=0)/(num_nodes - 1)

    if generate_plots:
        plt.plot(nodes_axis, avg_L_per_node)
        plt.title("%s L" % prefix, fontsize=18)
        plt.xlabel('Node Indices', fontsize=16)
        plt.ylabel('L', fontsize=16)
        plt.savefig("%s_L.png" % prefix, dpi=300, bbox_inches='tight')
        plt.close()

    avg_L_per_node = avg_L_per_node.reshape(1, num_nodes)
    np.savetxt("%s_avg_L.dat" % prefix, avg_L_per_node)
    if xmgrace:
        dat2xmgrace(avg_L_per_node, prefix, "L", traj=traj)

    return dj_path_matrix 
Example #6
Source File: cfg.py    From polyfile with Apache License 2.0 5 votes vote down vote up
def path_length(self, from_node, to_node):
        if self._path_lengths is None:
            self._path_lengths = dict(nx.all_pairs_shortest_path_length(self, cutoff=None))
        if from_node not in self._path_lengths or to_node not in self._path_lengths[from_node]:
            return math.inf
        else:
            return self._path_lengths[from_node][to_node] 
Example #7
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #8
Source File: test_unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_all_pairs_shortest_path_length(self):
        l=nx.all_pairs_shortest_path_length(self.cycle)
        assert_equal(l[0],{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        l=nx.all_pairs_shortest_path_length(self.grid)
        assert_equal(l[1][16],6) 
Example #9
Source File: unweighted.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def all_pairs_shortest_path_length(G, cutoff=None):
    """Computes the shortest path lengths between all nodes in ``G``.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        ``cutoff`` are returned.

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

    Notes
    -----
    The dictionary returned only has keys for reachable node pairs.

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

    """
    length = single_source_shortest_path_length
    # TODO This can be trivially parallelized.
    return {n: length(G, n, cutoff=cutoff) for n in G} 
Example #10
Source File: test_unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_all_pairs_shortest_path_length(self):
        l = dict(nx.all_pairs_shortest_path_length(self.cycle))
        assert_equal(l[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
        l = dict(nx.all_pairs_shortest_path_length(self.grid))
        assert_equal(l[1][16], 6) 
Example #11
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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) 
Example #12
Source File: test_unweighted.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_all_pairs_shortest_path_length(self):
        l = dict(nx.all_pairs_shortest_path_length(self.cycle))
        assert_equal(l[0],{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
        l = dict(nx.all_pairs_shortest_path_length(self.grid))
        assert_equal(l[1][16],6) 
Example #13
Source File: unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def all_pairs_shortest_path_length(G, cutoff=None):
    """Computes the shortest path lengths between all nodes in `G`.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        `cutoff` are returned.

    Returns
    -------
    lengths : iterator
        (source, dictionary) iterator with dictionary keyed by target and
        shortest path length as the key value.

    Notes
    -----
    The iterator returned only has reachable node pairs.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = dict(nx.all_pairs_shortest_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

    """
    length = single_source_shortest_path_length
    # TODO This can be trivially parallelized.
    for n in G:
        yield (n, length(G, n, cutoff=cutoff)) 
Example #14
Source File: unweighted.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def all_pairs_shortest_path_length(G, cutoff=None):
    """Computes the shortest path lengths between all nodes in `G`.

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

    cutoff : integer, optional
        Depth at which to stop the search. Only paths of length at most
        `cutoff` are returned.

    Returns
    -------
    lengths : iterator
        (source, dictionary) iterator with dictionary keyed by target and
        shortest path length as the key value.

    Notes
    -----
    The iterator returned only has reachable node pairs.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> length = dict(nx.all_pairs_shortest_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

    """
    length = single_source_shortest_path_length
    # TODO This can be trivially parallelized.
    for n in G:
        yield (n, length(G, n, cutoff=cutoff))