Python networkx.laplacian_matrix() Examples

The following are 30 code examples of networkx.laplacian_matrix(). 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: test_algebraic_connectivity.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_two_nodes(self):
        G = nx.Graph()
        G.add_edge(0, 1, weight=1)
        A = nx.laplacian_matrix(G)
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), 2)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, 2, x)
        G = nx.MultiGraph()
        G.add_edge(0, 0, spam=1e8)
        G.add_edge(0, 1, spam=1)
        G.add_edge(0, 1, spam=-2)
        A = -3 * nx.laplacian_matrix(G, weight='spam')
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, weight='spam', tol=1e-12, method=method), 6)
            x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method)
            check_eigenvector(A, 6, x) 
Example #2
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_cycle(self):
        path = list(range(10))
        G = nx.Graph()
        nx.add_path(G, path, weight=5)
        G.add_edge(path[-1], path[0], weight=1)
        A = nx.laplacian_matrix(G).todense()
        for normalized in (False, True):
            for method in methods:
                try:
                    order = nx.spectral_ordering(G, normalized=normalized,
                                                 method=method)
                except nx.NetworkXError as e:
                    if e.args not in (('Cholesky solver unavailable.',),
                                      ('LU solver unavailable.',)):
                        raise
                else:
                    if not normalized:
                        ok_(order in [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8],
                                      [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]])
                    else:
                        ok_(order in [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8],
                                      [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]) 
Example #3
Source File: test_threshold.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_eigenvectors(self):
        try:
            import numpy as N
            eigenval = N.linalg.eigvals
            import scipy
        except ImportError:
            raise SkipTest('SciPy not available.')

        cs = 'ddiiddid'
        G = nxt.threshold_graph(cs)
        (tgeval, tgevec) = nxt.eigenvectors(cs)
        dot = N.dot
        assert_equal([abs(dot(lv, lv) - 1.0) < 1e-9 for lv in tgevec], [True] * 8)
        lapl = nx.laplacian_matrix(G)
#        tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
#        assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
#        tgev.sort()
#        lev=list(eigenval(lapl))
#        lev.sort()
#        assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9) 
Example #4
Source File: utils.py    From BANE with GNU General Public License v3.0 6 votes vote down vote up
def normalize_adjacency(graph, args):
    """
    Method to calculate a sparse degree normalized adjacency matrix.
    :param graph: Sparse graph adjacency matrix.
    :return A: Normalized adjacency matrix.
    """
    for node in graph.nodes():
        graph.add_edge(node, node)
    ind = range(len(graph.nodes()))
    degs = [1.0/graph.degree(node) for node in graph.nodes()]
    L = sparse.csr_matrix(nx.laplacian_matrix(graph),
                          dtype=np.float32)

    degs = sparse.csr_matrix(sparse.coo_matrix((degs, (ind, ind)),
                                               shape=L.shape,
                                               dtype=np.float32))

    propagator = sparse.eye(L.shape[0])-args.gamma*degs.dot(L)
    return propagator 
Example #5
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_two_nodes(self):
        G = nx.Graph()
        G.add_edge(0, 1, weight=1)
        A = nx.laplacian_matrix(G)
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), 2)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, 2, x)
        G = nx.MultiGraph()
        G.add_edge(0, 0, spam=1e8)
        G.add_edge(0, 1, spam=1)
        G.add_edge(0, 1, spam=-2)
        A = -3 * nx.laplacian_matrix(G, weight='spam')
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, weight='spam', tol=1e-12, method=method), 6)
            x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method)
            check_eigenvector(A, 6, x) 
Example #6
Source File: test_laplacian.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_laplacian(self):
        "Graph Laplacian"
        NL = numpy.array([[3, -1, -1, -1, 0],
                          [-1,  2, -1,  0, 0],
                          [-1, -1,  2,  0, 0],
                          [-1,  0,  0,  1, 0],
                          [0,  0,  0,  0, 0]])
        WL = 0.5 * NL
        OL = 0.3 * NL
        assert_equal(nx.laplacian_matrix(self.G).todense(), NL)
        assert_equal(nx.laplacian_matrix(self.MG).todense(), NL)
        assert_equal(nx.laplacian_matrix(self.G, nodelist=[0, 1]).todense(),
                     numpy.array([[1, -1], [-1, 1]]))
        assert_equal(nx.laplacian_matrix(self.WG).todense(), WL)
        assert_equal(nx.laplacian_matrix(self.WG, weight=None).todense(), NL)
        assert_equal(nx.laplacian_matrix(self.WG, weight='other').todense(), OL) 
Example #7
Source File: test_laplacian.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_laplacian(self):
        "Graph Laplacian"
        NL = numpy.array([[3, -1, -1, -1, 0],
                          [-1,  2, -1,  0, 0],
                          [-1, -1,  2,  0, 0],
                          [-1,  0,  0,  1, 0],
                          [0,  0,  0,  0, 0]])
        WL = 0.5 * NL
        OL = 0.3 * NL
        assert_equal(nx.laplacian_matrix(self.G).todense(), NL)
        assert_equal(nx.laplacian_matrix(self.MG).todense(), NL)
        assert_equal(nx.laplacian_matrix(self.G, nodelist=[0, 1]).todense(),
                     numpy.array([[1, -1], [-1, 1]]))
        assert_equal(nx.laplacian_matrix(self.WG).todense(), WL)
        assert_equal(nx.laplacian_matrix(self.WG, weight=None).todense(), NL)
        assert_equal(nx.laplacian_matrix(self.WG, weight='other').todense(), OL) 
Example #8
Source File: test_threshold.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_eigenvectors(self):
        try:
            import numpy as N
            eigenval=N.linalg.eigvals
            import scipy
        except ImportError:
            raise SkipTest('SciPy not available.')

        cs='ddiiddid'
        G=nxt.threshold_graph(cs)
        (tgeval,tgevec)=nxt.eigenvectors(cs)
        dot=N.dot
        assert_equal([ abs(dot(lv,lv)-1.0)<1e-9 for lv in tgevec ], [True]*8)
        lapl=nx.laplacian_matrix(G)
#        tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
#        assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
#        tgev.sort()
#        lev=list(eigenval(lapl))
#        lev.sort()
#        assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9) 
Example #9
Source File: test_algebraic_connectivity.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_cycle(self):
        path = list(range(10))
        G = nx.Graph()
        G.add_path(path, weight=5)
        G.add_edge(path[-1], path[0], weight=1)
        A = nx.laplacian_matrix(G).todense()
        for normalized in (False, True):
            for method in methods:
                try:
                    order = nx.spectral_ordering(G, normalized=normalized,
                                                 method=method)
                except nx.NetworkXError as e:
                    if e.args not in (('Cholesky solver unavailable.',),
                                      ('LU solver unavailable.',)):
                        raise
                else:
                    if not normalized:
                        ok_(order in [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8],
                                      [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]])
                    else:
                        ok_(order in [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8],
                                      [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]) 
Example #10
Source File: test_algebraic_connectivity.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_two_nodes(self):
        G = nx.Graph()
        G.add_edge(0, 1, weight=1)
        A = nx.laplacian_matrix(G)
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), 2)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, 2, x)
        G = nx.MultiGraph()
        G.add_edge(0, 0, spam=1e8)
        G.add_edge(0, 1, spam=1)
        G.add_edge(0, 1, spam=-2)
        A = -3 * nx.laplacian_matrix(G, weight='spam')
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, weight='spam', tol=1e-12, method=method), 6)
            x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method)
            check_eigenvector(A, 6, x) 
Example #11
Source File: test_laplacian.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_laplacian(self):
        "Graph Laplacian"
        NL=numpy.array([[ 3, -1, -1, -1, 0],
                        [-1,  2, -1,  0, 0],
                        [-1, -1,  2,  0, 0],
                        [-1,  0,  0,  1, 0],
                        [ 0,  0,  0,  0, 0]])
        WL=0.5*NL
        OL=0.3*NL
        assert_equal(nx.laplacian_matrix(self.G).todense(),NL)
        assert_equal(nx.laplacian_matrix(self.MG).todense(),NL)
        assert_equal(nx.laplacian_matrix(self.G,nodelist=[0,1]).todense(),
                numpy.array([[ 1, -1],[-1, 1]]))
        assert_equal(nx.laplacian_matrix(self.WG).todense(),WL)
        assert_equal(nx.laplacian_matrix(self.WG,weight=None).todense(),NL)
        assert_equal(nx.laplacian_matrix(self.WG,weight='other').todense(),OL) 
Example #12
Source File: sdne.py    From cogdl with MIT License 6 votes vote down vote up
def train(self, G):
        num_node = G.number_of_nodes()
        model = SDNE_layer(num_node, self.hidden_size1, self.hidden_size2, self.droput, self.alpha, self.beta, self.nu1, self.nu2)
        
        A = torch.from_numpy(nx.adjacency_matrix(G).todense().astype(np.float32))
        L = torch.from_numpy(nx.laplacian_matrix(G).todense().astype(np.float32))
        
        A, L = A.to(self.device), L.to(self.device)
        model = model.to(self.device)
        
        opt = torch.optim.Adam(model.parameters(), lr=self.lr)
        epoch_iter = tqdm(range(self.max_epoch))
        for epoch in epoch_iter:            
            opt.zero_grad()
            L_1st, L_2nd, L_all, L_reg = model.forward(A, L)
            Loss = L_all + L_reg
            Loss.backward()
            epoch_iter.set_description(
                f"Epoch: {epoch:03d}, L_1st: {L_1st:.4f}, L_2nd: {L_2nd:.4f}, L_reg: {L_reg:.4f}"
            )
            opt.step()
        embedding = model.get_emb(A)
        return embedding.detach().cpu().numpy() 
