Numeric - writing extentions

Fernando Pérez fperez528 at yahoo.com
Tue Jan 15 06:46:15 EST 2002


Jesper Olsen wrote:

> Today I downloaded and installed Numeric-20.3 from sourceforge
> - I installed it from source, and it seems to work ok (with python 2.1.1).
> 
> Now I want to write an extention where I use Numeric.array
> 

You may want to take a serious look at weave 
(http://www.scipy.org/site_content/weave). It may be the case that you do 
need a full blown extension, but chances are some inlined C with weave, 
either using blitz() or inline() with blitz type factories may do. And it's 
*vastly* simpler to use.

An example:

#-----------------------------------------------------------------------------
# Operating in-place in an existing Numeric array.
def in_place_mult(num,mat):
    """In-place multiplication of a matrix by a scalar.
    """
    nrow,ncol = mat.shape
    code = \
"""
for(int i=0;i<nrow;++i)
    for(int j=0;j<ncol;++j)
        mat(i,j) *= num;

"""
    weave.inline(code,['num','mat','nrow','ncol'],
                 type_factories = blitz_type_factories)


In the above, mat is a pre-allocated Numeric 2d matrix.

Or the following to compute a trace:

#-----------------------------------------------------------------------------
# Returning a quantity computed from a Numeric array.
def mtrace(mat):
    """Return the trace of a matrix.
    """
    nrow,ncol = mat.shape
    code = \
""" 
double tr=0.0;

for(int i=0;i<nrow;++i)
    tr += mat(i,i);
return_val = Py::new_reference_to(Py::Float(tr));
"""
    return weave.inline(code,['mat','nrow','ncol'],
                        type_factories = blitz_type_factories)


Note that these are simple test cases I wrote for learning, not meant to be 
production code. But they illustrate how trivially easy weave is to use. Full 
access to raw C speed right inside Python! (btw, I'm not a weave developer, 
just a happy amazed user, so I feel like I can cheer :)

HTH,

f.



More information about the Python-list mailing list