# [Numpy-discussion] Manipulate neighboring points in 2D array

Nicolas Rougier Nicolas.Rougier@inria...
Sun Dec 30 08:54:09 CST 2012

```
You might want to have a look at :

http://code.google.com/p/glumpy/source/browse/demos/gray-scott.py

which implements a Gray-Scott reaction-diffusion system.

The 'convolution_matrix(src, dst, kernel, toric)' build a sparse matrix such that multiplying an array with this matrix will result in the convolution. This is very fast if your kernel is small (like for cellular automata) and if you intend to repeat the convolution several times. Note that you only need to build the matrix once.

Example:

>>> S = np.ones((3,3))
>>> K = np.ones((3,3))
>>> M = convolution_matrix(S,S,K,True)
>> print (M*S.ravel()).reshape(S.shape)
[[ 9.  9.  9.]
[ 9.  9.  9.]
[ 9.  9.  9.]]
>>> M = convolution_matrix(S,S,K,False)
>>> print (M*S.ravel()).reshape(S.shape)
[[ 4.  6.  4.]
[ 6.  9.  6.]
[ 4.  6.  4.]]

the 'dst' parameter won't be useful in your case so you have to set it to 'src'.

Nicolas

On Dec 30, 2012, at 12:21 , deb wrote:

> Thanks Zach for your interest
>
> I was thinking about ndimage.generic_filter when I wrote about generic filter.
> For generic_filter I used trivial function that returns .sum() but I can't seem to make the code any faster than it is.
>
> This is the code: http://code.activestate.com/recipes/578390-snowflake-simulation-using-reiter-cellular-automat/
> As commenter suggested I thought to try and make it in numpy
>
> Interestingly, the first thing I tried before trying to use numpy was change range() loops with xrange(), as xrange is considered faster and more efficient, but result was that code was twice slower.
>
> Anyway I give up, and concluded that my numpy skills are far below I expected :D
>
>
>> It's possible that some generic filter operations can be cast in
>> terms of pure-numpy operations, or composed out of existing filters
>> available in scipy.ndimage. If you can describe the filter operation
>> you wish to perform, perhaps someone can make some suggestions.
>
>> Alternately, scipy.ndimage.generic_filter can take an arbitrary
>> python function. Though it's not really fast...
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion

```

More information about the NumPy-Discussion mailing list