[Numpy-discussion] Dot as a method
bart.vandereycken at cs.kuleuven.be
Thu Jul 6 06:49:57 CDT 2006
Tim Hochberg wrote:
> Bart Vandereycken wrote:
>> Hi all,
>> reading the thread "Ransom proposals" I was wondering why there isn't a
>> ndarray.dot() method? There is already a scipy.sparse.dot() so this
>> would fit nicely in the whole idea of polymorphism.
> Are you sure about that?
> The problem with a dot method (aside from a over proliferation of
> methods in general) is that to be done correctly you want to choose a
> particular implementation of dot based *both* of its arguments. A method
> does a good job dispatching on a single argument, but falls down when
> dispatching on two types. Let's look at this specific case. Imagine that
> in addition ndarray.dot and sparse.dot, we also stick a dot method on
> ma.masked, etc. Now in order to fully exploit polymorphism and get
> maximum efficiency, we want asparsearray.dot(amaskedarray) to correctly
> treat the masked values (ma.dot treats them as zeros) and to not
> instantiate a dense version of the sparsearray. But in order to do that
> all three classes need to know about the other two. That's possible, if
> messy since all three of these are known in advance, but this approach
> becomes untenable if you classes outside core numpy or scipy to
> participate as full citizens.
You're right that you need to put the class specific dot code somewhere.
However, it would be better if this can be done in a clean way. By
the way I don't fixate on methods or functions, I just want something
Suppose I have written my own matrix class (custmatrix) with it's own
fast matrix-vector product. How can I extend numpy code so that is uses
this fast multiplication when I want a_custmatrix*a_ndarray or
> What does appear fit well here is generic functions / multimethods /
> protocols as discussed in some detail on pydev-3000 a couple of months
> ago. This would allow classes defined outside of core numpy and scipy to
> work correctly and efficiently with dot as long as they register
> appropriate versions of dot. If I wasn't swamped right at the moment I'd
> prototype this up and see how it works in practice.
Right, I was thinking about multimethods too after reading
The other solution that simulates double dispatching is the Visitor
pattern, but it has a lot of disadvantages (difficult to add custom
matrices, slow?, all the matrices have to be children of an abstract class).
More information about the Numpy-discussion