Skip to content

remove_self_loops

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

Removes self-loops from the given graph represented by edge_index and edge_features.

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 tensor representing features associated with each edge, with shape [num_edges, num_edge_features]

None

Returns:

Type Description
Union[array, tuple[array, array]]

A tuple containing the updated edge_index and edge_features without self-loops.

Source code in mlx_graphs/utils/transformations.py
@validate_edge_index_and_features
def remove_self_loops(
    edge_index: mx.array,
    edge_features: Optional[mx.array] = None,
) -> Union[mx.array, tuple[mx.array, mx.array]]:
    """
    Removes self-loops from the given graph represented by edge_index and edge_features.

    Args:
        edge_index: a [2, num_edges] array representing the source and target nodes
            of each edge
        edge_features: Optional tensor representing features associated with each edge,
            with shape [num_edges, num_edge_features]

    Returns:
        A tuple containing the updated edge_index and edge_features without self-loops.

    """
    edges = _to_numpy(edge_index)
    keep = np.nonzero(edges[0] != edges[1])[0]
    if keep.size == edges.shape[1]:  # nothing to remove
        if edge_features is not None:
            return edge_index, edge_features
        return edge_index

    no_self_loop_index = _take_edges(edge_index, keep)
    if edge_features is not None:
        if keep.size == 0:
            return no_self_loop_index, mx.zeros(
                (0, *edge_features.shape[1:]), dtype=edge_features.dtype
            )
        return no_self_loop_index, edge_features[mx.array(keep)]
    return no_self_loop_index

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