Repository navigation
Array ufunc doc updates - #11
Conversation
| for item in inputs + outputs): | ||
| if (hasattr(item, '__array_ufunc__') and | ||
| type(item).__array_ufunc__ is not ndarray.__array_ufunc__): | ||
| return NotImplemented |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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...)
There was a problem hiding this comment.
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__...
There was a problem hiding this comment.
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`. |
There was a problem hiding this comment.
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.).
| 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 |
| 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): |
There was a problem hiding this comment.
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__): |
There was a problem hiding this comment.
Is there a reason why this needs to use type(item) instead of item?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Note that the bound method is not the same as the unbound method.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I thought it was a pep8 error to compare classes using ==...
| 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) |
There was a problem hiding this comment.
should be out=(self,) for consistency with how numpy itself does things
| 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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Just another note: I think it's important to include numbers.Number in that list of handled types, too.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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__...
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?)
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
It's also OK to return NotImplemented for input of a type below A (in case the casting is indirect).
There was a problem hiding this comment.
I'm a bit confused how this translates to a graph or subclasses. Could you expand a bit?
|
@mhvk I'm going to let this settle for a bit before merging... |
|
The point of this section is to provide some tools using which some
properties of Python-style multiple dispatch can be analysed, and not so
much to provide examples on how to write classes. Some of the points such
as when exactly commutativity and transitivity of result types is lost were
not that obvious in the beginning, and since this influenced the design in
some parts, it is useful to spell it out I think.
4.4.2017 0.06 "Marten van Kerkwijk" <[email protected]> kirjoitti:
… ***@***.**** commented on this pull request.
------------------------------
In doc/neps/ufunc-overrides.rst
<#11 (comment)>:
> +----------------------
+
+Similarly to the Python operator dispatch mechanism, writing ufunc
+dispatch methods requires some discipline in order to achieve
+predictable results.
+
+In particular, it is useful to maintain a clear idea of what types can
+be upcast to others, possibly indirectly (i.e. A->B->C is implemented
+but direct A->C not). Moreover, one should make sure the implementations of
+``__array_ufunc__``, which implicitly define the type casting hierarchy,
+don't contradict this.
+
+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):
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...
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#11 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AACI5viaAKHagRtMdQqFuqDU-pyiJPt_ks5rsW1SgaJpZM4Mw8O9>
.
|
|
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. |
|
As comments are starting to get hidden, I think the open issues are (mostly for @pv):
|
|
Hi, I can edit the analysis part myself and send a PR, but a bit later.
.
The question about which option should make user-defined classes follow
what ndarray does:
.
(i) if `__array_ufunc__ = None` is the only way to opt-out from binops
in ndarray, then user-defined classes follow "Option 1".
(ii) if any `__array_ufunc__`, not only `__array_ufunc__ = None` opts
out, then user-defined classes follow "Option 2".
.
The question on which option to pick for ndarray (and consequently for
user-defined classes) is probably something to be discussed in the main
thread. As I understand, the choice in the code is (i).
.
The NEP should be edited to contain some discussion of why a particular
choice was made, and not the other --- but in a separate section
discussing alternatives to the proposed design we considered but discarded.
|
|
I suggest to merge this PR soon, so that it's easier to do further work
on the NEP.
|
|
@pv OK, merged. |
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]
No description provided.