8000 ENH: Add `__array_ufunc__` by charris · Pull Request #8247 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

ENH: Add __array_ufunc__ #8247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 43 commits into from
Apr 27, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
4fd7e84
ENH: Revert "Temporarily disable __numpy_ufunc__"
charris Nov 6, 2016
fcd11d2
ENH: Rename __numpy_ufunc__ to __array_ufunc__.
charris Nov 9, 2016
c7b25e2
ENH: Remove position arg from __array_ufunc__.
charris Nov 12, 2016
8a9e790
MAINT: Put PyArray_GetAttrString_SuppressException in get_attr_string.h
njsmith Jun 24, 2015
4dd5380
MAINT: dike out a bunch of weird old code implementing scalar power
njsmith Jun 24, 2015
7d9bc2f
BUG/ENH: Switch to simplified __array_ufunc__/binop interaction
njsmith Jun 22, 2015
e4b5163
MAINT: allow __array_ufunc__ = None to force binops to defer.
mhvk Mar 12, 2017
2e6d8c0
MAINT: Split out C code in ufunc_override.h to .c file.
mhvk Mar 15, 2017
d5c5ac1
MAINT: Add NPY_NO_EXPORT modifier to PyUFunc_CheckOverride.
charris Mar 16, 2017
3124e96
MAINT: for __array_ufunc__ pass inputs as *args, ensure out is tuple.
mhvk Mar 14, 2017
6a3ca31
DOC: describe current implementation of __array_ufunc__.
mhvk Mar 14, 2017
79bb733
DOC: Style and sphinx fixes for arrays.classes.rst.
charris Mar 23, 2017
7c3dc5a
TST: test that gufuncs are also overridden by __array_ufunc__.
mhvk Mar 25, 2017
71201d2
DOC: Describe __array_func__ in subclassing
mhvk Mar 15, 2017
3041710
ENH: implement ndarray.__array_ufunc__
mhvk Mar 13, 2017
5fe6fc6
DOC Update NEP to reflect actual implementation.
mhvk Mar 31, 2017
e092823
MAINT: let ndarray.__array_ufunc__ bail if any overrides are in place.
mhvk Apr 2, 2017
1147894
MAINT: Update array_ufunc NEP.
pv Apr 1, 2017
e325a10
DOC: Document behavior of ufuncs with default ndarray.__array_ufunc__
pv Apr 1, 2017
39c2273
DOC: Update ndarray.__array_ufunc__ documentation vs. review comments
pv Apr 2, 2017
6b41d11
DOC: clarify use of super and getattr
mhvk Apr 2, 2017
0ede0e9
DOC: update NEP again.
mhvk Apr 2, 2017
5f9252c
DOC: implement many smaller and bigger changes suggested in review.
mhvk Apr 4, 2017
8cc2f71
BUG,MAINT: ensure out=None is never passed on to __array_ufunc__.
mhvk Apr 4, 2017
856da73
DOC: remove left-over piece discussing binops
mhvk Apr 5, 2017
2b6c7fd
REVERT: remove __array_ufunc__ override for np.dot and ndarray.dot.
mhvk Apr 6, 2017
36e8494
REVERT: remove __array_ufunc__ override for np.matmul.
mhvk Apr 6, 2017
55500b9
MAINT: simplify now that __array_ufunc__ overrides ufuncs only.
mhvk Apr 6, 2017
25e973d
MAINT: split out umath-specific part of ufunc_override.
mhvk Apr 6, 2017
b1fa10a
BUG: ensure subclass of override class doesn't segfault.
mhvk Apr 8, 2017
1de8f5a
DOC: Mention `__array_ufunc__` in the 1.13.0 release notes.
charris Apr 8, 2017
a460015
DOC: ufunc-overrides: sync the discussion vs. current implementation
pv Apr 9, 2017
cd2e42c
DOC: ufunc-overrides: revise hierarchy discussion
pv Apr 9, 2017
ff628f1
BUG: Add back removed elision code.
charris Apr 9, 2017
1fc6e63
DOC,TST: clarify example of ndarray subclass using __array_ufunc__
mhvk Apr 10, 2017
a431743
BUG: Support nout == 0 and at method
eric-wieser Apr 12, 2017
1e460b7
DOC,MAINT: small corrections to NEP following Stephan's comments.
mhvk Apr 12, 2017
02600d3
ENH: Add NDArrayOperatorsMixin mixin class.
shoyer Apr 21, 2017
d3ff023
DOC: clarify recommendations for subclasses, deprecations.
mhvk Apr 21, 2017
b9359f1
MAINT: remove unnecessary checks, wrong code for 'outer', cleanup.
mhvk Apr 21, 2017
256a8ae
BUG: Fix ArrayLike(NDArrayOperatorsMixin) operations with object()
shoyer Apr 23, 2017
3272a86
ENH: Better error message for __array_ufunc__ not implemented
shoyer Apr 24, 2017
32221df
ENH: NDArrayOperatorsMixin calls ufuncs directly, like ndarray
shoyer Apr 27, 2017
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
Prev Previous commit
Next Next commit
REVERT: remove __array_ufunc__ override for np.matmul.
  • Loading branch information
