Skip to content

to_edge_index

to_edge_index(adjacency_matrix: array, *, dtype: Dtype = uint32) -> array

Converts an adjacency matrix to an edge index representation.

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
array

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

Example:

matrix = mx.array(
    [
        [0, 1, 2],
        [3, 0, 0],
        [5, 1, 2],
    ]
)
edge_index = to_edge_index(matrix)
# mx.array([[0, 0, 1, 2, 2, 2], [1, 2, 0, 0, 1, 2]])
Source code in mlx_graphs/utils/transformations.py
@validate_adjacency_matrix
def to_edge_index(
    adjacency_matrix: mx.array, *, dtype: mx.Dtype = mx.uint32
) -> mx.array:
    """
    Converts an adjacency matrix to an edge index representation.

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

    Returns:
        A [2, num_edges] array representing the source and target nodes of each edge

    Example:

    .. code-block:: python

        matrix = mx.array(
            [
                [0, 1, 2],
                [3, 0, 0],
                [5, 1, 2],
            ]
        )
        edge_index = to_edge_index(matrix)
        # mx.array([[0, 0, 1, 2, 2, 2], [1, 2, 0, 0, 1, 2]])
    """
    edge_index = mx.stack(
        [
            mx.array(x, dtype=dtype)
            for x in np.nonzero(np.array(adjacency_matrix, copy=False))
        ]
    )
    return edge_index

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