Getting Cython to work on OSX10.5 with Python 2.5

I’m trying out Cython to see if it the answer for making fast nbody systems with python. What follows is code for computing the covariance of two vectors. This is not optimised cython, it’s purely my first attempt at getting a cython program to compile and run. I recommend The Cython Numpy tutorial as a nice place to start.

Did I mention installation? Just download and then run setup.py, I didn’t need to do anything special.

#covar.pyx#
import numpy as np
def cov(a,b):
    # Computes the covariance between the n element vectors a and b
    # c is the output array indexed by x,y
    if len(a.shape) != 1:
        raise ValueError("Array must be one dimensional.")
    if a.shape != b.shape:
        raise ValueError("arrays must be the same shape")
    n = a.shape[0]
    c = 0
    # Perform the calculation
    for i in range(n):
        c += (a[i]-np.mean(a[:]) ) * (b[i] - np.mean(b[:]) )/n
    return c
#test_covar.py#
""" Covariance with Cython.
"""
import numpy as np        
import covar              
n = 50
a = length*np.random.random((n))  
b = length*np.random.random((n)) 
print "Covariance of two numpy random vectors",covar.cov(a,b)
print "Covariance of a vector with itself.",covar.cov(a,a)
print "Covariance of a vector with its sine.",covar.cov(a,np.sin(a))

And the build script. I got frustrated trying to figure out the compiler flags, and ended up using distutils to do it for me. I will post a cython nbody system soon which will use disutils to compile.

build_covar.sh
#!/bin/ksh
# TRANSLATE
cython -a covar.pyx
# COMPILE
gcc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c covar.c -o covar.o
gcc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle -undefined dynamic_lookup covar.o -o covar.so
# TEST
python test_covar.py

Enjoy.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: