Numeric slicing, iteration prob.

Duncan Smith buzzard at urubu.freeserve.co.uk
Tue Aug 6 02:00:23 CEST 2002


"Fernando Perez" <fperez528 at yahoo.com> wrote in message
news:aimtmj$mg2$1 at peabody.colorado.edu...

[snip]

>
> Can't think of a nicer one right now, but there probably is one. Maybe
build
> the necessary index structures and use take()? Don't know...
>

I considered take() for a while but it didn't look too nice (hope this is
not too technical ;-)).

The following is what I currently have to generate the appropriate slice
(self.values is a Numeric array),

def getSlice(index, axes):
    last_axis = 0
    s = 'self.values['
    for axis in axes:
        s += ':,'*(axis-last_axis-1) + str(index[axis]) + ','
        last_axis = axis

    return s + '...]'

>>> getSlice((2,3,5,6), [0,1,3])
'self.values[2,3,:,6,...]'

Seems to work OK, but I'm going to be calling this function many times and
any speed ups will be of practical benefit.  Maybe I can cache previous
slices in a dictionary or something.  Typically I might want the slices
'self.values[2,:,:,6,...]' and 'self.values[2,3,...]', then subsequently
'self.values[2,3,:,6,...]'.  Hmmm?

>
> > On a related note, does anyone have a feeling for the most efficient way
of
> > checking if all the values in a returned slice are zero? I can obviously
> > just iterate over the cells and break when I get a non-zero value, but
I'm
> > hoping there's some more efficient method available in Numeric. TIA.
>
> Look into alltrue:
>
>
> In [14]: import Numeric as N
>
> In [15]: N.alltrue ?
> Type:           function
> Base Class:     <type 'function'>
> String Form:    <function alltrue at 0x82e31f4>
> Namespace:      Currently not defined in user session.
> File:
> /usr/users/fperez/local/lib/python2.2/site-packages/Numeric/Numeric.py
> Definition:     N.alltrue(x, axis=0)
> Docstring:
>     Perform a logical_and over the given axis.
>
> That may help.

Cheers.  Actually it's 'sometrue()' that seems to do the job,

def f5(table):
    if Numeric.sometrue(Numeric.ravel(table)):
        return 0
    else:
        return 1

which is (on average) fractionally quicker than using,

if Numeric.add.reduce(Numeric.ravel(table)):

Cheers.

Duncan

>
> Cheers,
>
> f





More information about the Python-list mailing list