Skip to content

segregate_self_loops

segregate_self_loops(
    edge_index: array, edge_features: Optional[array] = None
) -> tuple[array, Optional[array], array, Optional[array]]

Splits the edges of a graph into the self-loops and the other edges.

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]

Optional features of each edge, of shape [num_edges, ...]. Default: None

None

Returns:

Type Description
array

A tuple `(edge_index, edge_features, loop_edge_index,

Optional[array]

loop_edge_features)` with the edges that are not self-loops, their

array

features, the self-loops and their features (features are None if

Optional[array]

edge_features was not given).

Example:

edge_index = mx.array([[0, 0, 1], [0, 1, 0]])
segregate_self_loops(edge_index)
# (mx.array([[0, 1], [1, 0]]), None, mx.array([[0], [0]]), None)
Source code in mlx_graphs/utils/loop.py
@validate_edge_index_and_features
def segregate_self_loops(
    edge_index: mx.array,
    edge_features: Optional[mx.array] = None,
) -> tuple[mx.array, Optional[mx.array], mx.array, Optional[mx.array]]:
    """
    Splits the edges of a graph into the self-loops and the other edges.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge
        edge_features: Optional features of each edge, of shape
            ``[num_edges, ...]``. Default: ``None``

    Returns:
        A tuple ``(edge_index, edge_features, loop_edge_index,
        loop_edge_features)`` with the edges that are not self-loops, their
        features, the self-loops and their features (features are ``None`` if
        ``edge_features`` was not given).

    Example:

    .. code-block:: python

        edge_index = mx.array([[0, 0, 1], [0, 1, 0]])
        segregate_self_loops(edge_index)
        # (mx.array([[0, 1], [1, 0]]), None, mx.array([[0], [0]]), None)
    """
    edges = _to_numpy(edge_index)
    is_loop = edges[0] == edges[1]
    keep, loops = np.nonzero(~is_loop)[0], np.nonzero(is_loop)[0]

    out_features = loop_features = None
    if edge_features is not None:
        out_features = _take_rows(edge_features, keep)
        loop_features = _take_rows(edge_features, loops)
    return (
        _take_edges(edge_index, keep),
        out_features,
        _take_edges(edge_index, loops),
        loop_features,
    )

from mlx_graphs.utils import segregate_self_loops · mlx_graphs/utils/loop.py