Skip to content

scatter_quantile

scatter_quantile(
    values: array,
    index: array,
    out_size: int,
    q: Union[float, List[float]] = 0.5,
    interpolation: QuantileInterpolations = "linear",
    fill_value: float = 0.0,
) -> array

Computes the feature-wise \(q\)-th quantile of the values grouped by index (along axis 0), as PyG's QuantileAggregation.

The values of each group are sorted, and the quantile is read at position \(q \cdot (n - 1)\) of its \(n\) sorted values, interpolating between the two neighbouring values when the position is not an integer. The index does not need to be sorted. The gradient flows to the selected values.

Parameters:

Name Type Description Default
values array

Input array of shape [num_values, ...].

required
index array

Array of shape [num_values] with the group of each value.

required
out_size int

Number of groups.

required
q Union[float, List[float]]

Quantile(s) in [0, 1]. With several quantiles, the results are concatenated along the last axis. Default: 0.5

0.5
interpolation QuantileInterpolations

How to read a quantile lying between two values a <= b: "linear" (a + (b - a) * frac), "lower" (a), "higher" (b), "nearest" or "midpoint". Default: "linear"

'linear'
fill_value float

Value of groups without any value. Default: 0.0

0.0

Returns:

Type Description
array

An array of shape [out_size, ...], or `[out_size, ...,

array

len(q) * num_features]` for several quantiles.

Example:

values = mx.array([[1.0], [5.0], [3.0], [2.0]])
index = mx.array([0, 0, 0, 1])

scatter_quantile(values, index, 3, q=0.5)
>>> mx.array([[3.0], [2.0], [0.0]])
Source code in mlx_graphs/utils/scatter.py
def scatter_quantile(
    values: mx.array,
    index: mx.array,
    out_size: int,
    q: Union[float, List[float]] = 0.5,
    interpolation: QuantileInterpolations = "linear",
    fill_value: float = 0.0,
) -> mx.array:
    r"""Computes the feature-wise :math:`q`-th quantile of the values grouped
    by index (along axis 0), as PyG's ``QuantileAggregation``.

    The values of each group are sorted, and the quantile is read at position
    :math:`q \cdot (n - 1)` of its :math:`n` sorted values, interpolating
    between the two neighbouring values when the position is not an integer.
    The index does not need to be sorted. The gradient flows to the selected
    values.

    Args:
        values: Input array of shape ``[num_values, ...]``.
        index: Array of shape ``[num_values]`` with the group of each value.
        out_size: Number of groups.
        q: Quantile(s) in ``[0, 1]``. With several quantiles, the results are
            concatenated along the last axis. Default: ``0.5``
        interpolation: How to read a quantile lying between two values
            ``a <= b``: ``"linear"`` (``a + (b - a) * frac``), ``"lower"``
            (``a``), ``"higher"`` (``b``), ``"nearest"`` or ``"midpoint"``.
            Default: ``"linear"``
        fill_value: Value of groups without any value. Default: ``0.0``

    Returns:
        An array of shape ``[out_size, ...]``, or ``[out_size, ...,
        len(q) * num_features]`` for several quantiles.

    Example:

    .. code-block:: python

        values = mx.array([[1.0], [5.0], [3.0], [2.0]])
        index = mx.array([0, 0, 0, 1])

        scatter_quantile(values, index, 3, q=0.5)
        >>> mx.array([[3.0], [2.0], [0.0]])
    """
    qs = list(q) if isinstance(q, (list, tuple)) else [q]
    if len(qs) == 0:
        raise ValueError("Provide at least one quantile value for `q`.")
    if not all(0.0 <= quantile <= 1.0 for quantile in qs):
        raise ValueError("`q` must be in the range [0, 1].")
    if interpolation not in get_args(QuantileInterpolations):
        raise ValueError(
            f"Invalid interpolation '{interpolation}', available values are "
            f"{get_args(QuantileInterpolations)}"
        )

    num_values = values.shape[0]
    feature_shape = values.shape[1:]
    if num_values == 0:
        out = mx.full((out_size, *feature_shape), fill_value, dtype=values.dtype)
        return out if len(qs) == 1 else mx.concatenate([out] * len(qs), axis=-1)

    x = values.reshape(num_values, -1)

    # Sort each feature column by value, then (stably) by group, so that the
    # values of every group are contiguous and sorted in every column.
    perm = mx.argsort(x, axis=0)
    rank = mx.arange(num_values, dtype=mx.int64).reshape(-1, 1)
    group_key = index.astype(mx.int64)[perm] * num_values + rank
    perm = mx.take_along_axis(perm, mx.argsort(group_key, axis=0), axis=0)
    x = mx.take_along_axis(x, mx.stop_gradient(perm), axis=0)

    count = mx.zeros((out_size,), dtype=mx.int32).at[index].add(1)
    start = mx.minimum(mx.cumsum(count) - count, num_values - 1)
    empty = (count == 0).reshape(-1, 1)
    fill = mx.array(fill_value, dtype=x.dtype)

    outs = []
    for quantile in qs:
        # Position within the group, added to the (integer) start of the
        # group afterwards: a float32 global position would be rounded for
        # more than 2**24 values and read from the wrong group.
        local = mx.maximum(quantile * (count - 1).astype(mx.float32), 0.0)
        low = mx.floor(local)
        frac_point = local - low
        low_idx = mx.minimum(start + low.astype(mx.int32), num_values - 1)
        high_idx = mx.minimum(start + mx.ceil(local).astype(mx.int32), num_values - 1)
        if interpolation == "lower":
            out = x[low_idx]
        elif interpolation == "higher":
            out = x[high_idx]
        elif interpolation == "nearest":
            # round half to even on the global position, as torch.round
            tie_idx = mx.where(low_idx % 2 == 0, low_idx, high_idx)
            nearest = mx.where(frac_point < 0.5, low_idx, high_idx)
            out = x[mx.where(frac_point == 0.5, tie_idx, nearest)]
        elif interpolation == "linear":
            frac = frac_point.reshape(-1, 1).astype(x.dtype)
            out = x[low_idx] + (x[high_idx] - x[low_idx]) * frac
        else:  # midpoint
            out = 0.5 * x[low_idx] + 0.5 * x[high_idx]
        out = mx.where(empty, fill, out)
        outs.append(out.reshape(out_size, *feature_shape))

    return outs[0] if len(outs) == 1 else mx.concatenate(outs, axis=-1)

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