[SciPy-user] Re: weave and access to Numeric arrays

Fernando Perez fperez at pizero.colorado.edu
Mon Jul 22 21:55:15 CDT 2002


Final followup. Here's a modified version of your code with some extra 
comments which may be useful for others in this situation. Now I see how nice 
some of the type handling magic that weave does is!

#!/usr/bin/env python
import Numeric as N
from scipy import weave

def sumC(x):
    """Return the sum of the elements of a 1-d array.
    
    An example of how weave accesses a Numeric array without blitz.  """

    num_types = {N.Float:'double',
                 N.Float32:'float'}
    x_type = num_types[x.typecode()]
    
    code = """
           double result=0.0;
           double element;

           for (int i = 0; i < _Nx[0]; i++){

               // Note the type of the pointer below is computed in python
               //element = *(%s *)(x->data+i*x->strides[0]);

               // Weave's magic does the above for us:
               element = x_data[i];
               
               result += element;
               cout << "Element " << i << " = " << element << "\n";
           }
           cout << "size x " << _Nx[0] << "\n";    

           return_val = Py::new_reference_to(Py::Float(result));
           """ % x_type;

    return weave.inline(code,['x'],verbose=0)



x = N.ones(5,typecode=N.Float32)
y = N.array([4.3,1.5,5.6],typecode=N.Float)
z = N.array([4.3,1.5,5.6],typecode=N.Float32)

print x
print sumC(x)
print
print y
print sumC(y)
print
print z
print sumC(z)

#---------------------------------------------------------------------------


I've posted an updated version of my weave examples with this at:

http://www-hep.colorado.edu/~fperez/python/python-c/weave_examples.html

http://www-hep.colorado.edu/~fperez/python/python-c/weave_examples.py

One is color highlighted, the other pure text for python use.

Again, thanks a lot Eric.

Cheers,

f.




More information about the SciPy-user mailing list