Example #13
Source File: test_algebraic_connectivity.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_cycle(self):
        path = list(range(10))
        G = nx.Graph()
        nx.add_path(G, path, weight=5)
        G.add_edge(path[-1], path[0], weight=1)
        A = nx.laplacian_matrix(G).todense()
        for normalized in (False, True):
            for method in methods:
                try:
                    order = nx.spectral_ordering(G, normalized=normalized,
                                                 method=method)
                except nx.NetworkXError as e:
                    if e.args not in (('Cholesky solver unavailable.',),
                                      ('LU solver unavailable.',)):
                        raise
                else:
                    if not normalized:
                        ok_(order in [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8],
                                      [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]])
                    else:
                        ok_(order in [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8],
                                      [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]) 
Example #14
Source File: test_threshold.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_eigenvectors(self):
        try:
            import numpy as N
            eigenval = N.linalg.eigvals
            import scipy
        except ImportError:
            raise SkipTest('SciPy not available.')

        cs = 'ddiiddid'
        G = nxt.threshold_graph(cs)
        (tgeval, tgevec) = nxt.eigenvectors(cs)
        dot = N.dot
        assert_equal([abs(dot(lv, lv) - 1.0) < 1e-9 for lv in tgevec], [True] * 8)
        lapl = nx.laplacian_matrix(G)
#        tgev=[ dot(lv,dot(lapl,lv)) for lv in tgevec ]
#        assert_true(sum([abs(c-d) for c,d in zip(tgev,tgeval)]) < 1e-9)
#        tgev.sort()
#        lev=list(eigenval(lapl))
#        lev.sort()
#        assert_true(sum([abs(c-d) for c,d in zip(tgev,lev)]) < 1e-9) 
Example #15
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_abbreviation_of_method(self):
        G = nx.path_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2 + sqrt(2))
        ac = nx.algebraic_connectivity(G, tol=1e-12, method='tracemin')
        assert_almost_equal(ac, sigma)
        x = nx.fiedler_vector(G, tol=1e-12, method='tracemin')
        check_eigenvector(A, sigma, x) 
Example #16
Source File: test_algebraic_connectivity.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2 + sqrt(2))
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, sigma, x) 
Example #17
Source File: test_algebraic_connectivity.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_cycle(self):
        G = nx.cycle_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2)
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, sigma, x) 
Example #18
Source File: spectrum.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def laplacian_spectrum(G, weight='weight'):
    """Return eigenvalues of the Laplacian of G

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

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    Returns
    -------
    evals : NumPy array
      Eigenvalues

    Notes
    -----
    For MultiGraph/MultiDiGraph, the edges weights are summed.
    See to_numpy_matrix for other options.

    See Also
    --------
    laplacian_matrix
    """
    from scipy.linalg import eigvalsh
    return eigvalsh(nx.laplacian_matrix(G, weight=weight).todense()) 
Example #19
Source File: test_graphs.py    From pygsp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_graph(self, n_vertices=11):
        """Empty graphs have either no edge, or self-loops only. The Laplacian
        doesn't see self-loops, as the gradient on those edges is always zero.
        """
        adjacencies = [
            np.zeros((n_vertices, n_vertices)),
            np.identity(n_vertices),
        ]
        for adjacency, n_edges in zip(adjacencies, [0, n_vertices]):
            graph = graphs.Graph(adjacency)
            self.assertEqual(graph.n_vertices, n_vertices)
            self.assertEqual(graph.n_edges, n_edges)
            self.assertEqual(graph.W.nnz, n_edges)
            for laplacian in ['combinatorial', 'normalized']:
                graph.compute_laplacian(laplacian)
                self.assertEqual(graph.L.nnz, 0)
                sources, targets, weights = graph.get_edge_list()
                self.assertEqual(len(sources), n_edges)
                self.assertEqual(len(targets), n_edges)
                self.assertEqual(len(weights), n_edges)
                graph.compute_differential_operator()
                self.assertEqual(graph.D.nnz, 0)
                graph.compute_fourier_basis()
                np.testing.assert_allclose(graph.U, np.identity(n_vertices))
                np.testing.assert_allclose(graph.e, np.zeros(n_vertices))
            # NetworkX uses the same conventions.
            G = nx.from_scipy_sparse_matrix(graph.W)
            self.assertEqual(nx.laplacian_matrix(G).nnz, 0)
            self.assertEqual(nx.normalized_laplacian_matrix(G).nnz, 0)
            self.assertEqual(nx.incidence_matrix(G).nnz, 0) 
