Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
1ad9475
Add regression tests for gh-5031 (__array_function__ min/amin alias)
rgommers Jul 1, 2019
c3b1d24
Deal with numpy aliases and functions and numpy functions not in dask
rgommers Jul 2, 2019
032dfff
Clean up @implements decorator, addresses review comment on gh-5043
rgommers Jul 2, 2019
ed18a2a
Better handling of args, kwargs for __array_function__.
rgommers Jul 2, 2019
5526d4d
Add @implements to all functions in reductions.py and routines.py
rgommers Jul 2, 2019
f0c4550
Add @implements to support __array_function__ for fft functions
rgommers Jul 2, 2019
89911e1
Add @implements to support __array_function__ to linalg functions
rgommers Jul 2, 2019
0b42d33
Add @implements to dask/array/core functions
rgommers Jul 2, 2019
94c5b9e
Change __array_function__ test from check for TypeError to check for …
rgommers Jul 2, 2019
93becb6
Fix some issues with array_ufunc tests. isreal/iscomplex/real/imag ar…
rgommers Jul 2, 2019
3b38c98
Add argmin/argmax/nanargmin/nanargmax to __array_function__ dict
rgommers Jul 2, 2019
bcf0110
Add __array_function__ handling for functions in creation.py
rgommers Jul 2, 2019
64aa2f0
Use @implements decorator as a function to clean up some __array_func…
rgommers Jul 3, 2019
5e06685
Make warning message in __array_function__ more explicit, change to F…
rgommers Jul 3, 2019
2561bc0
Fix last test failure - FutureWarning only happens if NEP18 is enabled
rgommers Jul 3, 2019
bcd9707
Update __array_function__ to only use dict mapping for aliases and na…
rgommers Jul 3, 2019
9474b8c
Change warning message for __array_function__ to use map_blocks.
rgommers Jul 3, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 56 additions & 4 deletions dask/array/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import numpy as np

