Skip to content

Array ufunc doc updates - #11

Merged
charris merged 7 commits into
charris:enable-numpy_ufuncfrom
mhvk:array_ufunc_doc_updates
Apr 5, 2017
Merged

charris merged 7 commits into
charris:enable-numpy_ufuncfrom
mhvk:array_ufunc_doc_updates

Conversation

@mhvk

@mhvk mhvk commented Apr 2, 2017

Copy link
Copy Markdown

No description provided.

for item in inputs + outputs):
if (hasattr(item, '__array_ufunc__') and
type(item).__array_ufunc__ is not ndarray.__array_ufunc__):
return NotImplemented

@pv pv Apr 2, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This doesn't do the superclass check discussed in the text above.
If that's dropped (and the default method deals with all subclasses), the text should argue how the type casting hierarchy stays valid.

The subclasses-first rule in the dispatch may make the default implementation OK, but that probably deserves separate discussion to be sure about it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@pv - if this is wrong, so is the actual implementation, so I'll only fix that once that is OK. But just to be sure I understand: what is missing here is for ndarray to check whether there it has a superclass that implements __array_ufunc__ and then call it, correct? I.e., the idea is that someone defined something like class MyNew(ndarray, MyBase), which means MyBase gets inserted between ndarray and object, and MyBase.__array_ufunc__ exists. I definitely did not consider that, but I think you're right that I should.

@pv pv Apr 3, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Consider two subclasses that inherit the default behavior:

class A(ndarray):
    pass
class B(ndarray):
    pass

However, now I think the following happens:

type(a + b) is A
type(b + a) is B

(Had to think a bit what was actually wrong, but drawing the diagram it came out...)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ok, sorry that's not it --- the default implementation doesn't get called at all.
So the type restriction is actually on "legacy" ndarray subclasses, which maybe is OK, because then this is resolved by __array_priority__...

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I now realise my own example is meaningless, since it cannot change the location of ndarray on the type hierarchy. So my example class MyNew(ndarray, MyBase) is explicitly inconsistent with this, and thus should never be done.

``C > B > D``. The type B is incompatible relative to A and vice
versa, and A and ndarray are incompatible relative to D. Ufunc
expressions involving these classes should produce results of the
highest type involved or raise a :exc:`TypeError`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I added some additional examples of "bad" cases in my branch here that can be useful to add.
(The binop discussion there is not yet ready for discussion, that's just writing some thoughts down.).

Comment thread doc/neps/ufunc-overrides.rst Outdated
this is not the case for comparison operators. For those, a quantity
class would return a plain array.

Note also that the legacy behaviour of numpy ufunc (legacy) behavior is

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

remove second "legacy behavior"

def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
# Cannot handle items that have __array_ufunc__ (other than our own).
outputs = kwargs.get('out', ())
for item in inputs + outputs):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remove + outputs):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I think this is correct: I'm adding input and output tuples, so I can iterate over all inputs and outputs.

outputs = kwargs.get('out', ())
for item in inputs + outputs):
if (hasattr(item, '__array_ufunc__') and
type(item).__array_ufunc__ is not ndarray.__array_ufunc__):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Is there a reason why this needs to use type(item) instead of item?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Yes ;)

In [1]: class A(ndarray): pass

In [2]: A((1,1)).__array_ufunc__ is ndarray.__array_ufunc__
Out[2]: False

In [3]: type(A((1,1))).__array_ufunc__ is ndarray.__array_ufunc__
Out[3]: True

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Note that the bound method is not the same as the unbound method.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Although it might be that == would be a better operator than is. Not sure what the difference is in this context, but == seems to do better with subclasses of python classes as opposed to subclasses of C defined types.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I thought it was a pep8 error to compare classes using ==...

Comment thread doc/neps/ufunc-overrides.rst Outdated
In this case, standard Python override rules combined with the above
discussion would imply::
def __imul__(self, other):
return np.multiply(self, other, out=self)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

should be out=(self,) for consistency with how numpy itself does things

