Skip to content

to_adjacency_matrix

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

Converts an edge index representation to an adjacency matrix.

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]

a 1-dimensional array representing the features corresponding to the edges in edge_index. Defaults to None.

None
num_nodes Optional[int]

the number of nodes in the graph. Defaults to the number of nodes in edge_index

None

Returns:

Type Description
array

The resulting adjacency matrix

Source code in mlx_graphs/utils/transformations.py
@validate_edge_index_and_features
def to_adjacency_matrix(
    edge_index: mx.array,
    edge_features: Optional[mx.array] = None,
    num_nodes: Optional[int] = None,
) -> mx.array:
    """
    Converts an edge index representation to an adjacency matrix.

    Args:
        edge_index: a [2, num_edges] array representing the source and target nodes
            of each edge
        edge_features: a 1-dimensional array representing the features corresponding
            to the edges in edge_index. Defaults to None.
        num_nodes: the number of nodes in the graph. Defaults to the number of nodes
            in edge_index

    Returns:
        The resulting adjacency matrix
    """
    if num_nodes is not None:
        if mx.max(edge_index) > num_nodes - 1:
            raise ValueError(
                "num_nodes must be >= than the number of nodes in the edge_index ",
                f"(got num_nodes={num_nodes} and {mx.max(edge_index) + 1}",
                "nodes in index",
            )
    else:
        num_nodes = (mx.max(edge_index) + 1).item()

    if edge_features is not None:
        if edge_features.ndim != 1:
            raise ValueError(
                "edge_features must be 1-dimensional",
                f"(got {edge_features.ndim} dimensions)",
            )

    adjacency_matrix = mx.zeros((num_nodes, num_nodes), dtype=edge_index.dtype)
    if edge_features is None:
        adjacency_matrix[edge_index[0], edge_index[1]] = 1
    else:
        adjacency_matrix[edge_index[0], edge_index[1]] = edge_features
    return adjacency_matrix

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