[Numpy-discussion] Multidimensional neighbours

Sebastian Berg sebastian at sipsolutions.net
Thu Aug 16 14:38:00 EDT 2012


Hello,

Just to throw it in, if you do not mind useing scipy, you can use its
multidimensional correlate method instead:

stamp = np.ones((3,3,3))
stamp[1,1,1] = 0
num_neighbours = scipy.ndimage.correlate(x, stamp, mode='wrap'))

In the link np.roll is used to implement periodic boundaries
(mode='wrap' when using correlate), if you want constant boundary
conditions padding is probably simplest. Maybe someone else has some
trick to avoid so much code duplication without using scipy...

Regards,

Sebastian

On Do, 2012-08-16 at 18:46 +0100, Jose Gomez-Dans wrote:
> Hi,
> I've just come across Travis Oliphant's array version of the game of
> life here <https://gist.github.com/3353411>. It's a really nice
> example of how to efficiently find neighbours using numpy and family.
> However, I wanted to apply these ideas to higher order arrays (eg GRID
> being three dimensional rather than two dimensional). My previous
> attempts at this include the (sorry for the ensuing horror!)
>       neighbours = np.array( [ \
>             # Lower row...
>             x[:-2, :-2, :-2], x[:-2, :-2, 1:-1], x[:-2, :-2, 2: ], 
>             x[:-2, 1:-1,:-2], x[:-2, 1:-1, 1:-1], x[:-2, 1:-1, 2:], 
>             x[:-2, 2:,:-2], x[:-2, 2:, 1:-1], x[:-2, 2:, 2:], 
>             # Middle row
>             x[1:-1, :-2, :-2], x[1:-1, :-2, 1:-1], x[1:-1, :-2, 2: ], 
>             x[1:-1, 1:-1,:-2], x[1:-1, 1:-1, 2:], 
>             x[1:-1, 2:,:-2], x[1:-1, 2:, 1:-1], x[1:-1, 2:, 2:], 
>             # Top row
>             x[2:, :-2, :-2], x[2:, :-2, 1:-1], x[2:, :-2, 2: ], 
>             x[2:, 1:-1,:-2], x[2:, 1:-1, 1:-1], x[2:, 1:-1, 2:], 
>             x[2:, 2:,:-2], x[2:, 2:, 1:-1], x[2:, 2:, 2:] ] )
> 
> 
> I think this works (it's been a while! ;D), but it's a bit messy and
> the boundary condition is a bit crude. I was wondering whether there's
> some other nice way of doing it, like demonstrated in the above link.
> Also, what if you want to have a larger neighbourhood (say 5x5x2
> instead of 3x3x3)?
> 
> 
> While I appreciate these index tricks, I also find them quite mind
> boggling!
> Thanks!
> Jose
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion





More information about the NumPy-Discussion mailing list