Comment thread doc/neps/ufunc-overrides.rst Outdated
is a subclass of :class:`ndarray`, Python calls ``mine.__rmul__`` first.)
def __imul__(self, other):
result = self.__array_ufunc__(np.multiply, '__call__', self, other,
out=self)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

out=(self,) as above

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Nice catches; here it is even wrong, since for __array_ufunc__ it really should be a tuple.


class MyObject(object):
__array_ufunc__ = None
# Option 1: call ufunc directly

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Do we really need both options (1) and (2)? When would someone choose one vs the other?

I agree with @pv that we should not recommend both (if possible), because it makes things even more confusing.

To give one concrete example, I don't think the implementation of ArrayLike in my gist would work with option (2), because that implementation of __array_ufunc__ calls getattr(ufunc, method) instead of using super(), and hence can never return NotImplemented.

Even with that example aside, if both options can be made to work, we should prefer option (1) because it uses public API.

@pv pv Apr 2, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I think the options are quite different --- one allows opt-out with array_ufunc, and the other not. The NEP should explain here only one option --- ndarray does only one of them, and other classes should follow how it does it.

As an aside, the ArrayLike example in the gist uses an unconditional nested ufunc dispatch --- which puts it in the type hierarchy above all other types, which probably is not intended (namely the result from any ufunc involving an ArrayLike returns an ArrayLike or raises a TypeError). I think this can be avoided by first making type checks (e.g. accept ndarray, ArrayLike and otherwise return NotImplemented) --- or, delegate also the type checking by calling self.value.__array_ufunc__(...). I don't really see this as a question about a public vs private API, as the special method is not really private API, and you should be able to delegate it the same way as __mul__ et al.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

As an aside, the ArrayLike example in the gist uses an unconditional nested ufunc dispatch --- which puts it in the type hierarchy above all other types, which probably is not intended.

Indeed, this is not what I actually want. Two different classes that implement this exact same interface would have an ill-defined result when they are added together.

I was hoping for some sort of cooperative behavior without setting an explicit type hierarchy, but I realize now that that is impossible. If ArrayLike wants to be able to wrap arbitrary other array types, it should expose a registration function that allows other array types to say that they can be wrapped by ArrayLike instead of trying to wrap everything.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Just another note: I think it's important to include numbers.Number in that list of handled types, too.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I updated my gist with the mixin to follow @mhvk's option 2 and @pv's guidance about type hierarchies for ArrayLike. I kept a redundant check for other.__array_ufunc__ is None in binary operations, because we really don't want to people to try to write array types that are above classes that set __array_ufunc__ = None in the type-hierarchy, and this precludes the possibility of making that mistake with a poor __array_ufunc__ implementation.

I agree that we should recommend only copying the behavior that we choose for numpy.ndarray itself, but one additional consideration (especially for the mixin class) is that option 2 works even in versions of NumPy prior to __array_ufunc__ but option 1 does not. So possibly we would recommend the mixin approach in my gist for people who need more backwards compatibility and implement a different mixin for numpy 1.13+ that can assume that ufunc dispatch to __array_ufunc__ works.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

This is really useful (I think this will help me rewrite Quantity.__array_ufunc__ in a better way ;-), but also leaves me slightly confused: in this gist, @shoyer uses option 2, where we call __array_ufunc__ inside the binop (but write __array_ufunc__ such that it returns NotImplemented if another function defines __array_ufunc__ and it cannot handle it). I like this most. However, ndarray currently does something much closer to option 1: see https://github.com/numpy/numpy/pull/8247/files#diff-a76a87b213692b2a554a63aebea985caR89

So, which should I pick? Here, we should also consider that we might well end up rewriting the ndarray code to use ndarray.__array_ufunc__...

Comment thread doc/neps/ufunc-overrides.rst Outdated
class like :class:`MaskedArray`, which only cares that whatever
it contains is an :class:`ndarray` subclass, a reimplementation with
``__array_ufunc__`` is probably more easily done by directly applying
the ufunc to its data, and then adjusting the mask.

@pv pv Apr 2, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Or, dispatch to self.value.__array_ufunc__? --- There's a distinction in what types are handled, in the sense that a nested ufunc call will raise TypeErrors --- so I think if you call the ufunc, you need to first check that you handle the types of the inputs. Whereas, passing it on to self.value.__array_ufunc__ delegates the responsibility of type checking to the wrapped object.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

In the example that follows delegating to self.value.__array_ufunc__ would just use the ndarray.__array_ufunc__ implementation, which would not be able to handle a quantity and thus return NotImplemented. However, I think that strictly one should think of this as part of a "can I handle this" clause, so I guess one should ensure to return NotImplemened if the ufunc call on self.value fails. I will include an explicit example.

It is useful to think of the typecasting hierarchy as a graph (see
example below) in which, for any given class A, all other classes that
define ``__array_ufunc__`` must belong to exactly one of three groups
(making this an directed acyclic graph):

@pv pv Apr 2, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I would really include the formal definition I had:

   For any two different types *A*, *B*, the relation "A can handle B" 
   defined as::

       a.__array_ufunc__(..., b, ...) is not NotImplemented

   for instances *a* and *b* of *A* and *B*, defines the
   edges B->A of a graph.

   This also assumes A.__array_ufunc__ either returns
   an instance of A, NotImplemented, or raises an error.

otherwise, it's difficult to see from the following explanation what the "graph" exactly means in terms of array_ufunc.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The problem is that you assume someone knows what a "graph" is... I thought it was not so relevant to the NEP, but am reconsidering. I now adjusted the text, trying to make it friendly to types like myself...

- Return :obj:`NotImplemented` if any argument has a type that is above
A or with which it is incompatible.

Note that there are, as always, exceptions. For instance, for a

@pv pv Apr 2, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It should be said that exceptions make the above analysis not apply any more, and need separate consideration.

Do we understand what happens if you return a different type?
Is it possible to lose commutativity (maybe no) or transitivity (yes? but maybe not a problem for comparisons?)

@pv pv Apr 3, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It's probably possible to fit different return types in the above discussion:

For each class A implementing `A.__array_ufunc__`, draw a directed edge from
all input types B to the output type `type(c)` in 
`c = a.__array_ufunc__(..., b, ...)`, if `c is not NotImplemented`.

Then returning ndarray results produces a cycle. This loses the type transitivity, but maybe it appearrs only(?) in contrived examples:

q = Quantity(...)
a = np.array(...)
type((a > a) + q) is Quantity
type(a > (a + q)) is ndarray

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I'd love to be clearer here, so maybe we can work out the example better, since for Quantity, the logic is quite simple:

from astropy import units as u
a = 1.
q = 1.*u.m
type(q + q)
# Quantity
type (q > q)
# ndarray
type(a > (a + q))
# UnitsError: Can only apply 'add' function to dimensionless quantities when other argument is not a quantity (unless the latter is all zero/infinity/nan)
dq = 1.*u.dimensionless_unscaled
type(a > (a + dq))
# ndarray

Would it make sense to see Quantity as two types, with and without dimension (and there is an exception for all-zero, inf, nan, mostly because this makes many more functions work...)

their arguments were in, the above implies that ``__array_ufunc__`` for
type A should:

- Return an object of type A if all other arguments are of types below A.

@pv pv Apr 2, 2017 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It's also OK to return NotImplemented for input of a type below A (in case the casting is indirect).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I'm a bit confused how this translates to a graph or subclasses. Could you expand a bit?

@charris

charris commented Apr 3, 2017

Copy link
Copy Markdown
Owner

@mhvk I'm going to let this settle for a bit before merging...

@pv

pv commented Apr 3, 2017 via email

Copy link
Copy Markdown

@mhvk

mhvk commented Apr 4, 2017 •

Copy link
Copy Markdown
Author

I think I covered most comments, so pushed a new version; I do hope this doesn't hide unaddressed comments... Not quite ready to merge yet: still need to work around some corner cases in type hierarchy with @pv.

