Created
August 13, 2012 19:51
-
-
Save dfm/3343607 to your computer and use it in GitHub Desktop.
ctypes chi2 example by @jrwren
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double chi2(double m, double b, double *x, double *y, double *yerr, int N) { | |
int n; | |
double result = 0.0, diff; | |
for (n = 0; n < N; n++) { | |
diff = (y[n] - (m * x[n] + b)) / yerr[n]; | |
result += diff * diff; | |
} | |
return result; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from ctypes import * | |
libchi2 = cdll.LoadLibrary("libchi2.so.1.0.0") | |
ThreeDoubles = c_double * 3 | |
m = c_double(2.0) | |
b = c_double(1.0) | |
x = ThreeDoubles( -1.0, 4.2, 30.6) | |
y = ThreeDoubles( -1.5, 8.0, 63.0) | |
y_err = ThreeDoubles( 1.0, 1.5, 0.6) | |
libchi2.chi2.restype = c_double | |
result = libchi2.chi2(m, b, x, y, y_err, 3) | |
print result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
libchi2.so: chi2.o | |
gcc -shared -Wl,-soname,libchi2.so.1 -o libchi2.so.1.0.0 chi2.o -lc | |
chi2.o: chi2.c | |
gcc -fPIC -g -c -Wall chi2.c |
I made a version which uses the numpy.ctypes extensions which will work with arbitrarily long input/output vectors:
https://gist.github.com/3313315
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks man, this is great. I loved your post and it made me look into ctypes which I'd been meaning to do.