# [SciPy-user] 2D arrays in weave.inline

Alan Jackson alan@ajackson....
Sat Nov 17 15:30:10 CST 2007

```This is probably an astonishingly simple question, but I've been struggling for
some time with it.

I am trying to work with weave for the first time, and it is becoming clear that
I don't understand how 2D arrays get passed. The example below illustrates the problem I'm
having... the 2D indexing doesn't seem to be working right at all.

#!/usr/bin/env python

from numpy import array, zeros, abs, ones, arange, ravel, nan, empty, isnan, histogram, hstack, multiply, log, shape, triu
import scipy.weave as weave
from scipy.weave import converters

def Matrix(width, minval, maxval, exponent, type="HorseSaddle"):

halfSqrt2 = 0.707106781185
sin45 = halfSqrt2
cos45 = halfSqrt2
Matrix = zeros((width, width), dtype=float)
for j in range(0,width):
jScaled = j / (halfSqrt2 * (width-1))
jTranslated = jScaled - halfSqrt2
jsin45 = jTranslated * sin45
jcos45 = jsin45
for i in range(j,width):
iScaled = i / (halfSqrt2 * (width-1));
iTranslated = iScaled - halfSqrt2;
iRotated = iTranslated * cos45 + jsin45;
jRotated = - iTranslated * sin45 + jcos45;
iRotated = abs(iRotated);
jRotated = abs(jRotated);
Matrix[i, j] = round(maxval * iRotated**exponent + \
minval * jRotated**exponent, 2)
Matrix[j,i] = Matrix[i,j]

return Matrix

################################################################################
#   algorithm - WEAVE version
################################################################################

def Fast(s1, s2, wt1, wt2, M):

seq1 = s1[0]
seq2 = s2[0]
t1 = s1[1]
t2 = s2[1]

code = '''

for (unsigned int idx2 = 0; idx2 < 10; ++idx2) {

printf("\\n");
for (unsigned int idx1 = 0; idx1 < 10; ++idx1) {
printf("%6f  ", M[idx1, idx2]);

}// for whole s1
}// for whole s2
printf("\\n");
'''

weave.inline(code, ["seq1", "seq2", "t1", "t2", "M" ])

################################################################################
#		test section
################################################################################

if __name__ == '__main__' :
attr1  = array([1,2,2,3,2,4,3,5,4,3,3,  3,4,6,1,0,2,4,2,5,2,3])
attr2 = array([1,2,2,3,2,5,3,5,4,3,2,6, 3,4,6,1,0,1,4,2,5,2,3])
t = arange(1, len(attr1)+1, dtype=float)
wt1 = ones(len(attr1), dtype=float)
t2 = arange(1, len(attr2)+1, dtype=float)
wt2 = ones(len(attr2), dtype=float)

seq1 = [attr1, t]
seq2 = [attr2, t2]
M = Matrix(7,-10,10,2.)
print M
s1s2, s2s1 = Fast(seq1, seq2, wt1, wt2, M )

--
-----------------------------------------------------------------------
| Alan K. Jackson            | To see a World in a Grain of Sand      |
| alan@ajackson.org          | And a Heaven in a Wild Flower,         |
| www.ajackson.org           | Hold Infinity in the palm of your hand |
| Houston, Texas             | And Eternity in an hour. - Blake       |
-----------------------------------------------------------------------
```