mhvk authored and charris committed Apr 27, 2017
commit 36e84948a448c74efda008a9629c68e9fbb0a218
29 changes: 15 additions & 14 deletions doc/neps/ufunc-overrides.rst
Original file line number Diff line number Diff line change
Expand Up @@ -548,16 +548,16 @@ classes, we will provide a mixin class that provides overrides for all
binary operators.


Extension to other numpy functions
----------------------------------
Future extensions to other functions
------------------------------------

The ``__array_ufunc__`` method is also used to override
:func:`~numpy.matmul`, since while this function is not a Ufunc, it is
very similar. Indeed, :func:`~numpy.matmul` may well be implemented as
a (generalized) Ufunc in the future, as may happen with some other
functions, such as :func:`~numpy.median`, :func:`~numpy.min`,
:func:`~numpy.argsort`, etc. (in which case it will thus become possible
to override these as well).
Some numpy functions could be implemented as (generalized) Ufunc, in
which case it would be possible for them to be overridden by the
``__array_ufunc__`` method. A prime candidate is :func:`~numpy.matmul`,
which currently is not a Ufunc, but could be relatively easily be
rewritten as a (set of) generalized Ufuncs. The same may happen with
functions such as :func:`~numpy.median`, :func:`~numpy.min`, and
:func:`~numpy.argsort`.

Demo
====
Expand All @@ -576,16 +576,17 @@ proposed in this NEP. Here is a demo highlighting the functionality.::

In [4]: b = B()

In [5]: np.matmul(a, b)
In [5]: np.negative(b)
Out[5]: 'B'

In [6]: np.multiply(a, b)
Out[6]: 'B'

As a simple example, one could add the following ``__array_ufunc__`` to
SciPy's sparse matrices (just for ``np.matmul`` and ``np.multiply`` as
these are the two most common cases where users would attempt to use
sparse matrices with ufuncs)::
As a simple example, once ``np.matmul`` is covered as well (see above),
one could add the following ``__array_ufunc__`` to SciPy's sparse
matrices (just for ``np.matmul`` and ``np.multiply`` as these are the
two most common cases where users would attempt to use sparse matrices
with ufuncs)::

def __array_ufunc__(self, func, method, pos, inputs, **kwargs):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this implementation is correct. What if the caller provided the output array? That looks like it gets dropped. A bigger complication I think might be lurking is if out was provided and is some funky, nonstandard class it could potentially break anything. That would be another thing this method would need to check for, and would apply to almost any implementation.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That documentation is incorrect. The signature is

    def __array_ufunc__(self, func, method, *inputs, **kwargs)

Out(s) always ends up in kwargs in a tuple. Currently, if no out arrays supplied then no out keyword. As for funky classes, I think we should require them to clean up their act ;)

