Skip to content

to_scipy_sparse_matrix

to_scipy_sparse_matrix(
    edge_index: array,
    edge_features: Optional[array] = None,
    num_nodes: Optional[int] = None,
) -> Any

Converts a graph given by edge_index (and optional scalar edge features) to a scipy.sparse.coo_matrix. Requires scipy.

Parameters:

Name Type Description Default
edge_index array

a [2, num_edges] array representing the source and target nodes of each edge

required
edge_features Optional[array]

Optional scalar weight of each edge, of shape [num_edges] or [num_edges, 1]. Default: None (all ones)

None
num_nodes Optional[int]

Number of nodes in the graph. Inferred from edge_index if not given.

None

Returns:

Type Description
Any

A scipy.sparse.coo_matrix of shape [num_nodes, num_nodes].

Example:

edge_index = mx.array([[0, 1, 1], [1, 0, 2]])
to_scipy_sparse_matrix(edge_index).toarray()
# array([[0., 1., 0.],
#        [1., 0., 1.],
#        [0., 0., 0.]], dtype=float32)
Source code in mlx_graphs/utils/sparse.py
@validate_edge_index_and_features
def to_scipy_sparse_matrix(
    edge_index: mx.array,
    edge_features: Optional[mx.array] = None,
    num_nodes: Optional[int] = None,
) -> Any:
    """
    Converts a graph given by ``edge_index`` (and optional scalar edge
    features) to a ``scipy.sparse.coo_matrix``. Requires ``scipy``.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge
        edge_features: Optional scalar weight of each edge, of shape
            ``[num_edges]`` or ``[num_edges, 1]``. Default: ``None`` (all
            ones)
        num_nodes: Number of nodes in the graph. Inferred from ``edge_index``
            if not given.

    Returns:
        A ``scipy.sparse.coo_matrix`` of shape ``[num_nodes, num_nodes]``.

    Example:

    .. code-block:: python

        edge_index = mx.array([[0, 1, 1], [1, 0, 2]])
        to_scipy_sparse_matrix(edge_index).toarray()
        # array([[0., 1., 0.],
        #        [1., 0., 1.],
        #        [0., 0., 0.]], dtype=float32)
    """
    import scipy.sparse as sp

    edges = _to_numpy(edge_index)
    if edge_features is None:
        values = np.ones(edges.shape[1], dtype=np.float32)
    else:
        values = np.asarray(edge_features).reshape(-1)
        if values.size != edges.shape[1]:
            raise ValueError(
                "`edge_features` must hold one scalar per edge "
                f"(got shape {edge_features.shape})"
            )
    n = _infer_num_nodes(edge_index, num_nodes)
    return sp.coo_matrix((values, (edges[0], edges[1])), shape=(n, n))

from mlx_graphs.utils import to_scipy_sparse_matrix · mlx_graphs/utils/sparse.py