Skip to content

Commit ffe6b2a

Browse files
committed
ENH: add np.minmax() for combined min/max reduction
Adds np.minmax(a, axis=None, keepdims=..., initial=..., where=...) that returns a (min, max) tuple. This provides a clean public API for computing both extrema in a single call, matching the naming convention used by C++ std::minmax, MATLAB, Julia, and Ruby. The initial parameter accepts a (min_initial, max_initial) tuple to handle empty slices with separate identity values for each reduction. Supports axis, keepdims, initial, and where parameters consistent with np.min/np.max. Internally delegates to minimum.reduce and maximum.reduce; a future C-level single-pass implementation can be swapped in behind the same public API for a ~2x speedup on memory-bandwidth-bound workloads. Closes numpy#9836 Signed-off-by: Varun Chawla <[email protected]>
1 parent 552c46f commit ffe6b2a

6 files changed

Lines changed: 326 additions & 2 deletions

File tree

‎numpy/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,7 @@
332332
min,
333333
min_scalar_type,
334334
minimum,
335+
minmax,
335336
mod,
336337
modf,
337338
moveaxis,

‎numpy/__init__.pyi‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ from numpy._core.fromnumeric import (
246246
ptp,
247247
max,
248248
min,
249+
minmax,
249250
amax,
250251
amin,
251252
prod,
@@ -619,7 +620,7 @@ __all__ = [ # noqa: RUF022
619620
"shares_memory", "may_share_memory",
620621
"all", "amax", "amin", "any", "argmax", "argmin", "argpartition", "argsort",
621622
"around", "choose", "clip", "compress", "cumprod", "cumsum", "cumulative_prod",
622-
"cumulative_sum", "diagonal", "mean", "max", "min", "matrix_transpose", "ndim",
623+
"cumulative_sum", "diagonal", "mean", "max", "min", "minmax", "matrix_transpose", "ndim",
623624
"nonzero", "partition", "prod", "ptp", "put", "ravel", "repeat", "reshape",
624625
"resize", "round", "searchsorted", "shape", "size", "sort", "squeeze", "std", "sum",
625626
"swapaxes", "take", "trace", "transpose", "var",

‎numpy/_core/_methods.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,11 @@ def _ptp(a, axis=None, out=None, keepdims=False):
235235
out
236236
)
237237

238+
def _minmax(a, axis=None, keepdims=False, initial=_NoValue, where=True):
239+
mn = umr_minimum(a, axis, None, None, keepdims, initial, where)
240+
mx = umr_maximum(a, axis, None, None, keepdims, initial, where)
241+
return mn, mx
242+
238243
def _dump(self, file, protocol=2):
239244
if hasattr(file, 'write'):
240245
ctx = nullcontext(file)

‎numpy/_core/fromnumeric.py‎

Lines changed: 120 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
'all', 'amax', 'amin', 'any', 'argmax',
2020
'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
2121
'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
22-
'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
22+
'diagonal', 'mean', 'max', 'min', 'minmax', 'matrix_transpose',
2323
'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
2424
'ravel', 'repeat', 'reshape', 'resize', 'round',
2525
'searchsorted', 'shape', 'size', 'sort', 'squeeze',
@@ -3279,6 +3279,125 @@ def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
32793279
keepdims=keepdims, initial=initial, where=where)
32803280

32813281

