Skip to content

to_dense_adj

to_dense_adj(
    edge_index: array,
    batch_indices: Optional[array] = None,
    edge_features: Optional[array] = None,
    max_num_nodes: Optional[int] = None,
) -> array

Converts the edges of a batch of graphs to dense adjacency matrices of shape [batch_size, max_num_nodes, max_num_nodes].

Entry [b, i, j] holds the edge from the i-th to the j-th node of graph b. Duplicate edges are summed.

Parameters:

Name Type Description Default
edge_index array

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

required
batch_indices Optional[array]

Array of shape [num_nodes] with the graph of each node (e.g. GraphDataBatch.batch_indices). Default: None (a single graph, whose size is inferred from edge_index).

None
edge_features Optional[array]

Optional features of each edge, of shape [num_edges, ...], used as the values of the adjacency matrices. Default: None (ones).

None
max_num_nodes Optional[int]

Number of nodes per graph in the output. Edges of nodes beyond that size are dropped. Default: None (the size of the largest graph).

None

Returns:

Type Description
array

The dense adjacency matrices, of shape

array

[batch_size, max_num_nodes, max_num_nodes, ...] (the trailing

array

dimensions are those of edge_features). The dtype is the one of

array

edge_features, or float32 if they are not given.

Example:

edge_index = mx.array([[0, 0, 1, 2, 3], [0, 1, 0, 3, 2]])
batch_indices = mx.array([0, 0, 1, 1])

to_dense_adj(edge_index, batch_indices)
# mx.array([[[1, 1], [1, 0]], [[0, 1], [1, 0]]])
Source code in mlx_graphs/utils/dense.py
@validate_edge_index
def to_dense_adj(
    edge_index: mx.array,
    batch_indices: Optional[mx.array] = None,
    edge_features: Optional[mx.array] = None,
    max_num_nodes: Optional[int] = None,
) -> mx.array:
    """
    Converts the edges of a batch of graphs to dense adjacency matrices of
    shape ``[batch_size, max_num_nodes, max_num_nodes]``.

    Entry ``[b, i, j]`` holds the edge from the ``i``-th to the ``j``-th node
    of graph ``b``. Duplicate edges are summed.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge
        batch_indices: Array of shape ``[num_nodes]`` with the graph of each
            node (e.g. ``GraphDataBatch.batch_indices``). Default: ``None``
            (a single graph, whose size is inferred from ``edge_index``).
        edge_features: Optional features of each edge, of shape
            ``[num_edges, ...]``, used as the values of the adjacency
            matrices. Default: ``None`` (ones).
        max_num_nodes: Number of nodes per graph in the output. Edges of nodes
            beyond that size are dropped. Default: ``None`` (the size of the
            largest graph).

    Returns:
        The dense adjacency matrices, of shape
        ``[batch_size, max_num_nodes, max_num_nodes, ...]`` (the trailing
        dimensions are those of ``edge_features``). The dtype is the one of
        ``edge_features``, or float32 if they are not given.

    Example:

    .. code-block:: python

        edge_index = mx.array([[0, 0, 1, 2, 3], [0, 1, 0, 3, 2]])
        batch_indices = mx.array([0, 0, 1, 1])

        to_dense_adj(edge_index, batch_indices)
        # mx.array([[[1, 1], [1, 0]], [[0, 1], [1, 0]]])
    """
    num_edges = edge_index.shape[1]
    if edge_features is not None and edge_features.shape[0] != num_edges:
        raise ValueError(
            "edge_features must be 1 per edge "
            f"(got {num_edges} edges and {edge_features.shape[0]} features)"
        )
    edges = _to_numpy(edge_index).astype(np.int64)
    max_node = int(edges.max()) if edges.size > 0 else -1
    if batch_indices is None:
        num_nodes = max_node + 1
    else:
        num_nodes = batch_indices.size
        if max_node >= num_nodes:
            raise ValueError(
                f"batch_indices has {num_nodes} entries but `edge_index` "
                f"contains node {max_node}"
            )
    batch, local, batch_size, largest = _batch_layout(batch_indices, num_nodes)
    if max_num_nodes is None:
        max_num_nodes = largest

    graph, row, col = batch[edges[0]], local[edges[0]], local[edges[1]]
    keep = np.nonzero((row < max_num_nodes) & (col < max_num_nodes))[0]

    if edge_features is None:
        feature_shape: tuple = ()
        dtype = mx.float32
    else:
        feature_shape = tuple(edge_features.shape[1:])
        dtype = edge_features.dtype
    adj = mx.zeros((batch_size * max_num_nodes * max_num_nodes, *feature_shape), dtype)

    if keep.size > 0:
        flat = (graph[keep] * max_num_nodes + row[keep]) * max_num_nodes + col[keep]
        if edge_features is None:
            values = mx.ones((keep.size,), dtype=dtype)
        elif keep.size < num_edges:
            values = edge_features[mx.array(keep)]
        else:
            values = edge_features
        adj = adj.at[mx.array(flat)].add(values)

    return adj.reshape(batch_size, max_num_nodes, max_num_nodes, *feature_shape)

from mlx_graphs.utils import to_dense_adj · mlx_graphs/utils/dense.py