Skip to content

unbatch_edge_index

unbatch_edge_index(
    edge_index: array, batch_indices: array, batch_size: Optional[int] = None
) -> list[array]

Splits the edge_index of a batch of graphs into one edge_index per graph, with the node ids of each graph starting at 0.

Parameters:

Name Type Description Default
edge_index array

a [2, num_edges] array representing the source and target nodes of each edge of the batch, with the edges of each graph stored contiguously and in graph order.

required
batch_indices array

The graph of each node, of shape [num_nodes], with the nodes of each graph stored contiguously and in graph order.

required
batch_size Optional[int]

Number of graphs. Inferred from batch_indices if not given.

None

Returns:

Type Description
list[array]

A list with the edge_index of each graph.

Example:

edge_index = mx.array([[0, 1, 1, 2, 4, 5, 5, 6], [1, 0, 2, 1, 5, 4, 6, 5]])
batch_indices = mx.array([0, 0, 0, 0, 1, 1, 1])
unbatch_edge_index(edge_index, batch_indices)
# [mx.array([[0, 1, 1, 2], [1, 0, 2, 1]]),
#  mx.array([[0, 1, 1, 2], [1, 0, 2, 1]])]
Source code in mlx_graphs/utils/unbatch.py
@validate_edge_index
def unbatch_edge_index(
    edge_index: mx.array,
    batch_indices: mx.array,
    batch_size: Optional[int] = None,
) -> list[mx.array]:
    """
    Splits the ``edge_index`` of a batch of graphs into one ``edge_index`` per
    graph, with the node ids of each graph starting at 0.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge of the batch, with the edges of each graph
            stored contiguously and in graph order.
        batch_indices: The graph of each node, of shape ``[num_nodes]``, with
            the nodes of each graph stored contiguously and in graph order.
        batch_size: Number of graphs. Inferred from ``batch_indices`` if not
            given.

    Returns:
        A list with the ``edge_index`` of each graph.

    Example:

    .. code-block:: python

        edge_index = mx.array([[0, 1, 1, 2, 4, 5, 5, 6], [1, 0, 2, 1, 5, 4, 6, 5]])
        batch_indices = mx.array([0, 0, 0, 0, 1, 1, 1])
        unbatch_edge_index(edge_index, batch_indices)
        # [mx.array([[0, 1, 1, 2], [1, 0, 2, 1]]),
        #  mx.array([[0, 1, 1, 2], [1, 0, 2, 1]])]
    """
    num_nodes = _graph_sizes(batch_indices, batch_size)
    ptr = np.concatenate([[0], np.cumsum(num_nodes)[:-1]])
    batch = _to_numpy(batch_indices).astype(np.int64).reshape(-1)
    edges = _to_numpy(edge_index).astype(np.int64)
    edge_batch = batch[edges[0]]
    local = mx.array(edges - ptr[edge_batch], dtype=edge_index.dtype)
    sizes = np.bincount(edge_batch, minlength=num_nodes.size)
    return _split(local, sizes, axis=1)

from mlx_graphs.utils import unbatch_edge_index · mlx_graphs/utils/unbatch.py