[Numpy-discussion] fiddling the strides of an array

Tim Hochberg tim.hochberg at ieee.org
Mon Nov 20 17:45:54 CST 2006


Filip Wasilewski wrote:
> On 11/20/06, A. M. Archibald <peridot.faceted at gmail.com> wrote:
>   
>> On 20/11/06, Tim Hochberg <tim.hochberg at ieee.org> wrote:
>>
>>     
>>> I don't know how much help this will be, but, if the input array can be
>>> mapped into a contiguous array using transpose, which looks to be the
>>> case with at least one of the problematic cases you show here, you could
>>> transpose so as to get a contiguous array and grab the buffer from that.
>>> As for how to decide what transposes to do, while it sounds like a fun
>>> problem, I don't have time to delve into it right now.
>>>       
>> I thought about that, actually, all you'd have to do is argsort the
>> strides tuple. It still fails for arrays that are of the form a[::2],
>> though, and I'm still hoping to find the secret code to access
>> something I know numpy is perfectly capable of doing, so I don't
>> really want to add such a grotty hack.
>>     
>
>
> As a replacement for ndarray.__new__ you can use the array interface
> protocol, at least until someone will come up with a better solution.
> I tried your segment_axis (cut mode) with strided and axis swapped
> multidimensional arrays and I think it works quite. The fiddle part
> goes like this:
>
> class My(object):
>     def __init__(self, arr):
>         self.__array_interface__ = arr.__array_interface__
>         self.__array_interface__["strides"] = newstrides
>         self.__array_interface__ai["shape"] = newshape
> a = numpy.asarray(My(arr))
>
>   
Clever!

Two cautionary notes: first, you can crash the interpreter if you use 
bogus strides or shape, so be careful. Second, and perhaps a little less 
obvious, My(arr) needs to hold a reference to the array 'arr'. 
Otherwise, if arr goes away before 'a' does, 'a' will be left pointing 
to invalid data.

-tim




More information about the Numpy-discussion mailing list