Skip to content

to_sparse_adjacency_matrix

to_sparse_adjacency_matrix(
    adjacency_matrix: array, *, dtype: Dtype = uint32
) -> tuple[array, array]

Converts an adjacency matrix to a sparse representation as a tuple of edge index and edge features.

Parameters:

Name Type Description Default
adjacency_matrix array

the input adjacency matrix

required
dtype Dtype

type of the output edge_index. Default to uint32.

uint32

Returns:

Type Description
tuple[array, array]

A tuple representing the edge index and edge features

Example:

matrix = mx.array(
    [
        [0, 1, 2],
        [3, 0, 0],
        [5, 1, 2],
    ]
)
edge_index, edge_features = to_sparse_adjacency_matrix(matrix)

edge_index
# mx.array([[0, 0, 1, 2, 2, 2], [1, 2, 0, 0, 1, 2]])

edge_features
# mx.array([1, 2, 3, 5, 1, 2])
Source code in mlx_graphs/utils/transformations.py
@validate_adjacency_matrix
def to_sparse_adjacency_matrix(
    adjacency_matrix: mx.array, *, dtype: mx.Dtype = mx.uint32
) -> tuple[mx.array, mx.array]:
    """
    Converts an adjacency matrix to a sparse representation as a tuple of edge index
    and edge features.

    Args:
        adjacency_matrix: the input adjacency matrix
        dtype: type of the output edge_index. Default to uint32.

    Returns:
        A tuple representing the edge index and edge features

    Example:

    .. code-block:: python

        matrix = mx.array(
            [
                [0, 1, 2],
                [3, 0, 0],
                [5, 1, 2],
            ]
        )
        edge_index, edge_features = to_sparse_adjacency_matrix(matrix)

        edge_index
        # mx.array([[0, 0, 1, 2, 2, 2], [1, 2, 0, 0, 1, 2]])

        edge_features
        # mx.array([1, 2, 3, 5, 1, 2])
    """
    edge_index = to_edge_index(adjacency_matrix)
    edge_features = adjacency_matrix[edge_index[0], edge_index[1]]
    return edge_index, mx.expand_dims(edge_features, 1)

from mlx_graphs.utils.transformations import to_sparse_adjacency_matrix · mlx_graphs/utils/transformations.py