Example #20
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_buckminsterfullerene(self):
        G = nx.Graph(
            [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6),
             (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56),
             (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12),
             (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53),
             (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27),
             (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54),
             (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42),
             (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58),
             (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51),
             (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56),
             (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45),
             (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49),
             (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47),
             (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55),
             (47, 54), (48, 55)])
        for normalized in (False, True):
            if not normalized:
                A = nx.laplacian_matrix(G)
                sigma = 0.2434017461399311
            else:
                A = nx.normalized_laplacian_matrix(G)
                sigma = 0.08113391537997749
            for method in methods:
                try:
                    assert_almost_equal(nx.algebraic_connectivity(
                        G, normalized=normalized, tol=1e-12, method=method),
                        sigma)
                    x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12,
                                          method=method)
                    check_eigenvector(A, sigma, x)
                except nx.NetworkXError as e:
                    if e.args not in (('Cholesky solver unavailable.',),
                                      ('LU solver unavailable.',)):
                        raise 
Example #21
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_seed_argument(self):
        G = nx.cycle_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2)
        for method in self._methods:
            ac = nx.algebraic_connectivity(G, tol=1e-12, method=method, seed=1)
            assert_almost_equal(ac, sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method, seed=1)
            check_eigenvector(A, sigma, x) 
Example #22
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cycle(self):
        G = nx.cycle_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2)
        for method in self._methods:
            ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
            assert_almost_equal(ac, sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, sigma, x) 
Example #23
Source File: test_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2 + sqrt(2))
        for method in self._methods:
            ac = nx.algebraic_connectivity(G, tol=1e-12, method=method)
            assert_almost_equal(ac, sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, sigma, x) 
Example #24
Source File: spectrum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def laplacian_spectrum(G, weight='weight'):
    """Returns eigenvalues of the Laplacian of G

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

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    Returns
    -------
    evals : NumPy array
      Eigenvalues

    Notes
    -----
    For MultiGraph/MultiDiGraph, the edges weights are summed.
    See to_numpy_matrix for other options.

    See Also
    --------
    laplacian_matrix
    """
    from scipy.linalg import eigvalsh
    return eigvalsh(nx.laplacian_matrix(G, weight=weight).todense()) 
Example #25
Source File: test_algebraic_connectivity.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_cycle(self):
        G = nx.cycle_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2)
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, sigma, x) 
Example #26
Source File: test_algebraic_connectivity.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(8)
        A = nx.laplacian_matrix(G)
        sigma = 2 - sqrt(2 + sqrt(2))
        for method in self._methods:
            assert_almost_equal(nx.algebraic_connectivity(
                G, tol=1e-12, method=method), sigma)
            x = nx.fiedler_vector(G, tol=1e-12, method=method)
            check_eigenvector(A, sigma, x) 
Example #27
Source File: spectrum.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def laplacian_spectrum(G, weight='weight'):
    """Return eigenvalues of the Laplacian of G

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

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    Returns
    -------
    evals : NumPy array
      Eigenvalues

    Notes
    -----
    For MultiGraph/MultiDiGraph, the edges weights are summed.
    See to_numpy_matrix for other options.

    See Also
    --------
    laplacian_matrix
    """
    from scipy.linalg import eigvalsh
    return eigvalsh(nx.laplacian_matrix(G,weight=weight).todense()) 
Example #28
Source File: utils.py    From quantumflow with Apache License 2.0 5 votes vote down vote up
def spanning_tree_count(graph: nx.Graph) -> int:
    """Return the number of unique spanning trees of a graph, using
    Kirchhoff's matrix tree theorem.
    """
    laplacian = nx.laplacian_matrix(graph).toarray()
    comatrix = laplacian[:-1, :-1]
    det = np.linalg.det(comatrix)
    count = int(round(det))
    return count 
Example #29
Source File: danmf.py    From DANMF with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, graph, args):
        """
        Initializing a DANMF object.
        :param graph: Networkx graph.
        :param args: Arguments object.
        """
        self.graph = graph
        self.A = nx.adjacency_matrix(self.graph)
        self.L = nx.laplacian_matrix(self.graph)
        self.D = self.L+self.A
        self.args = args
        self.p = len(self.args.layers) 
Example #30
Source File: danmf.py    From karateclub with GNU General Public License v3.0 5 votes vote down vote up
def _setup_target_matrices(self, graph):
        """
        Setup target matrix for pre-training process.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph being clustered.
        """
        self._graph = graph
        self._A = nx.adjacency_matrix(self._graph, nodelist=range(self._graph.number_of_nodes()))
        self._L = nx.laplacian_matrix(self._graph, nodelist=range(self._graph.number_of_nodes()))
        self._D = self._L+self._A