@mhvk

mhvk commented Apr 5, 2017

Copy link
Copy Markdown
Author

As comments are starting to get hidden, I think the open issues are (mostly for @pv):

  • How to describe the case where one does not return an instance of one's own type (with comparison operators probably being a good, general example: a bool is already a very different type than a number. And we're considering making things like argsort gufuncs, which would seem to provide another good case. (Though I see why it can break things: little is as annoying as the fact that ndarray sometimes returns plain python objects rather than scalar arrays.)
  • I'm not sure what you meant that a type can return NotImplemented for types below itself (if casting is indirect).
  • we still need some decision on which of the two options to show in the MyObject example.

@pv

pv commented Apr 5, 2017 via email

Copy link
Copy Markdown

@pv

pv commented Apr 5, 2017 via email

Copy link
Copy Markdown

@charris
charris merged this pull request into charris:enable-numpy_ufunc Apr 5, 2017
@charris

charris commented Apr 5, 2017

Copy link
Copy Markdown
Owner

@pv OK, merged.

@mhvk
mhvk deleted the array_ufunc_doc_updates branch April 5, 2017 13:34
charris pushed a commit that referenced this pull request Nov 21, 2021
commit 9c833bed5879d77e625556260690c349de18b433
Author: Thomas Li <[email protected]>
Date:   Wed Nov 17 16:21:27 2021 -0800

    Add Windows config to GHA

    update script [wheel build]

    typo [wheel build]

    fix typo? [wheel build]

    fix linux builds? [wheel build]

    typo [wheel build]

    add license and pin to windows 2016

    skip tests [wheel build]

    pin to windows 2019 instead [wheel build]

    try to find out the error on windows [wheel build]

    maybe fix? [wheel build]

    maybe fix? [wheel build]

    fix? [wheel build]

    cleanup [wheel build]

    Add Windows config to GHA

    update script [wheel build]

    typo [wheel build]

    fix typo? [wheel build]

    fix linux builds? [wheel build]

    typo [wheel build]

    add license and pin to windows 2016

    skip tests [wheel build]

    pin to windows 2019 instead [wheel build]

    try to find out the error on windows [wheel build]

    maybe fix? [wheel build]

    maybe fix? [wheel build]

    fix? [wheel build]

    cleanup [wheel build]

    Update LICENSE_win32.txt

    Update LICENSE_win32.txt

    Add Windows config to GHA

    update script [wheel build]

    typo [wheel build]

    fix typo? [wheel build]

    fix linux builds? [wheel build]

    typo [wheel build]

    add license and pin to windows 2016

    skip tests [wheel build]

    pin to windows 2019 instead [wheel build]

    try to find out the error on windows [wheel build]

    maybe fix? [wheel build]

    maybe fix? [wheel build]

    fix? [wheel build]

    cleanup [wheel build]

    Update LICENSE_win32.txt

    Update LICENSE_win32.txt

    Update cibw_test_command.sh

commit 4bd12df
Author: Thomas Li <[email protected]>
Date:   Mon Nov 15 17:28:47 2021 -0800

    # This is a combination of 14 commits.
    # This is the 1st commit message:

    Add Windows config to GHA
    # This is the commit message #2:

    update script [wheel build]
    # This is the commit message #3:

    typo [wheel build]
    # This is the commit message #4:

    fix typo? [wheel build]
    # This is the commit message #5:

    fix linux builds? [wheel build]
    # This is the commit message #6:

    typo [wheel build]
    # This is the commit message #7:

    add license and pin to windows 2016
    # This is the commit message #8:

    skip tests [wheel build]
    # This is the commit message #9:

    pin to windows 2019 instead [wheel build]
    # This is the commit message #10:

    try to find out the error on windows [wheel build]
    # This is the commit message #11:

    maybe fix? [wheel build]
    # This is the commit message #12:

    maybe fix? [wheel build]
    # This is the commit message #13:

    fix? [wheel build]
    # This is the commit message #14:

    cleanup [wheel build]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants