B
    Nô`Î  ã               @   s<   d Z ddlZddlmZ dgZedƒedƒddd„ƒƒZdS )	z5Bethe Hessian or deformed Laplacian matrix of graphs.é    N)Únot_implemented_forÚbethe_hessian_matrixZdirectedZ
multigraphc       
      C   sÄ   ddl }|dkrt| ƒ}|dkrTtdd„ t | ¡D ƒƒtdd„ t | ¡D ƒƒ d }tj| |dd�}|j\}}|jdd	�}|jj| 	¡ dg||dd
�}|jj
||dd
�}	|d d |	 ||  | S )u¶  Returns the Bethe Hessian matrix of G.

    The Bethe Hessian is a family of matrices parametrized by r, defined as
    H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the
    diagonal matrix of node degrees, and I is the identify matrix. It is equal
    to the graph laplacian when the regularizer r = 1.

    The default choice of regularizer should be the ratio [2]

    .. math::
      r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1

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

    r : float
       Regularizer parameter

    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
    -------
    H : Numpy matrix
      The Bethe Hessian matrix of G, with paramter r.

    Examples
    --------
    >>> k = [3, 2, 2, 1, 0]
    >>> G = nx.havel_hakimi_graph(k)
    >>> H = nx.modularity_matrix(G)


    See Also
    --------
    bethe_hessian_spectrum
    to_numpy_array
    adjacency_matrix
    laplacian_matrix

    References
    ----------
    .. [1] A. Saade, F. Krzakala and L. ZdeborovÃ¡
       "Spectral clustering of graphs with the bethe hessian",
       Advances in Neural Information Processing Systems. 2014.
    .. [2] C. M. Lee, E. Levina
       "Estimating the number of communities in networks by spectral methods"
       arXiv:1507.00827, 2015.
    r   Nc             S   s   g | ]\}}|d  ‘qS )é   © )Ú.0ÚvÚdr   r   úF/tmp/pip-unpacked-wheel-fc63gmtm/networkx/linalg/bethehessianmatrix.pyú
<listcomp>F   s    z(bethe_hessian_matrix.<locals>.<listcomp>c             S   s   g | ]\}}|‘qS r   r   )r   r   r   r   r   r	   r
   F   s    é   Zcsr)ÚnodelistÚformat)Zaxis)r   r   )Zscipy.sparseÚlistÚsumÚnxZdegreeZto_scipy_sparse_matrixÚshapeÚsparseZspdiagsÚflattenZeye)
ÚGÚrr   ZscipyÚAÚnÚmZdiagsÚDÚIr   r   r	   r      s    8.
)NN)Ú__doc__Znetworkxr   Znetworkx.utilsr   Ú__all__r   r   r   r   r	   Ú<module>   s   