Python networkx.modularity_matrix() Examples

The following are 12 code examples of networkx.modularity_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: modularity.py    From clusternet with MIT License 8 votes vote down vote up
def get_base_modularity_matrix(network):
    '''
    Obtain the modularity matrix for the whole network
    Parameters
    ----------
    network : nx.Graph or nx.DiGraph
        The network of interest
    Returns
    -------
    np.matrix
        The modularity matrix for `network`
    Raises
    ------
    TypeError
        When the input `network` does not fit either nx.Graph or nx.DiGraph
    '''

    if type(network) == nx.Graph:
        return sparse.csc_matrix(nx.modularity_matrix(network))
    elif type(network) == nx.DiGraph:
        return sparse.csc_matrix(nx.directed_modularity_matrix(network))
    else:
        raise TypeError('Graph type not supported. Use either nx.Graph or nx.Digraph') 
Example #2
Source File: modularitymatrix.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def modularity_matrix(G, nodelist=None):
    """Return the modularity matrix of G.

    The modularity matrix is the matrix B = A - <A>, where A is the adjacency
    matrix and <A> is the average adjacency matrix, assuming that the graph
    is described by the configuration model.

    More specifically, the element B_ij of B is defined as
        A_ij - k_i k_j/m
    where k_i(in) is the degree of node i, and were m is the number of edges
    in the graph.

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

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    Returns
    -------
    B : Numpy matrix
      The modularity matrix of G.

    Examples
    --------
    >>> import networkx as nx
    >>> k =[3, 2, 2, 1, 0]
    >>> G = nx.havel_hakimi_graph(k)
    >>> B = nx.modularity_matrix(G)


    See Also
    --------
    to_numpy_matrix
    adjacency_matrix
    laplacian_matrix
    directed_modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    if nodelist is None:
        nodelist = G.nodes()
    A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, format='csr')
    k = A.sum(axis=1)
    m = G.number_of_edges()
    # Expected adjacency matrix
    X = k * k.transpose() / (2 * m)
    return A - X 
Example #3
Source File: spectrum.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def modularity_spectrum(G):
    """Return eigenvalues of the modularity matrix of G.

    Parameters
    ----------
    G : Graph
       A NetworkX Graph or DiGraph

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

    See Also
    --------
    modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    from scipy.linalg import eigvals
    if G.is_directed():
        return eigvals(nx.directed_modularity_matrix(G))
    else:
        return eigvals(nx.modularity_matrix(G))

# fixture for nose tests 
Example #4
Source File: test_modularity.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_modularity(self):
        "Modularity matrix"
        B = numpy.matrix([[-1.125,  0.25 ,  0.25 ,  0.625,  0.   ],
                         [ 0.25 , -0.5  ,  0.5  , -0.25 ,  0.   ],
                         [ 0.25 ,  0.5  , -0.5  , -0.25 ,  0.   ],
                         [ 0.625, -0.25 , -0.25 , -0.125,  0.   ],
                         [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ]])

        permutation = [4, 0, 1, 2, 3]
        assert_equal(nx.modularity_matrix(self.G), B)
        assert_equal(nx.modularity_matrix(self.G, nodelist=permutation),
                     B[numpy.ix_(permutation, permutation)]) 
Example #5
Source File: spectrum.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def modularity_spectrum(G):
    """Returns eigenvalues of the modularity matrix of G.

    Parameters
    ----------
    G : Graph
       A NetworkX Graph or DiGraph

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

    See Also
    --------
    modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    from scipy.linalg import eigvals
    if G.is_directed():
        return eigvals(nx.directed_modularity_matrix(G))
    else:
        return eigvals(nx.modularity_matrix(G))

# fixture for nose tests 
Example #6
Source File: test_modularity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_modularity(self):
        "Modularity matrix"
        B = numpy.matrix([[-1.125,  0.25,  0.25,  0.625,  0.],
                          [0.25, -0.5,  0.5, -0.25,  0.],
                          [0.25,  0.5, -0.5, -0.25,  0.],
                          [0.625, -0.25, -0.25, -0.125,  0.],
                          [0.,  0.,  0.,  0.,  0.]])

        permutation = [4, 0, 1, 2, 3]
        assert_equal(nx.modularity_matrix(self.G), B)
        assert_equal(nx.modularity_matrix(self.G, nodelist=permutation),
                     B[numpy.ix_(permutation, permutation)]) 
Example #7
Source File: test_modularity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_modularity_weight(self):
        "Modularity matrix with weights"
        B = numpy.matrix([[-1.125,  0.25,  0.25,  0.625,  0.],
                          [0.25, -0.5,  0.5, -0.25,  0.],
                          [0.25,  0.5, -0.5, -0.25,  0.],
                          [0.625, -0.25, -0.25, -0.125,  0.],
                          [0.,  0.,  0.,  0.,  0.]])

        G_weighted = self.G.copy()
        for n1, n2 in G_weighted.edges():
            G_weighted.edges[n1, n2]["weight"] = 0.5
        # The following test would fail in networkx 1.1
        assert_equal(nx.modularity_matrix(G_weighted), B)
        # The following test that the modularity matrix get rescaled accordingly
        assert_equal(nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B) 
Example #8
Source File: modularitymatrix.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def modularity_matrix(G, nodelist=None, weight=None):
    """Return the modularity matrix of G.

    The modularity matrix is the matrix B = A - <A>, where A is the adjacency
    matrix and <A> is the average adjacency matrix, assuming that the graph
    is described by the configuration model.

    More specifically, the element B_ij of B is defined as
        A_ij - k_i k_j / 2 * m
    where k_i(in) is the degree of node i, and were m is the number of edges
    in the graph. When weight is set to a name of an attribute edge, Aij, k_i,
    k_j and m are computed using its value.

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

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used for
       the edge weight.  If None then all edge weights are 1.

    Returns
    -------
    B : Numpy matrix
      The modularity matrix of G.

    Examples
    --------
    >>> import networkx as nx
    >>> k =[3, 2, 2, 1, 0]
    >>> G = nx.havel_hakimi_graph(k)
    >>> B = nx.modularity_matrix(G)


    See Also
    --------
    to_numpy_matrix
    adjacency_matrix
    laplacian_matrix
    directed_modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    if nodelist is None:
        nodelist = list(G)
    A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
                                  format='csr')
    k = A.sum(axis=1)
    m = k.sum() * 0.5
    # Expected adjacency matrix
    X = k * k.transpose() / (2 * m)
    return A - X 
Example #9
Source File: spectrum.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def modularity_spectrum(G):
    """Return eigenvalues of the modularity matrix of G.

    Parameters
    ----------
    G : Graph
       A NetworkX Graph or DiGraph

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

    See Also
    --------
    modularity_matrix

    References
    ----------
    .. [1] M. E. J. Newman, "Modularity and community structure in networks",
       Proc. Natl. Acad. Sci. USA, vol. 103, pp. 8577-8582, 2006.
    """
    from scipy.linalg import eigvals
    if G.is_directed():
        return eigvals(nx.directed_modularity_matrix(G))
    else:
        return eigvals(nx.modularity_matrix(G))

# fixture for nose tests 
Example #10
Source File: test_modularity.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_modularity(self):
        "Modularity matrix"
        B = numpy.matrix([[-1.125,  0.25,  0.25,  0.625,  0.],
                          [0.25, -0.5,  0.5, -0.25,  0.],
                          [0.25,  0.5, -0.5, -0.25,  0.],
                          [0.625, -0.25, -0.25, -0.125,  0.],
                          [0.,  0.,  0.,  0.,  0.]])

        permutation = [4, 0, 1, 2, 3]
        assert_equal(nx.modularity_matrix(self.G), B)
        assert_equal(nx.modularity_matrix(self.G, nodelist=permutation),
                     B[numpy.ix_(permutation, permutation)]) 
Example #11
Source File: test_modularity.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_modularity_weight(self):
        "Modularity matrix with weights"
        B = numpy.matrix([[-1.125,  0.25,  0.25,  0.625,  0.],
                          [0.25, -0.5,  0.5, -0.25,  0.],
                          [0.25,  0.5, -0.5, -0.25,  0.],
                          [0.625, -0.25, -0.25, -0.125,  0.],
                          [0.,  0.,  0.,  0.,  0.]])

        G_weighted = self.G.copy()
        for n1, n2 in G_weighted.edges():
            G_weighted.edges[n1, n2]["weight"] = 0.5
        # The following test would fail in networkx 1.1
        assert_equal(nx.modularity_matrix(G_weighted), B)
        # The following test that the modularity matrix get rescaled accordingly
        assert_equal(nx.modularity_matrix(G_weighted, weight="weight"), 0.5 * B) 
Example #12
Source File: utils.py    From python-modularity-maximization with MIT License 5 votes vote down vote up
def get_base_modularity_matrix(network):
    '''
    Obtain the modularity matrix for the whole network

    Parameters
    ----------
    network : nx.Graph or nx.DiGraph
        The network of interest

    Returns
    -------
    np.matrix
        The modularity matrix for `network`

    Raises
    ------
    TypeError
        When the input `network` does not fit either nx.Graph or nx.DiGraph
    '''

    if type(network) == nx.Graph:
        return sparse.csc_matrix(nx.modularity_matrix(network))
    elif type(network) == nx.DiGraph:
        return sparse.csc_matrix(nx.directed_modularity_matrix(network))
    else:
        raise TypeError('Graph type not supported. Use either nx.Graph or nx.Digraph')