Skip to content

degree

degree(
    index: array,
    num_nodes: Optional[int] = None,
    edge_weights: Optional[array] = None,
) -> array

Counts the number of ocurrences of each node in the given index.

Parameters:

Name Type Description Default
index array

Array with node indices, usually src or dst of an edge_index.

required
num_nodes Optional[int]

Size of the output degree array. If not provided, the number of nodes will be inferred from the index.

None
edge_weights Optional[array]

Optional edge weights that will be leveraged instead of 1 values during the degree compute. Default: None

None

Returns:

Type Description
array

Array of length num_nodes with the degree of each node.

Source code in mlx_graphs/utils/scatter.py
def degree(
    index: mx.array,
    num_nodes: Optional[int] = None,
    edge_weights: Optional[mx.array] = None,
) -> mx.array:
    """Counts the number of ocurrences of each node in the given `index`.

    Args:
        index: Array with node indices, usually src or dst of an `edge_index`.
        num_nodes: Size of the output degree array. If not provided, the number
            of nodes will be inferred from the `index`.
        edge_weights: Optional edge weights that will be leveraged instead
            of 1 values during the degree compute. Default: ``None``

    Returns:
        Array of length `num_nodes` with the degree of each node.
    """
    if index.ndim != 1:
        raise ValueError(
            f"The `degree` function requires a 1D index array, found {index.ndim}."
        )

    num_nodes = num_nodes if num_nodes is not None else index.max().item() + 1
    if edge_weights is None:
        # int32 count: much faster than float atomics on hub nodes, and exact.
        #  Returned as float32, as before.
        return (
            mx.zeros((num_nodes,), dtype=mx.int32).at[index].add(1).astype(mx.float32)
        )
    return scatter(edge_weights, index, num_nodes, "add")

from mlx_graphs.utils.scatter import degree · mlx_graphs/utils/scatter.py