3282+
def _minmax_dispatcher(a, axis=None, keepdims=None, initial=None,
3283+
where=None):
3284+
return (a,)
3285+
3286+
3287+
@array_function_dispatch(_minmax_dispatcher)
3288+
@set_module('numpy')
3289+
def minmax(a, axis=None, keepdims=np._NoValue, initial=np._NoValue,
3290+
where=np._NoValue):
3291+
"""
3292+
Return the minimum and maximum of an array or along an axis in a
3293+
single call.
3294+
3295+
Parameters
3296+
----------
3297+
a : array_like
3298+
Input data.
3299+
axis : None or int or tuple of ints, optional
3300+
Axis or axes along which to operate. By default, flattened input
3301+
is used. If this is a tuple of ints, the result is computed over
3302+
multiple axes.
3303+
keepdims : bool, optional
3304+
If this is set to True, the axes which are reduced are left
3305+
in the result as dimensions with size one. With this option,
3306+
the result will broadcast correctly against the input array.
3307+
initial : scalar or tuple of scalars, optional
3308+
Initial values for the min and max reductions. Must be present to
3309+
allow computation on empty slices. When a tuple
3310+
``(min_initial, max_initial)`` is given, separate initial values are
3311+
used for minimum and maximum (e.g., ``(np.inf, -np.inf)`` for an
3312+
empty array). A single scalar is used as the initial for both
3313+
reductions. See `~numpy.ufunc.reduce` for details.
3314+
where : array_like of bool, optional
3315+
Elements to include in the computation. See `~numpy.ufunc.reduce`
3316+
for details.
3317+
3318+
Returns
3319+
-------
3320+
minmax : tuple of ndarray or scalars
3321+
A ``(min, max)`` pair with the minimum and maximum values of `a`.
3322+
If `axis` is not None, a pair of arrays with the same shape as
3323+
``np.min(a, axis=axis)`` is returned.
3324+
3325+
See Also
3326+
--------
3327+
min : Return the minimum of an array.
3328+
max : Return the maximum of an array.
3329+
ptp : Return the range (max - min) of values along an axis.
3330+
nanmin : Return the minimum ignoring NaN values.
3331+
nanmax : Return the maximum ignoring NaN values.
3332+
3333+
.. versionadded:: 2.5.0
3334+
3335+
Notes
3336+
-----
3337+
Combining minimum and maximum into a single function call can avoid
3338+
redundant passes over the data when both values are needed.
3339+
3340+
NaN values are propagated, that is if at least one item is NaN, the
3341+
corresponding min and max values will be NaN as well. To ignore NaN
3342+
values, use `nanmin` and `nanmax` separately.
3343+
3344+
Examples
3345+
--------
3346+
>>> import numpy as np
3347+
>>> a = np.arange(4).reshape((2, 2))
3348+
>>> a
3349+
array([[0, 1],
3350+
[2, 3]])
3351+
3352+
>>> np.minmax(a)
3353+
(np.int64(0), np.int64(3))
3354+
3355+
>>> np.minmax(a, axis=0)
3356+
(array([0, 1]), array([2, 3]))
3357+
3358+
>>> np.minmax(a, axis=1)
3359+
(array([0, 2]), array([1, 3]))
3360+
3361+
>>> b = np.arange(5, dtype=np.float64)
3362+
>>> b[2] = np.nan
3363+
>>> np.minmax(b)
3364+
(np.float64(nan), np.float64(nan))
3365+
3366+
Use ``initial`` to provide a bound when the input might be empty:
3367+
3368+
>>> np.minmax([], initial=(np.inf, -np.inf))
3369+
(inf, -inf)
3370+
3371+
>>> np.minmax([[-50], [10]], axis=-1)
3372+
(array([-50, 10]), array([-50, 10]))
3373+
"""
3374+
kwargs = {}
3375+
if keepdims is not np._NoValue:
3376+
kwargs['keepdims'] = keepdims
3377+
3378+
if initial is not np._NoValue:
3379+
if not isinstance(initial, tuple):
3380+
kwargs['initial'] = initial
3381+
else:
3382+
# Allow tuple (min_initial, max_initial) for empty-slice case
3383+
min_initial, max_initial = initial
3384+
a = np.asanyarray(a)
3385+
min_kwargs = dict(kwargs, initial=min_initial)
3386+
max_kwargs = dict(kwargs, initial=max_initial)
3387+
if where is not np._NoValue:
3388+
min_kwargs['where'] = where
3389+
max_kwargs['where'] = where
3390+
return (
3391+
_methods._amin(a, axis=axis, **min_kwargs),
3392+
_methods._amax(a, axis=axis, **max_kwargs),
3393+
)
3394+
3395+
if where is not np._NoValue:
3396+
kwargs['where'] = where
3397+
3398+
return _methods._minmax(a, axis=axis, **kwargs)
3399+
3400+
32823401
def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
32833402
initial=None, where=None):
32843403
return (a, out)

