[SciPy-User] Quick "grid" creation

Zachary Pincus zachary.pincus at yale.edu
Fri Aug 2 15:16:50 EDT 2013


On Aug 2, 2013, at 3:06 PM, Chris Weisiger wrote:

> You could use arange and then blow the array up using some scaling function, maybe? Google suggests the Kronecker product: http://stackoverflow.com/questions/7525214/how-to-scale-a-numpy-array
> http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html
> 
> a = numpy.arange(20*20).reshape(20, 20)
> b = numpy.kron(a, numpy.ones((100, 100))
> 
Oh using kron is a good tip!

Just for the record, you'd want:
b = numpy.kron(grid, numpy.ones((5,5)))

Also for the record, it turns out that kron is a bit faster than ndimage.zoom, but surprisingly not that much:
In: timeit numpy.kron(grid, numpy.ones((5,5)))
1000 loops, best of 3: 212 us per loop

In: timeit scipy.ndimage.zoom(grid, 5, order=0)
1000 loops, best of 3: 238 us per loop

And as the zoom-factor gets larger, zoom catches up... interesting:
In: timeit numpy.kron(grid, numpy.ones((50,50)))
10 loops, best of 3: 23.5 ms per loop

In: timeit scipy.ndimage.zoom(grid, 50, order=0)
10 loops, best of 3: 20.5 ms per loop

Zach


> -Chris
> 
> 
> On Fri, Aug 2, 2013 at 11:54 AM, Jose Gomez-Dans <jgomezdans at gmail.com> wrote:
> Hi,
> I'd like to quickly create a labelled grid to overlay on an array and use as labels (eg scipy.ndimage.sum takes a labels option to calculate statistics using a different array as a mask. My attempts to quickly produce said masks work, but are a bit embarrassing...
> 
> a = np.zeros((100, 100), dtype=np.int)
> cnt = 0
> for i in xrange(20):                    
>     for j in xrange(20):
>         cnt += 1
>         a[(i*5):((i+1)*5), (j*5):((j+1)*5)] = cnt
> 
> So the above works, but it quickly gets cumbersome with large arrays, and arrays where the ratio between how many cells in the finer array to the coarser array. Is there some "keys in hand" solution for this problem?
> 
> Thanks!
> Jose
> 
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
> 
> 
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user




More information about the SciPy-User mailing list