Repository: scipy/scipy

Issue:
Graph Laplacian sparse format change ruins the in-place calculation 
**Is your feature request related to a problem? Please describe.**
Since https://github.com/scipy/scipy/pull/15251 the function https://docs.scipy.org/doc/scipy-1.3.0/reference/generated/scipy.sparse.csgraph.laplacian.html now support in-place calculation, without doubling the amount of memory on the output , cf. https://github.com/scikit-learn/scikit-learn/pull/14636

However, it appears that the code is not preserving the format other than COO of the graph sparse matrix - the implementation explicitly makes a copy unless the input format is COO, as at least now documented in https://github.com/scipy/scipy/pull/15251.  It's really unclear why. 

**Describe the solution you'd like**
In-place and strictly format- and type-preserving calculation with `copy=False` avoiding the memory usage spikes. Cf. https://github.com/scipy/scipy/issues/10827

ENH: Update `laplacian` function introducing the new `dtype` option
### Is your feature request related to a problem? Please describe.

https://docs.scipy.org/doc/scipy-1.3.0/reference/generated/scipy.sparse.csgraph.laplacian.html does not allow setting `dtype` of the output, e.g., always making the normalized Laplacian in double precision ignoring the `dtype` of the input. It's especially problematic for large sizes, where excessive memory usage hurts performance, even with https://github.com/scipy/scipy/issues/10826 partially addressed in #15251 

### Describe the solution you'd like.

Update `laplacian` function introducing the new `dtype` option

### Describe alternatives you've considered.

The normalized Laplacian can be cast into single dtype after the function is executed, but one may run out of memory during the function execution.

### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:
Seems reasonable. Can we combine gh-10827 and this? I think it's the same thing right?
> 
> 
> Seems reasonable. Can we combine [gh-10827](https://github.com/scipy/scipy/issues/10827) and this? I think it's the same thing right?

The same code and similar goals, but different and unrelated changes. May be better finish one and have it merged, then start the other, to simplify code writing and unit testing. This one would have immediate positive effects in scikit-learn with trivial changes in scikit-learn code base, so is more practically important.
Makes sense. 

Looking at `_laplacian_sparse`, the implementation explicitly makes a copy unless the input format is COO, and this isn't documented. The scikit-learn PR seems to just add a `copy=True` keyword, but what seems to be needed first is an implementation that doesn't need conversion to COO. 

And then it's not 100% clear to me what the API request is: add `out=`, or really _overwrite_ the input matrix?
@rgommers  Whatever is the most memory efficient and without too much computing and coding. 
Merged PR was said to partially address this issue.


Resolving patch:
diff --git a/scipy/sparse/csgraph/_laplacian.py b/scipy/sparse/csgraph/_laplacian.py
--- a/scipy/sparse/csgraph/_laplacian.py
+++ b/scipy/sparse/csgraph/_laplacian.py
@@ -2,29 +2,33 @@
 Laplacian of a compressed-sparse graph
 """
 
-# Authors: Aric Hagberg <hagberg@lanl.gov>
-#          Gael Varoquaux <gael.varoquaux@normalesup.org>
-#          Jake Vanderplas <vanderplas@astro.washington.edu>
-#          Andrew Knyazev <Andrew.Knyazev@ucdenver.edu>
-# License: BSD
-
 import numpy as np
 from scipy.sparse import isspmatrix
+from scipy.sparse.linalg import LinearOperator
 
 
 ###############################################################################
 # Graph laplacian
-def laplacian(csgraph, normed=False, return_diag=False, use_out_degree=False,
-              *, copy=True):
+def laplacian(
+    csgraph,
+    normed=False,
+    return_diag=False,
+    use_out_degree=False,
+    *,
+    copy=True,
+    form="array",
+    dtype=None,
+    symmetrized=False,
+):
     """
-    Return the Laplacian matrix of a directed graph.
+    Return the Laplacian of a directed graph.
 
     Parameters
     ----------
     csgraph : array_like or sparse matrix, 2 dimensions
         compressed-sparse graph, with shape (N, N).
     normed : bool, optional
-        If True, then compute symmetric normalized Laplacian.
+        If True, then compute symmetrically normalized Laplacian.
         Default: False.
     return_diag : bool, optional
         If True, then also return an array related to vertex degrees.
@@ -37,81 +41,409 @@ def laplacian(csgraph, normed=False, return_diag=False, use_out_degree=False,
         If False, then change `csgraph` in place if possible,
         avoiding doubling the memory use.
         Default: True, for backward compatibility.
+    form: 'array', or 'function', or 'lo'
+        Determines the format of the output Laplacian:
+
+        * 'array' is a numpy array;
+        * 'function' is a pointer to evaluating the Laplacian-vector
+          or Laplacian-matrix product;
+        * 'lo' results in the format of the `LinearOperator`.
+
+        Choosing 'function' or 'lo' always avoids doubling
+        the memory use, ignoring `copy` value.
+        Default: 'array', for backward compatibility.
+    dtype: None or one of numeric numpy dtypes, optional
+        The dtype of the output. If ``dtype=None``, the dtype of the
+        output matches the dtype of the input csgraph, except for
+        the case ``normed=True`` and integer-like csgraph, where
+        the output dtype is 'float' allowing accurate normalization,
+        but dramatically increasing the memory use.
+        Default: None, for backward compatibility.
+    symmetrized: bool, optional
+        If True, then the output Laplacian is symmetric/Hermitian.
+        The symmetrization is done by ``csgraph + csgraph.T.conj``
+        without dividing by 2 to preserve integer dtypes if possible
+        prior to the construction of the Laplacian.
+        The symmetrization will increase the memory footprint of
+        sparse matrices unless the sparsity pattern is symmetric or
+        `form` is 'function' or 'lo'.
+        Default: False, for backward compatibility.
 
     Returns
     -------
-    lap : ndarray or sparse matrix
-        The N x N laplacian matrix of csgraph. It will be a NumPy array (dense)
-        if the input was dense, or a sparse matrix otherwise.
+    lap : ndarray, or sparse matrix, or `LinearOperator`
+        The N x N Laplacian of csgraph. It will be a NumPy array (dense)
+        if the input was dense, or a sparse matrix otherwise, or
+        the format of a function or `LinearOperator` if
+        `form` equals 'function' or 'lo', respectively.
     diag : ndarray, optional
-        The length-N diagonal of the Laplacian matrix.
+        The length-N main diagonal of the Laplacian matrix.
         For the normalized Laplacian, this is the array of square roots
         of vertex degrees or 1 if the degree is zero.
 
     Notes
     -----
     The Laplacian matrix of a graph is sometimes referred to as the
-    "Kirchoff matrix" or just the "Laplacian", and is useful in many
-    parts of spectral graph theory. In particular, the eigen-decomposition
-    of the Laplacian can give insight into many properties of the graph, e.g.,
-    is commonly used for spectal data enmedding and clustering.
-
-    The constructed Laplacian doubles the memory use if ``copy=True``,
-    which is the default. Choosing ``copy=False`` has no effect unless
-    the matrix is sparse in the ``coo`` format, or dense array, except
+    "Kirchhoff matrix" or just the "Laplacian", and is useful in many
+    parts of spectral graph theory.
+    In particular, the eigen-decomposition of the Laplacian can give
+    insight into many properties of the graph, e.g.,
+    is commonly used for spectral data embedding and clustering.
+
+    The constructed Laplacian doubles the memory use if ``copy=True`` and
+    ``form="array"`` which is the default.
+    Choosing ``copy=False`` has no effect unless ``form="array"``
+    or the matrix is sparse in the ``coo`` format, or dense array, except
     for the integer input with ``normed=True`` that forces the float output.
 
-    Sparse input is reformatted into ``coo``.
+    Sparse input is reformatted into ``coo`` if ``form="array"``,
+    which is the default.
 
-    If the input adjacency matrix is not symmetic, the Laplacian is also
-    non-symmetric and may need to be symmetrized; e.g., ``lap += lap.T``,
-    before the eigen-decomposition.
+    If the input adjacency matrix is not symmetic, the Laplacian is
+    also non-symmetric unless ``symmetrized=True`` is used.
 
     Diagonal entries of the input adjacency matrix are ignored and
     replaced with zeros for the purpose of normalization where ``normed=True``.
     The normalization uses the inverse square roots of row-sums of the input
     adjacency matrix, and thus may fail if the row-sums contain
-    zeros, negative, or complex with a non-zero imaginary part values.
+    negative or complex with a non-zero imaginary part values.
+
+    The normalization is symmetric, making the normalized Laplacian also
+    symmetric if the input csgraph was symmetric.
+
+    References
+    ----------
+    .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix
 
     Examples
     --------
     >>> from scipy.sparse import csgraph
-    >>> G = np.arange(5) * np.arange(5)[:, np.newaxis]
+
+    Our first illustration is the symmetric graph
+
+    >>> G = np.arange(4) * np.arange(4)[:, np.newaxis]
+    >>> G
+    array([[0, 0, 0, 0],
+           [0, 1, 2, 3],
+           [0, 2, 4, 6],
+           [0, 3, 6, 9]])
+
+    and its symmetric Laplacian matrix
+
+    >>> csgraph.laplacian(G)
+    array([[ 0,  0,  0,  0],
+           [ 0,  5, -2, -3],
+           [ 0, -2,  8, -6],
+           [ 0, -3, -6,  9]])
+
+    The non-symmetric graph
+
+    >>> G = np.arange(9).reshape(3, 3)
+    >>> G
+    array([[0, 1, 2],
+           [3, 4, 5],
+           [6, 7, 8]])
+
+    has different row- and column sums, resulting in two varieties
+    of the Laplacian matrix, using an in-degree, which is the default
+
+    >>> L_in_degree = csgraph.laplacian(G)
+    >>> L_in_degree
+    array([[ 9, -1, -2],
+           [-3,  8, -5],
+           [-6, -7,  7]])
+
+    or alternatively an out-degree
+
+    >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True)
+    >>> L_out_degree
+    array([[ 3, -1, -2],
+           [-3,  8, -5],
+           [-6, -7, 13]])
+
+    Constructing a symmetric Laplacian matrix, one can add the two as
+
+    >>> L_in_degree + L_out_degree.T
+    array([[ 12,  -4,  -8],
+            [ -4,  16, -12],
+            [ -8, -12,  20]])
+
+    or use the ``symmetrized=True`` option
+
+    >>> csgraph.laplacian(G, symmetrized=True)
+    array([[ 12,  -4,  -8],
+           [ -4,  16, -12],
+           [ -8, -12,  20]])
+
+    that is equivalent to symmetrizing the original graph
+
+    >>> csgraph.laplacian(G + G.T)
+    array([[ 12,  -4,  -8],
+           [ -4,  16, -12],
+           [ -8, -12,  20]])
+
+    The goal of normalization is to make the non-zero diagonal entries
+    of the Laplacian matrix to be all unit, also scaling off-diagonal
+    entries correspondingly. The normalization can be done manually, e.g.,
+
+    >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])
+    >>> L, d = csgraph.laplacian(G, return_diag=True)
+    >>> L
+    array([[ 2, -1, -1],
+           [-1,  2, -1],
+           [-1, -1,  2]])
+    >>> d
+    array([2, 2, 2])
+    >>> scaling = np.sqrt(d)
+    >>> scaling
+    array([1.41421356, 1.41421356, 1.41421356])
+    >>> (1/scaling)*L*(1/scaling)
+    array([[ 1. , -0.5, -0.5],
+           [-0.5,  1. , -0.5],
+           [-0.5, -0.5,  1. ]])
+
+    Or using ``normed=True`` option
+
+    >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
+    >>> L
+    array([[ 1. , -0.5, -0.5],
+           [-0.5,  1. , -0.5],
+           [-0.5, -0.5,  1. ]])
+
+    which now instead of the diagonal returns the scaling coefficients
+
+    >>> d
+    array([1.41421356, 1.41421356, 1.41421356])
+
+    Zero scaling coefficients are substituted with 1s, where scaling
+    has thus no effect, e.g.,
+
+    >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])
     >>> G
