Python networkx.floyd_warshall_numpy() Examples

The following are 20 code examples of networkx.floyd_warshall_numpy(). 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: token_swapper.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def __init__(self, graph: nx.Graph, seed: Union[int, np.random.Generator] = None) -> None:
        """Construct an ApproximateTokenSwapping object.

        Args:
            graph (nx.Graph): Undirected graph represented a coupling map.
            seed (Union[int, np.random.default_rng]): Seed to use for random trials.
        """
        self.graph = graph
        # We need to fix the mapping from nodes in graph to nodes in shortest_paths.
        # The nodes in graph don't have to integer nor contiguous, but those in a NumPy array are.
        nodelist = list(graph.nodes())
        self.node_map = {node: i for i, node in enumerate(nodelist)}
        self.shortest_paths = nx.floyd_warshall_numpy(graph, nodelist=nodelist)
        if isinstance(seed, np.random.Generator):
            self.seed = seed
        else:
            self.seed = np.random.default_rng(seed) 
Example #2
Source File: molecule.py    From CatLearn with GNU General Public License v3.0 6 votes vote down vote up
def get_autocorrelation(self, atoms):
        """Return the autocorrelation fingerprint for a molecule."""
        connectivity = atoms.connectivity

        G = nx.Graph(connectivity)
        distance_matrix = nx.floyd_warshall_numpy(G)
        Bm = np.zeros(distance_matrix.shape)

        n = len(self.parameters)
        W = list_mendeleev_params(atoms.numbers, self.parameters).T

        fingerprint = np.zeros(n * (self.dstar + 1))
        for dd in range(self.dstar + 1):
            B = Bm.copy()
            B[distance_matrix == dd] = 1
            AC = np.dot(np.dot(W, B), W.T).diagonal()
            fingerprint[n * dd:n * (dd + 1)] = AC

        return fingerprint 
Example #3
Source File: gk_shortest_path.py    From jstsp2015 with MIT License 5 votes vote down vote up
def compare(self, g_1, g_2, verbose=False):
        """Compute the kernel value (similarity) between two graphs.

        Parameters
        ----------
        g1 : networkx.Graph
            First graph.
        g2 : networkx.Graph
            Second graph.

        Returns
        -------
        k : The similarity value between g1 and g2.
        """
        # Diagonal superior matrix of the floyd warshall shortest
        # paths:
        fwm1 = np.array(nx.floyd_warshall_numpy(g_1))
        fwm1 = np.where(fwm1 == np.inf, 0, fwm1)
        fwm1 = np.where(fwm1 == np.nan, 0, fwm1)
        fwm1 = np.triu(fwm1, k=1)
        bc1 = np.bincount(fwm1.reshape(-1).astype(int))

        fwm2 = np.array(nx.floyd_warshall_numpy(g_2))
        fwm2 = np.where(fwm2 == np.inf, 0, fwm2)
        fwm2 = np.where(fwm2 == np.nan, 0, fwm2)
        fwm2 = np.triu(fwm2, k=1)
        bc2 = np.bincount(fwm2.reshape(-1).astype(int))

        # Copy into arrays with the same length the non-zero shortests
        # paths:
        v1 = np.zeros(max(len(bc1), len(bc2)) - 1)
        v1[range(0, len(bc1)-1)] = bc1[1:]

        v2 = np.zeros(max(len(bc1), len(bc2)) - 1)
        v2[range(0, len(bc2)-1)] = bc2[1:]

        return np.sum(v1 * v2) 
Example #4
Source File: test_dense_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_directed_cycle_numpy(self):
        G = nx.DiGraph()
        nx.add_cycle(G, [0, 1, 2, 3])
        pred,dist = nx.floyd_warshall_predecessor_and_distance(G)
        D = nx.utils.dict_to_numpy_array(dist)
        assert_equal(nx.floyd_warshall_numpy(G),D) 
