def mat_to_laplacian(mat, normalized):
if sps.issparse(mat):<EOL><INDENT>if np.all(mat.diagonal()>=<NUM_LIT:0>): <EOL><INDENT>if np.all((mat-sps.diags(mat.diagonal())).data <= <NUM_LIT:0>): <EOL><INDENT>return mat<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if np.all(np.diag(mat)>=<NUM_LIT:0>): <EOL><INDENT>if np.all(mat - np.diag(mat) <= <NUM_LIT:0>): <EOL><INDENT>return mat<EOL><DEDENT><DEDENT><DEDENT>deg = np.squeeze(np.asarray(mat.sum(axis=<NUM_LIT:1>)))<EOL>if sps.issparse(mat):<EOL><INDENT>L = sps.diags(deg) - mat<EOL><DEDENT>else:<EOL><INDENT>L = np.diag(deg) - mat<EOL><DEDENT>if not normalized:<EOL><INDENT>return L<EOL><DEDENT>with np.errstate(divide='<STR_LIT:ignore>'):<EOL><INDENT>sqrt_deg = <NUM_LIT:1.0> / np.sqrt(deg)<EOL><DEDENT>sqrt_deg[sqrt_deg==np.inf] = <NUM_LIT:0><EOL>if sps.issparse(mat):<EOL><INDENT>sqrt_deg_mat = sps.diags(sqrt_deg)<EOL><DEDENT>else:<EOL><INDENT>sqrt_deg_mat = np.diag(sqrt_deg)<EOL><DEDENT>return sqrt_deg_mat.dot(L).dot(sqrt_deg_mat)<EOL>
Converts a sparse or dence adjacency matrix to Laplacian.

Parameters
----------
mat : obj
    Input adjacency matrix. If it is a Laplacian matrix already, return it.
normalized : bool
    Whether to use normalized Laplacian.
    Normalized and unnormalized Laplacians capture different properties of graphs, e.g. normalized Laplacian spectrum can determine whether a graph is bipartite, but not the number of its edges. We recommend using normalized Laplacian.

Returns
-------
obj
    Laplacian of the input adjacency matrix

Examples
--------
>>> mat_to_laplacian(numpy.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]), False)
[[ 2, -1, -1], [-1,  2, -1], [-1, -1,  2]]