from . import chunk
from .. import config
from .. import config, compute
from ..base import (
DaskMethodsMixin,
tokenize,
Expand Down Expand Up @@ -138,6 +138,33 @@ def getter_inline(a, b, asarray=True, lock=None):
from .optimization import optimize, fuse_slice


# __array_function__ dict for mapping aliases and mismatching names
_HANDLED_FUNCTIONS = {}


def implements(*numpy_functions):
"""Register an __array_function__ implementation for dask.array.Array

Register that a function implements the API of a NumPy function (or several
NumPy functions in case of aliases) which is handled with
``__array_function__``.

Parameters
----------
\\*numpy_functions : callables
One or more NumPy functions that are handled by ``__array_function__``
and will be mapped by `implements` to a `dask.array` function.
"""

def decorator(dask_func):
for numpy_function in numpy_functions:
_HANDLED_FUNCTIONS[numpy_function] = dask_func

return dask_func

return decorator


def slices_from_chunks(chunks):
""" Translate chunks tuple to a set of slices in product order

Expand Down Expand Up @@ -1221,16 +1248,41 @@ def __array__(self, dtype=None, **kwargs):
def __array_function__(self, func, types, args, kwargs):
import dask.array as module

def handle_nonmatching_names(func, args, kwargs):
if func not in _HANDLED_FUNCTIONS:
warnings.warn(
"The `{}` function is not implemented by Dask array. "
"You may want to use the da.map_blocks function "
"or something similar to silence this warning. "
"Your code may stop working in a future release.".format(
func.__module__ + "." + func.__name__
),
FutureWarning,
)
# Need to convert to array object (e.g. numpy.ndarray or
# cupy.ndarray) as needed, so we can call the NumPy function
# again and it gets the chance to dispatch to the right
# implementation.
args, kwargs = compute(args, kwargs)
return func(*args, **kwargs)

return _HANDLED_FUNCTIONS[func](*args, **kwargs)

# First try to find a matching function name. If that doesn't work, we may
# be dealing with an alias or a function that's simply not in the Dask API.
# Handle aliases via the _HANDLED_FUNCTIONS dict mapping, and warn otherwise.
for submodule in func.__module__.split(".")[1:]:
try:
module = getattr(module, submodule)
except AttributeError:
return NotImplemented
return handle_nonmatching_names(func, args, kwargs)

if not hasattr(module, func.__name__):
return NotImplemented
return handle_nonmatching_names(func, args, kwargs)

da_func = getattr(module, func.__name__)
if da_func is func:
return NotImplemented
return handle_nonmatching_names(func, args, kwargs)
return da_func(*args, **kwargs)

@property
Expand Down
4 changes: 3 additions & 1 deletion dask/array/reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from toolz import compose, partition_all, get, accumulate, pluck

from . import chunk
from .core import _concatenate2, Array, handle_out
from .core import _concatenate2, Array, handle_out, implements
from .blockwise import blockwise
from ..blockwise import lol_tuples
from .creation import arange, diagonal
Expand Down Expand Up @@ -363,6 +363,7 @@ def prod(a, axis=None, dtype=None, keepdims=False, split_every=None, out=None):
)


@implements(np.min, np.amin)
@wraps(chunk.min)
def min(a, axis=None, keepdims=False, split_every=None, out=None):
return reduction(
Expand All @@ -377,6 +378,7 @@ def min(a, axis=None, keepdims=False, split_every=None, out=None):
)


@implements(np.max, np.amax)
@wraps(chunk.max)
def max(a, axis=None, keepdims=False, split_every=None, out=None):
return reduction(
Expand Down
2 changes: 2 additions & 0 deletions dask/array/routines.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
is_scalar_for_elemwise,
broadcast_to,
tensordot_lookup,
implements,
)

from .einsumfuncs import einsum # noqa
Expand Down Expand Up @@ -804,6 +805,7 @@ def corrcoef(x, y=None, rowvar=1):
return (c / sqr_d) / sqr_d.T


@implements(np.round, np.round_)
@derived_from(np)
def round(a, decimals=0):
return a.map_blocks(np.round, decimals=decimals, dtype=a.dtype)
Expand Down
23 changes: 22 additions & 1 deletion dask/array/tests/test_array_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@
lambda x: np.matmul(x, x),
lambda x: np.mean(x),
lambda x: np.stack([x, x]),
lambda x: np.block([x, x]),
lambda x: np.sum(x),
lambda x: np.var(x),
lambda x: np.vstack(x),
lambda x: np.linalg.norm(x),
lambda x: np.min(x),
lambda x: np.amin(x),
lambda x: np.round(x),
],
)
def test_array_function_dask(func):
Expand Down Expand Up @@ -57,13 +61,16 @@ def test_array_function_fft(func):
lambda x: np.min_scalar_type(x),
lambda x: np.linalg.det(x),
lambda x: np.linalg.eigvals(x),
lambda x: np.median(x),
],
)
def test_array_notimpl_function_dask(func):
x = np.random.random((100, 100))
y = da.from_array(x, chunks=(50, 50))

with pytest.raises(TypeError):
with pytest.warns(
FutureWarning, match="The `.*` function is not implemented by Dask"
):
func(y)


Expand Down Expand Up @@ -220,3 +227,17 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):

# Check that they are equivalent arrays.
assert_eq(xx, yy, check_meta=False)


def test_median_func():
# Regression test for __array_function__ becoming default in numpy 1.17
# dask has no median function, so ensure that this still calls np.median
image = da.from_array(np.array([[0, 1], [1, 2]]), chunks=(1, 2))
if IS_NEP18_ACTIVE:
with pytest.warns(
FutureWarning,
match="The `numpy.median` function is not implemented by Dask",
):
assert int(np.median(image)) == 1
else:
assert int(np.median(image)) == 1
10 changes: 10 additions & 0 deletions dask/array/tests/test_numpy_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,13 @@ def test_slice_dtype(dtype, index):
result = _make_sliced_dtype(dtype, index)
expected = np.ones((5, len(dtype)), dtype=dtype)[index].dtype
assert result == expected


def test_min_max_round_funcs():
# Regression test for gh-5031
image = da.from_array(np.array([[0, 1], [1, 2]]), chunks=(1, 2))
# These use __array_function__ (and min/max/round are aliased,
# to amin/amax/round_ in numpy)
assert int(np.min(image)) == 0
assert int(np.max(image)) == 2
assert np.round(image)[1, 1] == 2
1 change: 1 addition & 0 deletions dask/array/tests/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ def test_reduction_names():
assert x.mean().name.startswith("mean")


@pytest.mark.filterwarnings("ignore:`argmax` is not implemented by dask")
@pytest.mark.parametrize("func", [np.sum, np.argmax])
def test_array_reduction_out(func):
x = da.arange(10, chunks=(5,))
Expand Down
4 changes: 2 additions & 2 deletions dask/array/tests/test_ufunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ def test_ufunc_outer():
def test_complex(ufunc):

dafunc = getattr(da, ufunc)
# Note that these functions are not NumPy ufuncs
npfunc = getattr(np, ufunc)

real = np.random.randint(1, 100, size=(20, 20))
Expand All @@ -255,7 +256,6 @@ def test_complex(ufunc):
# applying Dask ufunc doesn't trigger computation
assert isinstance(dafunc(darr), da.Array)
assert_eq(dafunc(darr), npfunc(arr))

assert_eq(npfunc(darr), npfunc(arr))

# applying Dask ufunc to normal ndarray triggers computation
Expand Down Expand Up @@ -394,7 +394,7 @@ def test_array_ufunc():
x = np.arange(24).reshape((4, 6))
d = da.from_array(x, chunks=(2, 3))

for func in [np.sin, np.isreal, np.sum, np.negative, partial(np.prod, axis=0)]:
for func in [np.sin, np.sum, np.negative, partial(np.prod, axis=0)]:
Comment thread
rgommers marked this conversation as resolved.
Resolved
assert isinstance(func(d), da.Array)
assert_eq(func(d), func(x))

Expand Down