Created
June 30, 2026 21:54
-
-
Save ikrommyd/51dddb52e54c6f99aa86637b16a11d22 to your computer and use it in GitHub Desktop.
Minmax reduction loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Draft: `minimummaximum`, a 2-in / 2-out ufunc that also supports reduction | |
| * via the ArrayMethod API. The reduction loop lives on the *forward* | |
| * ArrayMethod through the new NPY_METH_get_reduction_loop slot -- there is no | |
| * separate registration call and nothing is stored on the ufunc struct. | |
| * | |
| * forward (elementwise): (a, b) -> (min(a,b), max(a,b)) arity 4 | |
| * reduction ((N+1)->N) : (acc_min, acc_max, x) -> (min, max) arity 5 | |
| * | |
| * `np.minimummaximum.reduce(arr)` returns a 2-tuple (min, max). | |
| * | |
| * Build against a NumPy that has the NPY_METH_get_reduction_loop slot. | |
| */ | |
| #define PY_SSIZE_T_CLEAN | |
| #define NPY_TARGET_VERSION NPY_2_6_API_VERSION | |
| #define NPY_NO_DEPRECATED_API NPY_API_VERSION | |
| #include <Python.h> | |
| #include "numpy/ndarraytypes.h" | |
| #include "numpy/ufuncobject.h" | |
| #include "numpy/dtype_api.h" | |
| #include "numpy/halffloat.h" | |
| #include "numpy/npy_math.h" | |
| #include <type_traits> | |
| /* ----------------------------------------------------------------------- * | |
| * NaN-propagating min/max (mirrors numpy's fmin/fmax-free comparisons). | |
| * ----------------------------------------------------------------------- */ | |
| template <typename T> | |
| static inline T nan_min(T acc, T val) { | |
| return (acc <= val || npy_isnan(acc)) ? acc : val; | |
| } | |
| template <typename T> | |
| static inline T nan_max(T acc, T val) { | |
| return (acc >= val || npy_isnan(acc)) ? acc : val; | |
| } | |
| template <typename T> | |
| static constexpr bool is_complex = | |
| std::is_same_v<T, npy_cfloat> || std::is_same_v<T, npy_cdouble> || | |
| std::is_same_v<T, npy_clongdouble>; | |
| static inline float cre(npy_cfloat z) { return npy_crealf(z); } | |
| static inline float cim(npy_cfloat z) { return npy_cimagf(z); } | |
| static inline double cre(npy_cdouble z) { return npy_creal(z); } | |
| static inline double cim(npy_cdouble z) { return npy_cimag(z); } | |
| static inline long double cre(npy_clongdouble z) { return npy_creall(z); } | |
| static inline long double cim(npy_clongdouble z) { return npy_cimagl(z); } | |
| template <typename T> | |
| static inline T mm_min(T acc, T val) { | |
| if constexpr (std::is_same_v<T, npy_half>) { | |
| return npy_float_to_half(nan_min(npy_half_to_float(acc), | |
| npy_half_to_float(val))); | |
| } | |
| else if constexpr (is_complex<T>) { | |
| auto ar = cre(acc), ai = cim(acc), vr = cre(val), vi = cim(val); | |
| bool acc_le = (ar < vr && !npy_isnan(ai) && !npy_isnan(vi)) || | |
| (ar == vr && ai <= vi); | |
| return (npy_isnan(ar) || npy_isnan(ai) || acc_le) ? acc : val; | |
| } | |
| else { | |
| return nan_min(acc, val); | |
| } | |
| } | |
| template <typename T> | |
| static inline T mm_max(T acc, T val) { | |
| if constexpr (std::is_same_v<T, npy_half>) { | |
| return npy_float_to_half(nan_max(npy_half_to_float(acc), | |
| npy_half_to_float(val))); | |
| } | |
| else if constexpr (is_complex<T>) { | |
| auto ar = cre(acc), ai = cim(acc), vr = cre(val), vi = cim(val); | |
| bool acc_ge = (ar > vr && !npy_isnan(ai) && !npy_isnan(vi)) || | |
| (ar == vr && ai >= vi); | |
| return (npy_isnan(ar) || npy_isnan(ai) || acc_ge) ? acc : val; | |
| } | |
| else { | |
| return nan_max(acc, val); | |
| } | |
| } | |
| /* ----------------------------------------------------------------------- * | |
| * Forward elementwise loop: data = {in1, in2, out_min, out_max} | |
| * ----------------------------------------------------------------------- */ | |
| template <typename T> | |
| static int | |
| minimummaximum_loop(PyArrayMethod_Context *NPY_UNUSED(context), | |
| char *const data[], npy_intp const dimensions[], | |
| npy_intp const strides[], NpyAuxData *NPY_UNUSED(auxdata)) | |
| { | |
| npy_intp N = dimensions[0]; | |
| char *in1 = data[0], *in2 = data[1], *out1 = data[2], *out2 = data[3]; | |
| npy_intp s_in1 = strides[0], s_in2 = strides[1]; | |
| npy_intp s_out1 = strides[2], s_out2 = strides[3]; | |
| while (N--) { | |
| T a = *(T *)in1; | |
| T b = *(T *)in2; | |
| *(T *)out1 = mm_min<T>(a, b); | |
| *(T *)out2 = mm_max<T>(a, b); | |
| in1 += s_in1; in2 += s_in2; out1 += s_out1; out2 += s_out2; | |
| } | |
| return 0; | |
| } | |
| /* ----------------------------------------------------------------------- * | |
| * Reduction loop (N+1)->N: data = {acc_min, acc_max, x, out_min, out_max} | |
| * The reduce machinery aliases out_i to acc_i with stride 0, so this both | |
| * reads the running accumulators and writes the running result. | |
| * ----------------------------------------------------------------------- */ | |
| template <typename T> | |
| static int | |
| minimummaximum_reduce_loop(PyArrayMethod_Context *NPY_UNUSED(context), | |
| char *const data[], npy_intp const dimensions[], | |
| npy_intp const strides[], NpyAuxData *NPY_UNUSED(auxdata)) | |
| { | |
| npy_intp N = dimensions[0]; | |
| char *acc_min = data[0], *acc_max = data[1], *x = data[2]; | |
| char *out_min = data[3], *out_max = data[4]; | |
| npy_intp s_amin = strides[0], s_amax = strides[1], s_x = strides[2]; | |
| npy_intp s_omin = strides[3], s_omax = strides[4]; | |
| while (N--) { | |
| T cur_min = *(T *)acc_min; | |
| T cur_max = *(T *)acc_max; | |
| T val = *(T *)x; | |
| *(T *)out_min = mm_min<T>(cur_min, val); | |
| *(T *)out_max = mm_max<T>(cur_max, val); | |
| acc_min += s_amin; acc_max += s_amax; x += s_x; | |
| out_min += s_omin; out_max += s_omax; | |
| } | |
| return 0; | |
| } | |
| /* ----------------------------------------------------------------------- * | |
| * Per-dtype loop tables and the get_reduction_loop dispatcher. | |
| * ----------------------------------------------------------------------- */ | |
| struct LoopRow { | |
| int typenum; | |
| PyArrayMethod_StridedLoop *forward; | |
| PyArrayMethod_StridedLoop *reduce; | |
| }; | |
| #define ROW(NPY, T) {NPY, &minimummaximum_loop<T>, &minimummaximum_reduce_loop<T>} | |
| static LoopRow minmax_rows[] = { | |
| ROW(NPY_BOOL, npy_bool), | |
| ROW(NPY_BYTE, npy_byte), | |
| ROW(NPY_UBYTE, npy_ubyte), | |
| ROW(NPY_SHORT, npy_short), | |
| ROW(NPY_USHORT, npy_ushort), | |
| ROW(NPY_INT, npy_int), | |
| ROW(NPY_UINT, npy_uint), | |
| ROW(NPY_LONG, npy_long), | |
| ROW(NPY_ULONG, npy_ulong), | |
| ROW(NPY_LONGLONG, npy_longlong), | |
| ROW(NPY_ULONGLONG, npy_ulonglong), | |
| ROW(NPY_HALF, npy_half), | |
| ROW(NPY_FLOAT, npy_float), | |
| ROW(NPY_DOUBLE, npy_double), | |
| ROW(NPY_LONGDOUBLE, npy_longdouble), | |
| ROW(NPY_CFLOAT, npy_cfloat), | |
| ROW(NPY_CDOUBLE, npy_cdouble), | |
| ROW(NPY_CLONGDOUBLE, npy_clongdouble), | |
| }; | |
| #undef ROW | |
| /* | |
| * get_reduction_loop: invoked by the reduce machinery instead of get_loop. | |
| * The reduction descriptors all share one dtype; pick the typed loop from the | |
| * accumulator descriptor (descriptors[0]). | |
| */ | |
| static int | |
| minmax_get_reduction_loop(PyArrayMethod_Context *context, | |
| int NPY_UNUSED(aligned), int NPY_UNUSED(move_references), | |
| const npy_intp *NPY_UNUSED(strides), | |
| PyArrayMethod_StridedLoop **out_loop, | |
| NpyAuxData **out_transferdata, | |
| NPY_ARRAYMETHOD_FLAGS *flags) | |
| { | |
| int type_num = context->descriptors[0]->type_num; | |
| for (auto &row : minmax_rows) { | |
| if (row.typenum == type_num) { | |
| *out_loop = row.reduce; | |
| *out_transferdata = NULL; | |
| /* Match the runtime flags the forward method was registered with. */ | |
| *flags = NPY_METH_NO_FLOATINGPOINT_ERRORS; | |
| return 0; | |
| } | |
| } | |
| PyErr_Format(PyExc_TypeError, | |
| "minimummaximum: no reduction loop for dtype num %d", type_num); | |
| return -1; | |
| } | |
| static int | |
| register_minmax_loops(PyObject *ufunc) | |
| { | |
| for (auto &row : minmax_rows) { | |
| PyArray_Descr *descr = PyArray_DescrFromType(row.typenum); | |
| if (descr == NULL) { | |
| return -1; | |
| } | |
| PyArray_DTypeMeta *dt = NPY_DTYPE(descr); | |
| PyArray_DTypeMeta *dtypes[4] = {dt, dt, dt, dt}; | |
| PyType_Slot slots[] = { | |
| {NPY_METH_strided_loop, (void *)row.forward}, | |
| {NPY_METH_get_reduction_loop, (void *)&minmax_get_reduction_loop}, | |
| {0, NULL}, | |
| }; | |
| PyArrayMethod_Spec spec = {}; | |
| spec.name = "minimummaximum_loop"; | |
| spec.nin = 2; | |
| spec.nout = 2; | |
| spec.casting = NPY_NO_CASTING; | |
| /* IS_REORDERABLE enables axis=None / multi-axis reductions. */ | |
| spec.flags = (NPY_ARRAYMETHOD_FLAGS)( | |
| NPY_METH_NO_FLOATINGPOINT_ERRORS | NPY_METH_IS_REORDERABLE); | |
| spec.dtypes = dtypes; | |
| spec.slots = slots; | |
| int res = PyUFunc_AddLoopFromSpec(ufunc, &spec); | |
| Py_DECREF(descr); | |
| if (res < 0) { | |
| return -1; | |
| } | |
| } | |
| return 0; | |
| } | |
| static PyMethodDef MinmaxMethods[] = { | |
| {NULL, NULL, 0, NULL} | |
| }; | |
| static struct PyModuleDef moduledef = { | |
| PyModuleDef_HEAD_INIT, "minmax", NULL, -1, MinmaxMethods, | |
| NULL, NULL, NULL, NULL | |
| }; | |
| PyMODINIT_FUNC PyInit_minmax(void) | |
| { | |
| import_array(); | |
| import_umath(); | |
| PyObject *m = PyModule_Create(&moduledef); | |
| if (m == NULL) { | |
| return NULL; | |
| } | |
| PyObject *minimummaximum = PyUFunc_FromFuncAndData( | |
| NULL, NULL, NULL, 0, 2, 2, PyUFunc_None, | |
| "minimummaximum", "minimummaximum_docstring", 0); | |
| if (minimummaximum == NULL || register_minmax_loops(minimummaximum) < 0) { | |
| Py_XDECREF(minimummaximum); | |
| Py_DECREF(m); | |
| return NULL; | |
| } | |
| if (PyModule_Add(m, "minimummaximum", minimummaximum)) { | |
| Py_DECREF(m); | |
| return NULL; | |
| } | |
| return m; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from setuptools import setup, Extension | |
| from numpy import get_include | |
| import numpy as np | |
| import os | |
| npymath_lib = os.path.join(np.get_include(), '..', 'lib') | |
| minmax = Extension('minmax', | |
| sources=['minmax.cpp'], | |
| include_dirs=[get_include()], | |
| library_dirs=[npymath_lib], | |
| libraries=['npymath'], | |
| extra_compile_args=['-std=c++17']) | |
| setup(name='minmax_arraymethod', version='1.0', ext_modules=[minmax]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import itertools | |
| import numpy as np | |
| import pytest | |
| import minmax | |
| mm = minmax.minimummaximum | |
| def _reduction_accepts(**kwargs): | |
| # Probe whether mm.reduce accepts a given keyword form. Tuple out=/initial= | |
| # for multi-output reductions depend on numpy-side changes that may not be | |
| # present in the installed numpy; when absent the related tests are skipped. | |
| try: | |
| mm.reduce(np.array([1.0, 2.0]), **kwargs) | |
| except Exception: | |
| return False | |
| return True | |
| HAS_TUPLE_OUT = _reduction_accepts(out=(np.empty(()), np.empty(()))) | |
| HAS_TUPLE_INITIAL = _reduction_accepts(initial=(0.0, 0.0)) | |
| requires_tuple_out = pytest.mark.skipif( | |
| not HAS_TUPLE_OUT, reason="reduction does not support tuple out=" | |
| ) | |
| requires_tuple_initial = pytest.mark.skipif( | |
| not HAS_TUPLE_INITIAL, reason="reduction does not support tuple initial=" | |
| ) | |
| SUPPORTED_DTYPES = [ | |
| np.bool_, | |
| np.int8, | |
| np.uint8, | |
| np.int16, | |
| np.uint16, | |
| np.int32, | |
| np.uint32, | |
| np.int64, | |
| np.uint64, | |
| np.float16, | |
| np.float32, | |
| np.float64, | |
| np.longdouble, | |
| np.complex64, | |
| np.complex128, | |
| np.clongdouble, | |
| ] | |
| DTYPE_IDS = [np.dtype(dt).name for dt in SUPPORTED_DTYPES] | |
| # Types whose comparisons involve NaN/inf, so specials are worth testing. | |
| INEXACT_DTYPES = [ | |
| np.float16, | |
| np.float32, | |
| np.float64, | |
| np.longdouble, | |
| np.complex64, | |
| np.complex128, | |
| np.clongdouble, | |
| ] | |
| INEXACT_IDS = [np.dtype(dt).name for dt in INEXACT_DTYPES] | |
| SHAPES = [(12,), (3, 4), (2, 3, 4), (2, 3, 2, 3)] | |
| # Shapes with at least one zero-length axis, in 1-D and higher dimensions, so | |
| # reductions over an empty axis are exercised well beyond the trivial (0,) case. | |
| EMPTY_SHAPES = [(0,), (0, 3), (3, 0), (2, 0, 4), (2, 3, 0), (0, 2, 3)] | |
| SPECIALS = { | |
| "nan": [np.nan], | |
| "inf": [np.inf, -np.inf], | |
| "nan_inf": [np.nan, np.inf, -np.inf], | |
| } | |
| def make_array(shape, dtype, seed): | |
| rng = np.random.default_rng(seed) | |
| dt = np.dtype(dtype) | |
| if dt == np.dtype(np.bool_): | |
| return rng.integers(0, 2, size=shape).astype(bool) | |
| if np.issubdtype(dt, np.unsignedinteger): | |
| return rng.integers(1, 61, size=shape).astype(dt) | |
| if np.issubdtype(dt, np.integer): | |
| return rng.integers(-50, 51, size=shape).astype(dt) | |
| if np.issubdtype(dt, np.complexfloating): | |
| re = rng.standard_normal(shape) * 10 | |
| im = rng.standard_normal(shape) * 10 | |
| return (re + 1j * im).astype(dt) | |
| return (rng.standard_normal(shape) * 10).astype(dt) | |
| def strided_variants(a): | |
| out = [a, a[::-1]] | |
| if a.ndim == 1: | |
| out.append(a[::2]) | |
| else: | |
| out += [a.swapaxes(0, -1), a[..., ::2]] | |
| return out | |
| def reduce_axes(ndim): | |
| # None, every single axis, and every multi-axis subset in both ascending | |
| # and reversed order so arbitrary picks/orderings are exercised (the result | |
| # must not depend on the order axes are given in). | |
| axes = [None] | |
| for r in range(1, ndim + 1): | |
| for combo in itertools.combinations(range(ndim), r): | |
| if len(combo) == 1: | |
| axes.append(combo[0]) | |
| else: | |
| axes.append(combo) | |
| axes.append(tuple(reversed(combo))) | |
| if ndim >= 1: | |
| axes.append(-1) # negative single axis | |
| if ndim >= 2: | |
| axes.append((-1, 0)) # negative + out-of-order | |
| return axes | |
| def reduces_over_empty(shape, axis): | |
| # A no-identity reduction is illegal exactly when it reduces over zero | |
| # elements into a non-empty result, i.e. some reduced axis is empty while | |
| # every surviving axis is non-empty (otherwise the result is just empty). | |
| ndim = len(shape) | |
| if axis is None: | |
| reduced = set(range(ndim)) | |
| elif isinstance(axis, tuple): | |
| reduced = {ax % ndim for ax in axis} | |
| else: | |
| reduced = {axis % ndim} | |
| empty_reduced = any(shape[ax] == 0 for ax in reduced) | |
| result_nonempty = all(shape[i] > 0 for i in range(ndim) if i not in reduced) | |
| return empty_reduced and result_nonempty | |
| def initial_for(a, kind): | |
| dt = a.dtype | |
| if dt == np.dtype(np.bool_): | |
| return kind == "large" | |
| if np.issubdtype(dt, np.integer): | |
| info = np.iinfo(dt) | |
| return ( | |
| max(int(a.min()) - 1, info.min) | |
| if kind == "small" | |
| else min(int(a.max()) + 1, info.max) | |
| ) | |
| if np.issubdtype(dt, np.complexfloating): | |
| # Lexicographic order is real-major, so a real part past the data's | |
| # extremes makes the initial win regardless of the imaginary part. | |
| re = a.real | |
| edge = float(re.min()) - 1.0 if kind == "small" else float(re.max()) + 1.0 | |
| return complex(edge, 0.0) | |
| return float(a.min()) - 1.0 if kind == "small" else float(a.max()) + 1.0 | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", SHAPES, ids=str) | |
| def test_minimum_maximum(dtype, shape): | |
| a = make_array(shape, dtype, seed=1) | |
| b = make_array(shape, dtype, seed=2) | |
| for av, bv in zip(strided_variants(a), strided_variants(b)): | |
| got_min, got_max = mm(av, bv) | |
| np.testing.assert_array_equal(got_min, np.minimum(av, bv)) | |
| np.testing.assert_array_equal(got_max, np.maximum(av, bv)) | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", SHAPES, ids=str) | |
| @pytest.mark.parametrize("initial_kind", ["small", "large"]) | |
| @pytest.mark.parametrize("keepdims", [False, True]) | |
| def test_reduce(dtype, shape, initial_kind, keepdims): | |
| a = make_array(shape, dtype, seed=3) | |
| for av in strided_variants(a): | |
| initial = initial_for(av, initial_kind) | |
| for axis in reduce_axes(av.ndim): | |
| got_min, got_max = mm.reduce( | |
| av, axis=axis, initial=initial, keepdims=keepdims | |
| ) | |
| np.testing.assert_array_equal( | |
| got_min, | |
| np.minimum.reduce(av, axis=axis, initial=initial, keepdims=keepdims), | |
| ) | |
| np.testing.assert_array_equal( | |
| got_max, | |
| np.maximum.reduce(av, axis=axis, initial=initial, keepdims=keepdims), | |
| ) | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", SHAPES, ids=str) | |
| def test_reduce_where(dtype, shape): | |
| a = make_array(shape, dtype, seed=6) | |
| mask = np.random.default_rng(7).integers(0, 2, size=shape).astype(bool) | |
| # where needs an identity to seed masked-out positions; the same scalar | |
| # seeds both outputs, exactly as it does for the numpy references. | |
| initial = initial_for(a, "large") | |
| for axis in reduce_axes(a.ndim): | |
| got_min, got_max = mm.reduce(a, axis=axis, where=mask, initial=initial) | |
| np.testing.assert_array_equal( | |
| got_min, np.minimum.reduce(a, axis=axis, where=mask, initial=initial) | |
| ) | |
| np.testing.assert_array_equal( | |
| got_max, np.maximum.reduce(a, axis=axis, where=mask, initial=initial) | |
| ) | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| def test_scalar_and_0d(dtype): | |
| scalar = np.dtype(dtype).type # e.g. np.float64 | |
| v1 = make_array((), dtype, seed=4).item() | |
| v2 = make_array((), dtype, seed=5).item() | |
| zero_d_arrays = (np.array(v1, dtype), np.array(v2, dtype)) | |
| numpy_scalars = (scalar(v1), scalar(v2)) | |
| for a, b in (zero_d_arrays, numpy_scalars): | |
| got_min, got_max = mm(a, b) | |
| np.testing.assert_array_equal(got_min, np.minimum(a, b)) | |
| np.testing.assert_array_equal(got_max, np.maximum(a, b)) | |
| red_min, red_max = mm.reduce(a) | |
| np.testing.assert_array_equal(red_min, np.minimum.reduce(a)) | |
| np.testing.assert_array_equal(red_max, np.maximum.reduce(a)) | |
| @pytest.mark.parametrize("dtype", INEXACT_DTYPES, ids=INEXACT_IDS) | |
| @pytest.mark.parametrize("kind", list(SPECIALS)) | |
| def test_minimum_maximum_specials(dtype, kind): | |
| vals = [1.0, -2.0, 3.5, 0.0, -1.0] + SPECIALS[kind] | |
| a = np.array(vals, dtype=dtype) | |
| b = np.array(vals[::-1], dtype=dtype) | |
| got_min, got_max = mm(a, b) | |
| np.testing.assert_array_equal(got_min, np.minimum(a, b)) | |
| np.testing.assert_array_equal(got_max, np.maximum(a, b)) | |
| @pytest.mark.parametrize("dtype", INEXACT_DTYPES, ids=INEXACT_IDS) | |
| @pytest.mark.parametrize("kind", list(SPECIALS)) | |
| def test_reduce_specials(dtype, kind): | |
| vals = [1.0, -2.0, 3.5, 0.0, -1.0] + SPECIALS[kind] | |
| a = np.array(vals, dtype=dtype) | |
| got_min, got_max = mm.reduce(a) | |
| np.testing.assert_array_equal(got_min, np.minimum.reduce(a)) | |
| np.testing.assert_array_equal(got_max, np.maximum.reduce(a)) | |
| @requires_tuple_out | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", SHAPES, ids=str) | |
| @pytest.mark.parametrize("keepdims", [False, True]) | |
| def test_reduce_out_tuple(dtype, shape, keepdims): | |
| # out must be a tuple of one array per reduction output; each element has | |
| # the same shape/dtype requirements as the single-output case. | |
| a = make_array(shape, dtype, seed=8) | |
| for axis in reduce_axes(a.ndim): | |
| ref_min = np.minimum.reduce(a, axis=axis, keepdims=keepdims) | |
| ref_max = np.maximum.reduce(a, axis=axis, keepdims=keepdims) | |
| omin = np.empty(np.shape(ref_min), dtype) | |
| omax = np.empty(np.shape(ref_max), dtype) | |
| got_min, got_max = mm.reduce(a, axis=axis, keepdims=keepdims, out=(omin, omax)) | |
| # Results are written into the provided arrays and returned as-is. | |
| assert got_min is omin and got_max is omax | |
| np.testing.assert_array_equal(omin, ref_min) | |
| np.testing.assert_array_equal(omax, ref_max) | |
| @requires_tuple_initial | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", SHAPES, ids=str) | |
| def test_reduce_initial_tuple(dtype, shape): | |
| # A scalar initial seeds every output; a per-output tuple seeds each | |
| # output independently, matching numpy's single-output behaviour per slot. | |
| a = make_array(shape, dtype, seed=9) | |
| small = initial_for(a, "small") | |
| large = initial_for(a, "large") | |
| for axis in reduce_axes(a.ndim): | |
| for initial in [(small, large), (large, small)]: | |
| got_min, got_max = mm.reduce(a, axis=axis, initial=initial) | |
| np.testing.assert_array_equal( | |
| got_min, np.minimum.reduce(a, axis=axis, initial=initial[0]) | |
| ) | |
| np.testing.assert_array_equal( | |
| got_max, np.maximum.reduce(a, axis=axis, initial=initial[1]) | |
| ) | |
| # Old behaviour, before out= was generalized to a tuple of one array per | |
| # reduction output: a bare out array for a multi-output reduction was rejected | |
| # outright. Runs only when tuple out= is unsupported (numpy changes reverted). | |
| @pytest.mark.skipif( | |
| HAS_TUPLE_OUT, reason="reduction supports tuple out=; single-out rejection gone" | |
| ) | |
| def test_out_raises(): | |
| a = np.array([3.0, 1.0, 5.0, 2.0]) | |
| with pytest.raises(TypeError, match="must be a tuple of arrays"): | |
| mm.reduce(a, out=np.array(0.0)) | |
| @requires_tuple_out | |
| def test_out_bare_array_raises(): | |
| a = np.array([3.0, 1.0, 5.0, 2.0]) | |
| with pytest.raises(TypeError, match="must be a tuple of arrays"): | |
| mm.reduce(a, out=np.array(0.0)) | |
| @requires_tuple_out | |
| def test_out_wrong_length_raises(): | |
| a = np.array([3.0, 1.0, 5.0, 2.0]) | |
| with pytest.raises(ValueError, match="exactly one entry per ufunc output"): | |
| mm.reduce(a, out=(np.array(0.0),)) | |
| @requires_tuple_initial | |
| def test_initial_wrong_length_raises(): | |
| a = np.array([3.0, 1.0, 5.0, 2.0]) | |
| with pytest.raises(ValueError, match="one entry per reduction output"): | |
| mm.reduce(a, initial=(1.0, 2.0, 3.0)) | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", EMPTY_SHAPES, ids=str) | |
| @pytest.mark.parametrize("keepdims", [False, True]) | |
| def test_reduce_empty_no_initial(dtype, shape, keepdims): | |
| # minimummaximum has no identity, so reducing over an empty axis must raise | |
| # exactly as np.minimum/np.maximum.reduce do. When an empty axis merely | |
| # survives in the result (no empty axis is actually reduced) an empty array | |
| # is returned instead. The values are irrelevant, only the shapes/axes are. | |
| a = np.zeros(shape, dtype) | |
| for axis in reduce_axes(a.ndim): | |
| if reduces_over_empty(shape, axis): | |
| # Cross-check the predicate against numpy: its own min/max reductions | |
| # raise here too, and minimummaximum must match them. | |
| for op in (np.minimum, np.maximum, mm): | |
| with pytest.raises( | |
| ValueError, match="zero-size array to reduction operation" | |
| ): | |
| op.reduce(a, axis=axis, keepdims=keepdims) | |
| continue | |
| got_min, got_max = mm.reduce(a, axis=axis, keepdims=keepdims) | |
| np.testing.assert_array_equal( | |
| got_min, np.minimum.reduce(a, axis=axis, keepdims=keepdims) | |
| ) | |
| np.testing.assert_array_equal( | |
| got_max, np.maximum.reduce(a, axis=axis, keepdims=keepdims) | |
| ) | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", EMPTY_SHAPES, ids=str) | |
| @pytest.mark.parametrize("keepdims", [False, True]) | |
| def test_reduce_empty_scalar_initial(dtype, shape, keepdims): | |
| # A scalar initial supplies the missing identity, so an otherwise-illegal | |
| # empty reduction succeeds and every output is seeded with it. | |
| a = np.zeros(shape, dtype) | |
| for axis in reduce_axes(a.ndim): | |
| got_min, got_max = mm.reduce(a, axis=axis, initial=0, keepdims=keepdims) | |
| np.testing.assert_array_equal( | |
| got_min, np.minimum.reduce(a, axis=axis, initial=0, keepdims=keepdims) | |
| ) | |
| np.testing.assert_array_equal( | |
| got_max, np.maximum.reduce(a, axis=axis, initial=0, keepdims=keepdims) | |
| ) | |
| @requires_tuple_initial | |
| @pytest.mark.parametrize("dtype", SUPPORTED_DTYPES, ids=DTYPE_IDS) | |
| @pytest.mark.parametrize("shape", EMPTY_SHAPES, ids=str) | |
| @pytest.mark.parametrize("keepdims", [False, True]) | |
| def test_reduce_empty_tuple_initial(dtype, shape, keepdims): | |
| # A per-output initial seeds each output independently over empty axes. | |
| a = np.zeros(shape, dtype) | |
| initial = (0, 1) | |
| for axis in reduce_axes(a.ndim): | |
| got_min, got_max = mm.reduce(a, axis=axis, initial=initial, keepdims=keepdims) | |
| np.testing.assert_array_equal( | |
| got_min, | |
| np.minimum.reduce(a, axis=axis, initial=initial[0], keepdims=keepdims), | |
| ) | |
| np.testing.assert_array_equal( | |
| got_max, | |
| np.maximum.reduce(a, axis=axis, initial=initial[1], keepdims=keepdims), | |
| ) | |
| def test_unsupported_dtype_raises(): | |
| a = np.array([1, 2, 3], dtype=object) | |
| with pytest.raises(ValueError, match="reduction over input type"): | |
| mm.reduce(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment