Skip to content

dense_to_sparse

dense_to_sparse(
    adj: array, mask: Optional[array] = None
) -> tuple[array, array]

Converts a dense adjacency matrix, or a batch of them, to an edge_index and edge weights (the non-zero entries).

For a batch of adjacency matrices of shape [batch_size, num_nodes, num_nodes], the graphs are stacked as one block-diagonal graph: the nodes of graph b are offset by b * num_nodes, or, if mask is given, by the number of valid nodes of the previous graphs (only the rows of the valid nodes are read).

Parameters:

Name Type Description Default
adj array

Dense adjacency of shape [num_nodes, num_nodes] or [batch_size, num_nodes, num_nodes].

required
mask Optional[array]

Optional boolean mask of the valid nodes of each graph, of shape [batch_size, num_nodes] (e.g. from to_dense_batch()). Only used for batched adjacencies. Default: None

None

Returns:

Type Description
tuple[array, array]

A tuple (edge_index, edge_weights) with an int32 edge_index.

Example:

adj = mx.array([[0, 1, 0], [2, 0, 0], [0, 0, 3]])
dense_to_sparse(adj)
# (mx.array([[0, 1, 2], [1, 0, 2]]), mx.array([1, 2, 3]))
Source code in mlx_graphs/utils/sparse.py
def dense_to_sparse(
    adj: mx.array, mask: Optional[mx.array] = None
) -> tuple[mx.array, mx.array]:
    """
    Converts a dense adjacency matrix, or a batch of them, to an
    ``edge_index`` and edge weights (the non-zero entries).

    For a batch of adjacency matrices of shape ``[batch_size, num_nodes,
    num_nodes]``, the graphs are stacked as one block-diagonal graph: the
    nodes of graph ``b`` are offset by ``b * num_nodes``, or, if ``mask`` is
    given, by the number of valid nodes of the previous graphs (only the rows
    of the valid nodes are read).

    Args:
        adj: Dense adjacency of shape ``[num_nodes, num_nodes]`` or
            ``[batch_size, num_nodes, num_nodes]``.
        mask: Optional boolean mask of the valid nodes of each graph, of shape
            ``[batch_size, num_nodes]`` (e.g. from
            :func:`~mlx_graphs.utils.to_dense_batch`). Only used for batched
            adjacencies. Default: ``None``

    Returns:
        A tuple ``(edge_index, edge_weights)`` with an int32 ``edge_index``.

    Example:

    .. code-block:: python

        adj = mx.array([[0, 1, 0], [2, 0, 0], [0, 0, 3]])
        dense_to_sparse(adj)
        # (mx.array([[0, 1, 2], [1, 0, 2]]), mx.array([1, 2, 3]))
    """
    if adj.ndim < 2 or adj.ndim > 3:
        raise ValueError(
            "Dense adjacency matrix `adj` must be two- or three-dimensional "
            f"(got {adj.ndim} dimensions)"
        )
    if mask is not None and adj.ndim == 2:
        mask = None  # ignored, as in PyG
    if mask is not None and mask.ndim != 2:
        raise ValueError(f"Mask must be two-dimensional (got {mask.ndim} dimensions)")
    if mask is not None and adj.shape[-2] != adj.shape[-1]:
        raise ValueError(
            "Mask is only supported on square adjacency matrices "
            f"(got {list(adj.shape)})"
        )

    adj_np = np.asarray(adj)
    if adj.ndim == 2:
        row, col = np.nonzero(adj_np)
        edge_weights = adj[mx.array(row), mx.array(col)] if row.size else adj[0, :0]
        return mx.array(np.stack([row, col]).astype(np.int32)), edge_weights

    batch_size, num_rows, num_cols = adj.shape
    flat = adj.reshape(-1, num_cols)
    if mask is None:
        offset = np.repeat(np.arange(batch_size) * num_cols, num_rows)
        rows = np.arange(batch_size * num_rows)
    else:
        mask_np = np.asarray(mask).astype(bool).reshape(-1)
        rows = np.nonzero(mask_np)[0]
        count = np.asarray(mask).astype(bool).sum(axis=-1)
        offset = np.repeat(np.concatenate([[0], np.cumsum(count)[:-1]]), count)
    row, col = np.nonzero(adj_np.reshape(-1, num_cols)[rows])
    if row.size == 0:
        return mx.zeros((2, 0), dtype=mx.int32), flat[0, :0]
    edge_weights = flat[mx.array(rows[row]), mx.array(col)]
    col = col + offset[row]
    return mx.array(np.stack([row, col]).astype(np.int32)), edge_weights

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