|
| 1 | +# SPDX-License-Identifier: MPL-2.0 |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from functools import partial, singledispatch |
| 5 | +from typing import TYPE_CHECKING, Any, cast, overload |
| 6 | + |
| 7 | +import numba |
| 8 | +import numpy as np |
| 9 | +from numpy.typing import NDArray |
| 10 | + |
| 11 | +from .. import types |
| 12 | +from .._validation import validate_axis |
| 13 | + |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from collections.abc import Callable |
| 17 | + from typing import Literal, TypeVar |
| 18 | + |
| 19 | + C = TypeVar("C", bound=Callable[..., Any]) |
| 20 | + |
| 21 | + |
| 22 | +@overload |
| 23 | +def is_constant(a: types.DaskArray, /, *, axis: Literal[0, 1, None] = None) -> types.DaskArray: ... |
| 24 | +@overload |
| 25 | +def is_constant(a: NDArray[Any] | types.CSBase, /, *, axis: None = None) -> bool: ... |
| 26 | +@overload |
| 27 | +def is_constant(a: NDArray[Any] | types.CSBase, /, *, axis: Literal[0, 1]) -> NDArray[np.bool]: ... |
| 28 | + |
| 29 | + |
| 30 | +def is_constant( |
| 31 | + a: NDArray[Any] | types.CSBase | types.DaskArray, /, *, axis: Literal[0, 1, None] = None |
| 32 | +) -> bool | NDArray[np.bool] | types.DaskArray: |
| 33 | + """Check whether values in array are constant. |
| 34 | +
|
| 35 | + Params |
| 36 | + ------ |
| 37 | + a |
| 38 | + Array to check |
| 39 | + axis |
| 40 | + Axis to reduce over. |
| 41 | +
|
| 42 | + Returns |
| 43 | + ------- |
| 44 | + If ``axis`` is :data:`None`, return if all values were constant. |
| 45 | + Else returns a boolean array with :data:`True` representing constant columns/rows. |
| 46 | +
|
| 47 | + Example |
| 48 | + ------- |
| 49 | + >>> a = np.array([[0, 1], [0, 0]]) |
| 50 | + >>> a |
| 51 | + array([[0, 1], |
| 52 | + [0, 0]]) |
| 53 | + >>> is_constant(a) |
| 54 | + False |
| 55 | + >>> is_constant(a, axis=0) |
| 56 | + array([ True, False]) |
| 57 | + >>> is_constant(a, axis=1) |
| 58 | + array([False, True]) |
| 59 | +
|
| 60 | + """ |
| 61 | + validate_axis(axis) |
| 62 | + return _is_constant(a, axis=axis) |
| 63 | + |
| 64 | + |
| 65 | +@singledispatch |
| 66 | +def _is_constant( |
| 67 | + a: NDArray[Any] | types.CSBase | types.DaskArray, /, *, axis: Literal[0, 1, None] = None |
| 68 | +) -> bool | NDArray[np.bool]: # pragma: no cover |
| 69 | + raise NotImplementedError |
| 70 | + |
| 71 | + |
| 72 | +@_is_constant.register(np.ndarray) |
| 73 | +def _(a: NDArray[Any], /, *, axis: Literal[0, 1, None] = None) -> bool | NDArray[np.bool]: |
| 74 | + # Should eventually support nd, not now. |
| 75 | + match axis: |
| 76 | + case None: |
| 77 | + return bool((a == a.flat[0]).all()) |
| 78 | + case 0: |
| 79 | + return _is_constant_rows(a.T) |
| 80 | + case 1: |
| 81 | + return _is_constant_rows(a) |
| 82 | + |
| 83 | + |
| 84 | +def _is_constant_rows(a: NDArray[Any]) -> NDArray[np.bool]: |
| 85 | + b = np.broadcast_to(a[:, 0][:, np.newaxis], a.shape) |
| 86 | + return cast(NDArray[np.bool], (a == b).all(axis=1)) |
| 87 | + |
| 88 | + |
| 89 | +@_is_constant.register(types.CSBase) |
| 90 | +def _(a: types.CSBase, /, *, axis: Literal[0, 1, None] = None) -> bool | NDArray[np.bool]: |
| 91 | + n_row, n_col = a.shape |
| 92 | + if axis is None: |
| 93 | + if len(a.data) == n_row * n_col: |
| 94 | + return is_constant(cast(NDArray[Any], a.data)) |
| 95 | + return bool((a.data == 0).all()) |
| 96 | + shape = (n_row, n_col) if axis == 1 else (n_col, n_row) |
| 97 | + match axis, a.format: |
| 98 | + case 0, "csr": |
| 99 | + a = a.T.tocsr() |
| 100 | + case 1, "csc": |
| 101 | + a = a.T.tocsc() |
| 102 | + return _is_constant_csr_rows(a.data, a.indptr, shape) |
| 103 | + |
| 104 | + |
| 105 | +@numba.njit(cache=True) |
| 106 | +def _is_constant_csr_rows( |
| 107 | + data: NDArray[np.number[Any]], |
| 108 | + indptr: NDArray[np.integer[Any]], |
| 109 | + shape: tuple[int, int], |
| 110 | +) -> NDArray[np.bool]: |
| 111 | + n = len(indptr) - 1 |
| 112 | + result = np.ones(n, dtype=np.bool) |
| 113 | + for i in numba.prange(n): |
| 114 | + start = indptr[i] |
| 115 | + stop = indptr[i + 1] |
| 116 | + val = data[start] if stop - start == shape[1] else 0 |
| 117 | + for j in range(start, stop): |
| 118 | + if data[j] != val: |
| 119 | + result[i] = False |
| 120 | + break |
| 121 | + return result |
| 122 | + |
| 123 | + |
| 124 | +@_is_constant.register(types.DaskArray) |
| 125 | +def _(a: types.DaskArray, /, *, axis: Literal[0, 1, None] = None) -> types.DaskArray: |
| 126 | + if TYPE_CHECKING: |
| 127 | + from dask.array.core import map_blocks |
| 128 | + from dask.array.overlap import map_overlap |
| 129 | + else: |
| 130 | + from dask.array import map_blocks, map_overlap |
| 131 | + |
| 132 | + if axis is not None: |
| 133 | + return cast( |
| 134 | + types.DaskArray, |
| 135 | + map_blocks( # type: ignore[no-untyped-call] |
| 136 | + partial(is_constant, axis=axis), a, drop_axis=axis, meta=np.array([], dtype=np.bool) |
| 137 | + ), |
| 138 | + ) |
| 139 | + |
| 140 | + rv = cast( |
| 141 | + types.DaskArray, |
| 142 | + (a == a[0, 0].compute()).all() |
| 143 | + if isinstance(a._meta, np.ndarray) # noqa: SLF001 |
| 144 | + else map_overlap( # type: ignore[no-untyped-call] |
| 145 | + lambda a: np.array([[is_constant(a)]]), |
| 146 | + a, |
| 147 | + # use asymmetric overlaps to avoid unnecessary computation |
| 148 | + depth={d: (0, 1) for d in range(a.ndim)}, |
| 149 | + trim=False, |
| 150 | + meta=np.array([], dtype=bool), |
| 151 | + ).all(), |
| 152 | + ) |
| 153 | + return cast( |
| 154 | + types.DaskArray, |
| 155 | + map_blocks(bool, rv, meta=np.array([], dtype=bool)), # type: ignore[no-untyped-call] |
| 156 | + ) |
0 commit comments