-    array([[ 0,  0,  0,  0,  0],
-           [ 0,  1,  2,  3,  4],
-           [ 0,  2,  4,  6,  8],
-           [ 0,  3,  6,  9, 12],
-           [ 0,  4,  8, 12, 16]])
-    >>> csgraph.laplacian(G, normed=False)
-    array([[  0,   0,   0,   0,   0],
-           [  0,   9,  -2,  -3,  -4],
-           [  0,  -2,  16,  -6,  -8],
-           [  0,  -3,  -6,  21, -12],
-           [  0,  -4,  -8, -12,  24]])
+    array([[0, 0, 0],
+           [0, 0, 1],
+           [0, 1, 0]])
+    >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
+    >>> L
+    array([[ 0., -0., -0.],
+           [-0.,  1., -1.],
+           [-0., -1.,  1.]])
+    >>> d
+    array([1., 1., 1.])
+
+    Only the symmetric normalization is implemented, resulting
+    in a symmetric Laplacian matrix if and only if its graph is symmetric
+    and has all non-negative degrees, like in the examples above.
+
+    The output Laplacian matrix is by default a dense array or a sparse matrix
+    inferring its shape, format, and dtype from the input graph matrix:
+
+    >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32)
+    >>> G
+    array([[0., 1., 1.],
+           [1., 0., 1.],
+           [1., 1., 0.]], dtype=float32)
+    >>> csgraph.laplacian(G)
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]], dtype=float32)
+
+    but can alternatively be generated matrix-free as a LinearOperator:
+
+    >>> L = csgraph.laplacian(G, form="lo")
+    >>> L
+    <3x3 _CustomLinearOperator with dtype=float32>
+    >>> L(np.eye(3))
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]])
+
+    or as a lambda-function:
+
+    >>> L = csgraph.laplacian(G, form="function")
+    >>> L
+    <function _laplace.<locals>.<lambda> at 0x0000012AE6F5A598>
+    >>> L(np.eye(3))
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]])
+
+    The Laplacian matrix is used for
+    spectral data clustering and embedding
+    as well as for spectral graph partitioning.
+    Our final example illustrates the latter
+    for a noisy directed linear graph.
+
+    >>> from scipy.sparse import diags, random
+    >>> from scipy.sparse.linalg import lobpcg
+
+    Create a directed linear graph with ``N=35`` vertices
+    using a sparse adjacency matrix ``G``:
+
+    >>> N = 35
+    >>> G = diags(np.ones(N-1), 1, format="csr")
+
+    Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``:
+
+    >>> rng = np.random.default_rng()
+    >>> G += 1e-2 * random(N, N, density=0.1, random_state=rng)
+
+    Set initial approximations for eigenvectors:
+
+    >>> X = rng.random((N, 2))
+
+    The constant vector of ones is always a trivial eigenvector
+    of the non-normalized Laplacian to be filtered out:
+
+    >>> Y = np.ones((N, 1))
+
+    Alternating (1) the sign of the graph weights allows determining
+    labels for spectral max- and min- cuts in a single loop.
+    Since the graph is undirected, the option ``symmetrized=True``
+    must be used in the construction of the Laplacian.
+    The option ``normed=True`` cannot be used in (2) for the negative weights
+    here as the symmetric normalization evaluates square roots.
+    The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees
+    a fixed memory footprint and read-only access to the graph.
+    Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector
+    that determines the labels as the signs of its components in (5).
+    Since the sign in an eigenvector is not deterministic and can flip,
+    we fix the sign of the first component to be always +1 in (4).
+
+    >>> for cut in ["max", "min"]:
+    ...     G = -G  # 1.
+    ...     L = csgraph.laplacian(G, symmetrized=True, form="lo")  # 2.
+    ...     _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-3)  # 3.
+    ...     eves *= np.sign(eves[0, 0])  # 4.
+    ...     print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0))  # 5.
+    max-cut labels:
+    [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
+    min-cut labels:
+    [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
+
+    As anticipated for a (slightly noisy) linear graph,
+    the max-cut strips all the edges of the graph coloring all
+    odd vertices into one color and all even vertices into another one,
+    while the balanced min-cut partitions the graph
+    in the middle by deleting a single edge.
+    Both determined partitions are optimal.
     """
     if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]:
         raise ValueError('csgraph must be a square matrix or array')
 
-    if normed and (np.issubdtype(csgraph.dtype, np.signedinteger)
-                   or np.issubdtype(csgraph.dtype, np.uint)):
-        csgraph = csgraph.astype(float)
+    if normed and (
+        np.issubdtype(csgraph.dtype, np.signedinteger)
+        or np.issubdtype(csgraph.dtype, np.uint)
+    ):
+        csgraph = csgraph.astype(np.float64)
+
+    if form == "array":
+        create_lap = (
+            _laplacian_sparse if isspmatrix(csgraph) else _laplacian_dense
+        )
+    else:
+        create_lap = (
+            _laplacian_sparse_flo
+            if isspmatrix(csgraph)
+            else _laplacian_dense_flo
+        )
 
-    create_lap = _laplacian_sparse if isspmatrix(csgraph) else _laplacian_dense
     degree_axis = 1 if use_out_degree else 0
-    lap, d = create_lap(csgraph, normed=normed, axis=degree_axis,
-                        copy=copy)
+
+    lap, d = create_lap(
+        csgraph,
+        normed=normed,
+        axis=degree_axis,
+        copy=copy,
+        form=form,
+        dtype=dtype,
+        symmetrized=symmetrized,
+    )
     if return_diag:
         return lap, d
     return lap
 
 
-def _setdiag_dense(A, d):
-    A.flat[::len(d)+1] = d
+def _setdiag_dense(m, d):
+    step = len(d) + 1
+    m.flat[::step] = d
+
+
+def _laplace(m, d):
+    return lambda v: v * d[:, np.newaxis] - m @ v
+
+
+def _laplace_normed(m, d, nd):
+    laplace = _laplace(m, d)
+    return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis])
+
+
+def _laplace_sym(m, d):
+    return (
+        lambda v: v * d[:, np.newaxis]
+        - m @ v
+        - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m))
+    )
+
+
+def _laplace_normed_sym(m, d, nd):
+    laplace_sym = _laplace_sym(m, d)
+    return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis])
+
+
+def _linearoperator(mv, shape, dtype):
+    return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype)
+
+
+def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized):
+    # The keyword argument `copy` is unused and has no effect here.
+    del copy
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    graph_sum = graph.sum(axis=axis).getA1()
+    graph_diagonal = graph.diagonal()
+    diag = graph_sum - graph_diagonal
+    if symmetrized:
+        graph_sum += graph.sum(axis=1 - axis).getA1()
+        diag = graph_sum - graph_diagonal - graph_diagonal
+
+    if normed:
+        isolated_node_mask = diag == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(diag))
+        if symmetrized:
+            md = _laplace_normed_sym(graph, graph_sum, 1.0 / w)
+        else:
+            md = _laplace_normed(graph, graph_sum, 1.0 / w)
+        if form == "function":
+            return md, w.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, w.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+    else:
+        if symmetrized:
+            md = _laplace_sym(graph, graph_sum)
+        else:
+            md = _laplace(graph, graph_sum)
+        if form == "function":
+            return md, diag.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, diag.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+
+
+def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized):
+    # The keyword argument `form` is unused and has no effect here.
+    del form
 
+    if dtype is None:
+        dtype = graph.dtype
 
-def _laplacian_sparse(graph, normed=False, axis=0,
-                      copy=True):
     needs_copy = False
     if graph.format in ('lil', 'dok'):
         m = graph.tocoo()
@@ -119,6 +451,10 @@ def _laplacian_sparse(graph, normed=False, axis=0,
         m = graph
         if copy:
             needs_copy = True
+
+    if symmetrized:
+        m += m.T.conj()
+
     w = m.sum(axis=axis).getA1() - m.diagonal()
     if normed:
         m = m.tocoo(copy=needs_copy)
@@ -135,16 +471,73 @@ def _laplacian_sparse(graph, normed=False, axis=0,
             m = m.tocoo(copy=needs_copy)
         m.data *= -1
         m.setdiag(w)
-    return m, w
 
+    return m.astype(dtype, copy=False), w.astype(dtype)
+
+
+def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized):
+
+    if copy:
+        m = np.array(graph)
+    else:
+        m = np.asarray(graph)
+
+    if dtype is None:
+        dtype = m.dtype
+
+    graph_sum = m.sum(axis=axis)
+    graph_diagonal = m.diagonal()
+    diag = graph_sum - graph_diagonal
+    if symmetrized:
+        graph_sum += m.sum(axis=1 - axis)
+        diag = graph_sum - graph_diagonal - graph_diagonal
+
+    if normed:
+        isolated_node_mask = diag == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(diag))
+        if symmetrized:
+            md = _laplace_normed_sym(m, graph_sum, 1.0 / w)
+        else:
+            md = _laplace_normed(m, graph_sum, 1.0 / w)
+        if form == "function":
+            return md, w.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, w.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+    else:
+        if symmetrized:
+            md = _laplace_sym(m, graph_sum)
+        else:
+            md = _laplace(m, graph_sum)
+        if form == "function":
+            return md, diag.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, diag.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+
+
+def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized):
+
+    if form != "array":
+        raise ValueError('{form!r} must be "array"')
+
+    if dtype is None:
+        dtype = graph.dtype
 
-def _laplacian_dense(graph, normed=False, axis=0,
-                     copy=True):
     if copy:
         m = np.array(graph)
     else:
         m = np.asarray(graph)
 
+    if dtype is None:
+        dtype = m.dtype
+
+    if symmetrized:
+        m += m.T.conj()
     np.fill_diagonal(m, 0)
     w = m.sum(axis=axis)
     if normed:
@@ -157,4 +550,5 @@ def _laplacian_dense(graph, normed=False, axis=0,
     else:
         m *= -1
         _setdiag_dense(m, w)
-    return m, w
+
+    return m.astype(dtype, copy=False), w.astype(dtype, copy=False)


Test patch:
diff --git a/scipy/sparse/csgraph/tests/test_graph_laplacian.py b/scipy/sparse/csgraph/tests/test_graph_laplacian.py
--- a/scipy/sparse/csgraph/tests/test_graph_laplacian.py
+++ b/scipy/sparse/csgraph/tests/test_graph_laplacian.py
@@ -1,7 +1,3 @@
-# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
-#         Jake Vanderplas <vanderplas@astro.washington.edu>
-#         Andrew Knyazev <Andrew.Knyazev@ucdenver.edu>
-# License: BSD
 import pytest
 import numpy as np
 from numpy.testing import assert_allclose
@@ -11,6 +7,12 @@
 from scipy.sparse import csgraph
 
 
+def check_int_type(mat):
+    return np.issubdtype(mat.dtype, np.signedinteger) or np.issubdtype(
+        mat.dtype, np.uint
+    )
+
+
 def test_laplacian_value_error():
     for t in int, float, complex:
         for m in ([1, 1],
@@ -59,8 +61,7 @@ def _check_symmetric_graph_laplacian(mat, normed, copy=True):
         assert_allclose(mat, mat_copy)
         _assert_allclose_sparse(sp_mat, sp_mat_copy)
     else:
-        if not (normed and (np.issubdtype(mat.dtype, np.signedinteger)
-                            or np.issubdtype(mat.dtype, np.uint))):
+        if not (normed and check_int_type(mat)):
             assert_allclose(laplacian, mat)
             if sp_mat.format == 'coo':
                 _assert_allclose_sparse(sp_laplacian, sp_mat)
@@ -99,29 +100,71 @@ def _assert_allclose_sparse(a, b, **kwargs):
     assert_allclose(a, b, **kwargs)
 
 
-def _check_laplacian(A, desired_L, desired_d,
-                     normed, use_out_degree, copy, dtype, arr_type):
+def _check_laplacian_dtype_none(
+    A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type
+):
+    mat = arr_type(A, dtype=dtype)
+    L, d = csgraph.laplacian(
+        mat,
+        normed=normed,
+        return_diag=True,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=None,
+    )
+    if normed and check_int_type(mat):
+        assert L.dtype == np.float64
+        assert d.dtype == np.float64
+        _assert_allclose_sparse(L, desired_L, atol=1e-12)
+        _assert_allclose_sparse(d, desired_d, atol=1e-12)
+    else:
+        assert L.dtype == dtype
+        assert d.dtype == dtype
+        desired_L = np.asarray(desired_L).astype(dtype)
+        desired_d = np.asarray(desired_d).astype(dtype)
+        _assert_allclose_sparse(L, desired_L, atol=1e-12)
+        _assert_allclose_sparse(d, desired_d, atol=1e-12)
+
+    if not copy:
+        if not (normed and check_int_type(mat)):
+            if type(mat) is np.ndarray:
+                assert_allclose(L, mat)
+            elif mat.format == "coo":
+                _assert_allclose_sparse(L, mat)
+
+
+def _check_laplacian_dtype(
+    A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type
+):
     mat = arr_type(A, dtype=dtype)
-    L, d = csgraph.laplacian(mat, normed=normed, return_diag=True,
-                             use_out_degree=use_out_degree,
-                             copy=copy)
+    L, d = csgraph.laplacian(
+        mat,
+        normed=normed,
+        return_diag=True,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+    )
+    assert L.dtype == dtype
+    assert d.dtype == dtype
+    desired_L = np.asarray(desired_L).astype(dtype)
+    desired_d = np.asarray(desired_d).astype(dtype)
     _assert_allclose_sparse(L, desired_L, atol=1e-12)
     _assert_allclose_sparse(d, desired_d, atol=1e-12)
 
     if not copy:
-        if not (normed and (np.issubdtype(mat.dtype, np.signedinteger)
-                            or np.issubdtype(mat.dtype, np.uint))):
+        if not (normed and check_int_type(mat)):
             if type(mat) is np.ndarray:
                 assert_allclose(L, mat)
             elif mat.format == 'coo':
                 _assert_allclose_sparse(L, mat)
 
 
-REAL_DTYPES = {np.intc, np.int_, np.longlong,
-               np.single, np.double, np.longdouble}
+INT_DTYPES = {np.intc, np.int_, np.longlong}
+REAL_DTYPES = {np.single, np.double, np.longdouble}
 COMPLEX_DTYPES = {np.csingle, np.cdouble, np.clongdouble}
 # use sorted tuple to ensure fixed order of tests
-DTYPES = tuple(sorted(REAL_DTYPES ^ COMPLEX_DTYPES, key=str))
+DTYPES = tuple(sorted(INT_DTYPES ^ REAL_DTYPES ^ COMPLEX_DTYPES, key=str))
 
 
 @pytest.mark.parametrize("dtype", DTYPES)
@@ -138,6 +181,7 @@ def test_asymmetric_laplacian(use_out_degree, normed,
          [4, 2, 0],
          [0, 0, 0]]
     A = arr_type(np.array(A), dtype=dtype)
+    A_copy = A.copy()
 
     if not normed and use_out_degree:
         # Laplacian matrix using out-degree
@@ -167,12 +211,27 @@ def test_asymmetric_laplacian(use_out_degree, normed,
              [0, 0, 0]]
         d = [2, 1, 1]
 
-    _check_laplacian(A, L, d,
-                     normed=normed,
-                     use_out_degree=use_out_degree,
-                     copy=copy,
-                     dtype=dtype,
-                     arr_type=arr_type)
+    _check_laplacian_dtype_none(
+        A,
+        L,
+        d,
+        normed=normed,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+        arr_type=arr_type,
+    )
+
+    _check_laplacian_dtype(
+        A_copy,
+        L,
+        d,
+        normed=normed,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+        arr_type=arr_type,
+    )
 
 
 @pytest.mark.parametrize("fmt", ['csr', 'csc', 'coo', 'lil',
@@ -182,3 +241,118 @@ def test_asymmetric_laplacian(use_out_degree, normed,
 def test_sparse_formats(fmt, normed, copy):
     mat = sparse.diags([1, 1], [-1, 1], shape=(4, 4), format=fmt)
     _check_symmetric_graph_laplacian(mat, normed, copy)
+
+
+@pytest.mark.parametrize(
+    "arr_type", [np.asarray, sparse.csr_matrix, sparse.coo_matrix]
+)
+@pytest.mark.parametrize("form", ["array", "function", "lo"])
+def test_laplacian_symmetrized(arr_type, form):
+    # adjacency matrix
+    n = 3
+    mat = arr_type(np.arange(n * n).reshape(n, n))
+    L_in, d_in = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        form=form,
+    )
+    L_out, d_out = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        use_out_degree=True,
+        form=form,
+    )
+    Ls, ds = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        symmetrized=True,
+        form=form,
+    )
+    Ls_normed, ds_normed = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        symmetrized=True,
+        normed=True,
+        form=form,
+    )
+    mat += mat.T
+    Lss, dss = csgraph.laplacian(mat, return_diag=True, form=form)
+    Lss_normed, dss_normed = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=True,
+        form=form,
+    )
+
+    assert_allclose(ds, d_in + d_out)
+    assert_allclose(ds, dss)
+    assert_allclose(ds_normed, dss_normed)
+
+    d = {}
+    for L in ["L_in", "L_out", "Ls", "Ls_normed", "Lss", "Lss_normed"]:
+        if form == "array":
+            d[L] = eval(L)
+        else:
+            d[L] = eval(L)(np.eye(n, dtype=mat.dtype))
+
+    _assert_allclose_sparse(d["Ls"], d["L_in"] + d["L_out"].T)
+    _assert_allclose_sparse(d["Ls"], d["Lss"])
+    _assert_allclose_sparse(d["Ls_normed"], d["Lss_normed"])
+
+
+@pytest.mark.parametrize(
+    "arr_type", [np.asarray, sparse.csr_matrix, sparse.coo_matrix]
+)
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("symmetrized", [True, False])
+@pytest.mark.parametrize("use_out_degree", [True, False])
+@pytest.mark.parametrize("form", ["function", "lo"])
+def test_format(dtype, arr_type, normed, symmetrized, use_out_degree, form):
+    n = 3
+    mat = [[0, 1, 0], [4, 2, 0], [0, 0, 0]]
+    mat = arr_type(np.array(mat), dtype=dtype)
+    Lo, do = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+    )
+    La, da = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+        form="array",
+    )
+    assert_allclose(do, da)
+    _assert_allclose_sparse(Lo, La)
+
+    L, d = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+        form=form,
+    )
+    assert_allclose(d, do)
+    assert d.dtype == dtype
+    Lm = L(np.eye(n, dtype=mat.dtype)).astype(dtype)
+    _assert_allclose_sparse(Lm, Lo, rtol=2e-7, atol=2e-7)
+    x = np.arange(6).reshape(3, 2)
+    if not (normed and dtype in INT_DTYPES):
+        assert_allclose(L(x), Lo @ x)
+    else:
+        # Normalized Lo is casted to integer, but L() is not
+        pass
+
+
+def test_format_error_message():
+    with pytest.raises(ValueError, match="Invalid form: 'toto'"):
+        _ = csgraph.laplacian(np.eye(1), form='toto')