‎numpy/_core/fromnumeric.pyi‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ __all__ = [
7878
"mean",
7979
"max",
8080
"min",
81+
"minmax",
8182
"matrix_transpose",
8283
"ndim",
8384
"nonzero",
@@ -1129,6 +1130,23 @@ def amin[ArrayT: np.ndarray](
11291130
where: _ArrayLikeBool_co | _NoValueType = ...,
11301131
) -> ArrayT: ...
11311132

1133+
@overload
1134+
def minmax[ScalarT: np.generic](
1135+
a: _ArrayLike[ScalarT],
1136+
axis: None = None,
1137+
keepdims: Literal[False] | _NoValueType = ...,
1138+
initial: tuple[_NumberLike_co, _NumberLike_co] | _NumberLike_co | _NoValueType = ...,
1139+
where: _ArrayLikeBool_co | _NoValueType = ...,
1140+
) -> tuple[ScalarT, ScalarT]: ...
1141+
@overload
1142+
def minmax(
1143+
a: ArrayLike,
1144+
axis: _ShapeLike | None = None,
1145+
keepdims: bool | _NoValueType = ...,
1146+
initial: tuple[_NumberLike_co, _NumberLike_co] | _NumberLike_co | _NoValueType = ...,
1147+
where: _ArrayLikeBool_co | _NoValueType = ...,
1148+
) -> tuple[Any, Any]: ...
1149+
11321150
# TODO: `np.prod()``: For object arrays `initial` does not necessarily
11331151
# have to be a numerical scalar.
11341152
# The only requirement is that it is compatible

‎numpy/_core/tests/test_minmax.py‎

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
"""Tests for np.minmax function."""
2+
3+
import pytest
4+
5+
import numpy as np
6+
from numpy.testing import assert_array_equal, assert_equal
7+
8+
9+
class TestMinMax:
10+
"""Tests for np.minmax."""
11+
12+
def test_basic(self):
13+
a = np.array([3, 1, 4, 1, 5, 9, 2, 6])
14+
mn, mx = np.minmax(a)
15+
assert_equal(mn, 1)
16+
assert_equal(mx, 9)
17+
18+
def test_scalar(self):
19+
mn, mx = np.minmax(42)
20+
assert_equal(mn, 42)
21+
assert_equal(mx, 42)
22+
23+
def test_2d_no_axis(self):
24+
a = np.array([[3, 1], [4, 5]])
25+
mn, mx = np.minmax(a)
26+
assert_equal(mn, 1)
27+
assert_equal(mx, 5)
28+
29+
def test_2d_axis0(self):
30+
a = np.array([[3, 1], [4, 5]])
31+
mn, mx = np.minmax(a, axis=0)
32+
assert_array_equal(mn, [3, 1])
33+
assert_array_equal(mx, [4, 5])
34+
35+
def test_2d_axis1(self):
36+
a = np.array([[3, 1], [4, 5]])
37+
mn, mx = np.minmax(a, axis=1)
38+
assert_array_equal(mn, [1, 4])
39+
assert_array_equal(mx, [3, 5])
40+
41+
def test_3d_axis(self):
42+
a = np.arange(24).reshape((2, 3, 4))
43+
mn, mx = np.minmax(a, axis=2)
44+
assert_array_equal(mn, np.min(a, axis=2))
45+
assert_array_equal(mx, np.max(a, axis=2))
46+
47+
def test_3d_axis_tuple(self):
48+
a = np.arange(24).reshape((2, 3, 4))
49+
mn, mx = np.minmax(a, axis=(0, 2))
50+
assert_array_equal(mn, np.min(a, axis=(0, 2)))
51+
assert_array_equal(mx, np.max(a, axis=(0, 2)))
52+
53+
def test_keepdims(self):
54+
a = np.array([[3, 1], [4, 5]])
55+
mn, mx = np.minmax(a, axis=0, keepdims=True)
56+
assert mn.shape == (1, 2)
57+
assert mx.shape == (1, 2)
58+
assert_array_equal(mn, [[3, 1]])
59+
assert_array_equal(mx, [[4, 5]])
60+
61+
def test_float(self):
62+
a = np.array([1.5, -2.3, 4.7, 0.1])
63+
mn, mx = np.minmax(a)
64+
assert_equal(mn, -2.3)
65+
assert_equal(mx, 4.7)
66+
67+
def test_nan_propagation(self):
68+
a = np.array([1.0, np.nan, 3.0])
69+
mn, mx = np.minmax(a)
70+
assert np.isnan(mn)
71+
assert np.isnan(mx)
72+
73+
def test_all_same(self):
74+
a = np.array([5, 5, 5, 5])
75+
mn, mx = np.minmax(a)
76+
assert_equal(mn, 5)
77+
assert_equal(mx, 5)
78+
79+
def test_single_element(self):
80+
a = np.array([42])
81+
mn, mx = np.minmax(a)
82+
assert_equal(mn, 42)
83+
assert_equal(mx, 42)
84+
85+
def test_negative_axis(self):
86+
a = np.arange(12).reshape((3, 4))
87+
mn, mx = np.minmax(a, axis=-1)
88+
assert_array_equal(mn, np.min(a, axis=-1))
89+
assert_array_equal(mx, np.max(a, axis=-1))
90+
91+
def test_empty_with_initial(self):
92+
a = np.array([])
93+
mn, mx = np.minmax(a, initial=(np.inf, -np.inf))
94+
assert_equal(mn, np.inf)
95+
assert_equal(mx, -np.inf)
96+
97+
def test_where(self):
98+
a = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
99+
mask = np.array([True, False, True, False, True])
100+
mn, mx = np.minmax(a, initial=(np.inf, -np.inf), where=mask)
101+
assert_equal(mn, 1.0)
102+
assert_equal(mx, 5.0)
103+
104+
def test_integer_dtypes(self):
105+
for dtype in [
106+
np.int8,
107+
np.int16,
108+
np.int32,
109+
np.int64,
110+
np.uint8,
111+
np.uint16,
112+
np.uint32,
113+
np.uint64,
114+
]:
115+
a = np.array([10, 3, 7, 1, 9], dtype=dtype)
116+
mn, mx = np.minmax(a)
117+
assert_equal(mn, dtype(1))
118+
assert_equal(mx, dtype(10))
119+
120+
def test_float_dtypes(self):
121+
for dtype in [np.float32, np.float64]:
122+
a = np.array([1.5, -2.3, 4.7, 0.1], dtype=dtype)
123+
mn, mx = np.minmax(a)
124+
assert_equal(mn, dtype(-2.3))
125+
assert_equal(mx, dtype(4.7))
126+
127+
def test_bool(self):
128+
a = np.array([True, False, True])
129+
mn, mx = np.minmax(a)
130+
assert_equal(mn, False)
131+
assert_equal(mx, True)
132+
133+
def test_datetime(self):
134+
for dtype in ("m8[s]", "m8[Y]"):
135+
a = np.arange(10).astype(dtype)
136+
mn, mx = np.minmax(a)
137+
assert_equal(mn, a[0])
138+
assert_equal(mx, a[9])
139+
140+
def test_datetime_nat_propagation(self):
141+
for dtype in ("m8[s]", "m8[Y]"):
142+
a = np.arange(10).astype(dtype)
143+
a[3] = "NaT"
144+
mn, mx = np.minmax(a)
145+
assert_equal(mn, a[3])
146+
assert_equal(mx, a[3])
147+
148+
def test_complex(self):
149+
a = np.array([1 + 2j, 3 + 0j, 0 + 1j])
150+
mn, mx = np.minmax(a)
151+
assert_equal(mn, np.min(a))
152+
assert_equal(mx, np.max(a))
153+
154+
def test_consistency_with_min_max(self):
155+
"""Verify minmax matches separate min/max calls."""
156+
rng = np.random.default_rng(42)
157+
for _ in range(10):
158+
shape = rng.integers(1, 10, size=rng.integers(1, 4))
159+
a = rng.standard_normal(shape)
160+
mn, mx = np.minmax(a)
161+
assert_equal(mn, np.min(a))
162+
assert_equal(mx, np.max(a))
163+
164+
def test_consistency_with_min_max_axis(self):
165+
"""Verify minmax matches separate min/max calls along axes."""
166+
rng = np.random.default_rng(123)
167+
a = rng.standard_normal((5, 7, 3))
168+
for axis in [0, 1, 2, -1, (0, 2)]:
169+
mn, mx = np.minmax(a, axis=axis)
170+
assert_array_equal(mn, np.min(a, axis=axis))
171+
assert_array_equal(mx, np.max(a, axis=axis))
172+
173+
def test_list_input(self):
174+
mn, mx = np.minmax([3, 1, 4, 1, 5])
175+
assert_equal(mn, 1)
176+
assert_equal(mx, 5)
177+
178+
def test_empty_raises(self):
179+
with pytest.raises(ValueError):
180+
np.minmax(np.array([]))

0 commit comments

Comments
 (0)