Example #5
Source File: test_dense_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_weight_parameter_numpy(self):
        XG4 = nx.Graph()
        XG4.add_edges_from([ (0, 1, {'heavy': 2}), (1, 2, {'heavy': 2}),
                             (2, 3, {'heavy': 1}), (3, 4, {'heavy': 1}),
                             (4, 5, {'heavy': 1}), (5, 6, {'heavy': 1}),
                             (6, 7, {'heavy': 1}), (7, 0, {'heavy': 1}) ])
        dist = nx.floyd_warshall_numpy(XG4, weight='heavy')
        assert_equal(dist[0, 2], 4) 
Example #6
Source File: test_dense_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_weighted_numpy(self):
        XG4=nx.Graph()
        XG4.add_weighted_edges_from([ [0,1,2],[1,2,2],[2,3,1],
                                      [3,4,1],[4,5,1],[5,6,1],
                                      [6,7,1],[7,0,1] ])
        dist = nx.floyd_warshall_numpy(XG4)
        assert_equal(dist[0,2],4) 
Example #7
Source File: test_dense_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_weighted_numpy(self):
        XG3=nx.Graph()
        XG3.add_weighted_edges_from([ [0,1,2],[1,2,12],[2,3,1],
                                      [3,4,5],[4,5,1],[5,0,10] ])
        dist = nx.floyd_warshall_numpy(XG3)
        assert_equal(dist[0,3],15) 
Example #8
Source File: test_dense_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_cycle_numpy(self):
        dist = nx.floyd_warshall_numpy(nx.cycle_graph(7))
        assert_equal(dist[0,3],3)
        assert_equal(dist[0,4],3) 
Example #9
Source File: test_dense_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_directed_cycle_numpy(self):
        G = nx.DiGraph()
        nx.add_cycle(G, [0, 1, 2, 3])
        pred, dist = nx.floyd_warshall_predecessor_and_distance(G)
        D = nx.utils.dict_to_numpy_array(dist)
        assert_equal(nx.floyd_warshall_numpy(G), D) 
Example #10
Source File: test_dense_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_weight_parameter_numpy(self):
        XG4 = nx.Graph()
        XG4.add_edges_from([(0, 1, {'heavy': 2}), (1, 2, {'heavy': 2}),
                            (2, 3, {'heavy': 1}), (3, 4, {'heavy': 1}),
                            (4, 5, {'heavy': 1}), (5, 6, {'heavy': 1}),
                            (6, 7, {'heavy': 1}), (7, 0, {'heavy': 1})])
        dist = nx.floyd_warshall_numpy(XG4, weight='heavy')
        assert_equal(dist[0, 2], 4) 
Example #11
Source File: test_dense_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_weighted_numpy_two_edges(self):
        XG4 = nx.Graph()
        XG4.add_weighted_edges_from([[0, 1, 2], [1, 2, 2], [2, 3, 1],
                                     [3, 4, 1], [4, 5, 1], [5, 6, 1],
                                     [6, 7, 1], [7, 0, 1]])
        dist = nx.floyd_warshall_numpy(XG4)
        assert_equal(dist[0, 2], 4) 
Example #12
Source File: test_dense_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_weighted_numpy_three_edges(self):
        XG3 = nx.Graph()
        XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1],
                                     [3, 4, 5], [4, 5, 1], [5, 0, 10]])
        dist = nx.floyd_warshall_numpy(XG3)
        assert_equal(dist[0, 3], 15) 
Example #13
Source File: test_dense_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cycle_numpy(self):
        dist = nx.floyd_warshall_numpy(nx.cycle_graph(7))
        assert_equal(dist[0, 3], 3)
        assert_equal(dist[0, 4], 3) 
Example #14
Source File: test_dense_numpy.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_directed_cycle_numpy(self):
        G = nx.DiGraph()
        G.add_cycle([0,1,2,3])
        pred,dist = nx.floyd_warshall_predecessor_and_distance(G)
        D = nx.utils.dict_to_numpy_array(dist)
        assert_equal(nx.floyd_warshall_numpy(G),D) 
Example #15
Source File: test_dense_numpy.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_weight_parameter_numpy(self):
        XG4 = nx.Graph()
        XG4.add_edges_from([ (0, 1, {'heavy': 2}), (1, 2, {'heavy': 2}),
                             (2, 3, {'heavy': 1}), (3, 4, {'heavy': 1}),
                             (4, 5, {'heavy': 1}), (5, 6, {'heavy': 1}),
                             (6, 7, {'heavy': 1}), (7, 0, {'heavy': 1}) ])
        dist = nx.floyd_warshall_numpy(XG4, weight='heavy')
        assert_equal(dist[0, 2], 4) 
Example #16
Source File: test_dense_numpy.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_weighted_numpy(self):
        XG4=nx.Graph()
        XG4.add_weighted_edges_from([ [0,1,2],[1,2,2],[2,3,1],
                                      [3,4,1],[4,5,1],[5,6,1],
                                      [6,7,1],[7,0,1] ])
        dist = nx.floyd_warshall_numpy(XG4)
        assert_equal(dist[0,2],4) 
Example #17
Source File: test_dense_numpy.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_weighted_numpy(self):
        XG3=nx.Graph()
        XG3.add_weighted_edges_from([ [0,1,2],[1,2,12],[2,3,1],
                                      [3,4,5],[4,5,1],[5,0,10] ])
        dist = nx.floyd_warshall_numpy(XG3)
        assert_equal(dist[0,3],15) 
Example #18
Source File: test_dense_numpy.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_cycle_numpy(self):
        dist = nx.floyd_warshall_numpy(nx.cycle_graph(7))
        assert_equal(dist[0,3],3)
        assert_equal(dist[0,4],3) 
Example #19
Source File: operations.py    From CatKit with GNU General Public License v3.0 5 votes vote down vote up
def autocorrelation(
        atoms=None,
        atoms_parameters=None,
        connectivity=None,
        d=0):
    """Autocorrelation convolution for systems without pbc."""
    G = nx.Graph(connectivity)
    D = nx.floyd_warshall_numpy(G)
    S = np.zeros_like(D)
    S[D == d] = 1

    AC = np.dot(np.dot(atoms_parameters, S), atoms_parameters.T).diagonal()

    return AC 
Example #20
Source File: test_db.py    From CatKit with GNU General Public License v3.0 4 votes vote down vote up
def test_database(self):
        """Test a general use case for the fingerprint database."""
        dstar = 8
        with FingerprintDB('tmp-fingerprints.db') as fpd:
            for i in range(dstar + 1):
                fpd.parameter_entry('Z{}'.format(i),
                                    'Atomic charge: depth {}'.format(i))
                fpd.parameter_entry(
                    'r{}'.format(i),
                    'Cordero covalent radius: depth {}'.format(i))
                fpd.parameter_entry(
                    'x{}'.format(i),
                    'Pauling electronegetivity: depth {}'.format(i))
                fpd.parameter_entry('T{}'.format(i),
                                    'Coordination number: depth {}'.format(i))
                fpd.parameter_entry(
                    '1{}'.format(i), 'Unity: depth {}'.format(i))
            fpd.parameter_entry('Ef', 'Formation energy')
            fpd.parameter_entry('Et', 'Total energy')

            par = fpd.get_parameters()

            for d in db.select():
                fpd.image_entry(d)

                atoms = d.toatoms()

                edges = [tuple([u, v]) for u, v in d.data['edges']]
                G = nx.Graph()
                G.add_nodes_from(range(len(atoms)))
                G.add_edges_from(edges)
                distance_matrix = nx.floyd_warshall_numpy(G)
                Bm = np.zeros(distance_matrix.shape)

                W = np.ones((5, len(atoms)))
                W[0] = atoms.numbers

                for i, n in enumerate(W[0]):
                    W[1][i] = properties['covalent_radius_cordero'][int(n)]
                    W[2][i] = properties['en_pauling'][int(n)]
                    W[3][i] = len(G[i])

                for dd in range(dstar + 1):
                    B = Bm.copy()
                    B[distance_matrix == dd] = 1
                    AC = np.dot(np.dot(W, B), W.T).diagonal()

                    for j, v in enumerate(AC):
                        ind = j + dd * len(AC)
                        fpd.fingerprint_entry(d.id, par[ind], v)

                fpd.fingerprint_entry(d.id, 46, d.Uref)
                fpd.fingerprint_entry(d.id, 47, atoms.get_potential_energy())