Copy link
Member Author
@charris charris Apr 3, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note also that the arguments are "normalized" before the call to __array_ufunc__ so that only the input arrays are in inputs, everything else is put into kwargs.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. However my point is that kwargs is never used. It is only part of the function definition. That's what I mean by "it gets dropped".

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattharrigan - for this part, best to look at the new version of this NEP... charris#11 (I think I got all your other commens; thanks!).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mhvk I don't think you got my comment, sorry it wasn't clear enough. In your example implementation kwargs is part of the method signature but it is never used. I think kwargs must be passed on to np.multiply and np.dot. For instance, doubt this will work as desired: "np.multiply(asp, a, out=b)"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for not looking carefully enough -- somehow I had not quite seen that you were commenting on the demo example -- I'm afraid this is left-over from the original PR, which is also why there still is this pos argument; another thing that should change here is that the example is with matmul, and that the whole setup follows "best practice" (which we still need to agree on...).

"""Method for compatibility with NumPy's ufuncs and matmul
Expand Down
15 changes: 8 additions & 7 deletions doc/source/reference/arrays.classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,14 @@ NumPy provides several hooks that classes can customize:
:func:`__array_ufunc__` operations return :obj:`NotImplemented`, a
:exc:`TypeError` is raised.

.. note:: In addition to ufuncs, :func:`__array_ufunc__` also
overrides the behavior of :func:`numpy.matmul`, even though it
is not a ufunc. But it can be thought of as :ref:`generalized
universal functions<c-api.generalized-ufuncs>` (which are
overridden). Indeed, we intend to rewrite :func:`numpy.matmul`
as such, and possibly do the same to other relevant functions,
such as :func:`numpy.median`, :func:`numpy.argsort`, etc.
.. note:: We intend to re-implement numpy functions as (generalized)
Ufunc, in which case it will become possible for them to be
overridden by the ``__array_ufunc__`` method. A prime candidate is
:func:`~numpy.matmul`, which currently is not a Ufunc, but could be
relatively easily be rewritten as a (set of) generalized Ufuncs. The
same may happen with functions such as :func:`~numpy.median`,
:func:`~numpy.min`, and :func:`~numpy.argsort`.


Like with some other special methods in python, such as ``__hash__`` and
``__iter__``, it is possible to indicate that your class does *not*
Expand Down
42 changes: 12 additions & 30 deletions numpy/core/src/multiarray/multiarraymodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2187,7 +2187,7 @@ array_matrixproduct(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject* kwds)
kwlist, &a, &v, &o)) {
return NULL;
}
if (o) {
if (o != NULL) {
if (o == Py_None) {
o = NULL;
}
Expand Down Expand Up @@ -2327,14 +2327,10 @@ array_vdot(PyObject *NPY_UNUSED(dummy), PyObject *args)
* out: Either NULL, or an array into which the output should be placed.
*
* Returns NULL on error.
* Returns NotImplemented on priority override.
*/
static PyObject *
array_matmul(PyObject *NPY_UNUSED(m), PyObject *args, PyObject* kwds)
{
static PyObject *matmul = NULL;
int errval;
PyObject *override = NULL;
PyObject *in1, *in2, *out = NULL;
char* kwlist[] = {"a", "b", "out", NULL };
PyArrayObject *ap1, *ap2, *ret = NULL;
Expand All @@ -2345,47 +2341,33 @@ array_matmul(PyObject *NPY_UNUSED(m), PyObject *args, PyObject* kwds)
char *subscripts;
PyArrayObject *ops[2];

npy_cache_import("numpy.core.multiarray", "matmul", &matmul);
if (matmul == NULL) {
return NULL;
}

errval = PyUFunc_CheckOverride((PyUFuncObject*)matmul, "__call__",
args, kwds, &override, 2, 1);
if (errval) {
return NULL;
}
else if (override) {
return override;
}

if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O:matmul", kwlist,
&in1, &in2, &out)) {
return NULL;
}

if (out == Py_None) {
out = NULL;
}
if (out != NULL && !PyArray_Check(out)) {
PyErr_SetString(PyExc_TypeError,
"'out' must be an array");
return NULL;
if (out != NULL) {
if (out == Py_None) {
out = NULL;
}
else if (!PyArray_Check(out)) {
PyErr_SetString(PyExc_TypeError, "'out' must be an array");
return NULL;
}
}

dtype = PyArray_DescrFromObject(in1, NULL);
dtype = PyArray_DescrFromObject(in2, dtype);
if (dtype == NULL) {
PyErr_SetString(PyExc_ValueError,
"Cannot find a common data type.");
PyErr_SetString(PyExc_ValueError, "Cannot find a common data type.");
return NULL;
}
typenum = dtype->type_num;

if (typenum == NPY_OBJECT) {
/* matmul is not currently implemented for object arrays */
PyErr_SetString(PyExc_TypeError,
"Object arrays are not currently supported");
"Object arrays are not currently supported");
Py_DECREF(dtype);
return NULL;
}
Expand All @@ -2407,7 +2389,7 @@ array_matmul(PyObject *NPY_UNUSED(m), PyObject *args, PyObject* kwds)
if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) {
/* Scalars are rejected */
PyErr_SetString(PyExc_ValueError,
"Scalar operands are not allowed, use '*' instead");
"Scalar operands are not allowed, use '*' instead");
return NULL;
}

Expand Down
37 changes: 0 additions & 37 deletions numpy/core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -5254,43 +5254,6 @@ def test_matrix_matrix_values(self):
res = self.matmul(m12, m21)
assert_equal(res, tgt12_21)

def test_array_ufunc_override(self):

class B(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)

def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
return "B"

class C(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)

def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
return NotImplemented

class D(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)

__array_ufunc__ = None

a = np.ones(2)
b = B([1, 2])
c = C([1, 2])
d = D([1, 8000 2])
assert_equal(self.matmul(b, a), "B")
assert_equal(self.matmul(a, b), "B")
assert_equal(self.matmul(b, c), "B")
assert_equal(self.matmul(c, b), "B")
assert_equal(self.matmul(b, d), "B")
assert_equal(self.matmul(d, b), "B")
assert_raises(TypeError, self.matmul, a, c)
assert_raises(TypeError, self.matmul, c, a)
assert_raises(TypeError, self.matmul, d, a)
assert_raises(TypeError, self.matmul, a, d)


class TestMatmul(MatmulCommon, TestCase):
matmul = np.matmul
Expand Down
13 changes: 7 additions & 6 deletions numpy/core/tests/test_umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -1577,19 +1577,19 @@ def __array_ufunc__(self, func, method, *inputs, **kwargs):
a = A()
b = np.matrix([1])
res0 = np.multiply(a, b)
res1 = np.matmul(a, b)
res1 = np.multiply(b, b, out=a)

# self
assert_equal(res0[0], a)
assert_equal(res1[0], a)
assert_equal(res0[1], np.multiply)
assert_equal(res1[1], np.matmul)
assert_equal(res1[1], np.multiply)
assert_equal(res0[2], '__call__')
assert_equal(res1[2], '__call__')
assert_equal(res0[3], (a, b))
assert_equal(res1[3], (a, b))
assert_equal(res1[3], (b, b))
assert_equal(res0[4], {})
assert_equal(res1[4], {})
assert_equal(res1[4], {'out': (a,)})

def test_ufunc_override_mro(self):

Expand Down Expand Up @@ -1878,8 +1878,9 @@ def __array_ufunc__(self, *a, **kwargs):
raise ValueError("oops")

a = A()
for func in [np.divide, np.matmul]:
assert_raises(ValueError, func, a, a)
assert_raises(ValueError, np.negative, 1, out=a)
assert_raises(ValueError, np.negative, a)
assert_raises(ValueError, np.divide, 1., a)

def test_gufunc_override(self):
# gufunc are just ufunc instances, but follow a different path,
Expand Down
0