Skip to content

Commit da97cc6

Browse files
committed
add an example for scipy
Signed-off-by: Jade Abraham <[email protected]>
1 parent 9b749ef commit da97cc6

File tree

7 files changed

+65
-0
lines changed

7 files changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../CLEANFILES
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../COMPOPTS
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../EXECENV
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use Python;
2+
3+
var interp = new Interpreter();
4+
5+
var sp = interp.importModule("scipy");
6+
var spi = interp.importModule("scipy.integrate");
7+
8+
// integrate a Python Function using scipy.integrate.quad
9+
proc integrate(f: owned Function, a: real, b: real): real {
10+
return spi.call("quad", f, a, b).call(real, "__getitem__", 0);
11+
}
12+
13+
{
14+
writeln("Integrating x**3, defined in Python");
15+
var f = interp.compileLambda("lambda x,: x**3");
16+
writeln(integrate(f, 0.0, 2.0));
17+
writeln(integrate(f, 0.0, 4.0));
18+
writeln(integrate(f, 0.0, 8.0));
19+
}
20+
21+
22+
// integrate a Chapel Function using scipy.integrate.quad
23+
proc integrate(f:proc(_: real):real, a: real, b: real): real {
24+
use CTypes;
25+
// get a c_ptr to a Chapel proc
26+
var f_ptr = c_ptrTo(f):c_ptr(void);
27+
28+
// create a ctypes object from the function pointer
29+
// another way to do this would be to support the pycapsule api in some form
30+
var ctypes = interp.importModule("ctypes");
31+
var ctypes_double = ctypes.get("c_double");
32+
var cfunctype = ctypes.call("CFUNCTYPE", ctypes_double, ctypes_double);
33+
var f_ptrPy = cfunctype(f_ptr:c_intptr);
34+
35+
// using the python representation of the function pointer,
36+
// create a LowLevelCallable for scipy usage
37+
var fPy = sp.call("LowLevelCallable", f_ptrPy,
38+
kwargs=["signature"=>"double (double)"]);
39+
40+
return spi.call("quad", fPy, a, b).call(real, "__getitem__", 0);
41+
}
42+
43+
{
44+
writeln("Integrating x**3, defined in Chapel");
45+
export proc f(x: real): real do return x;
46+
writeln(integrate(f, 0.0, 2.0));
47+
writeln(integrate(f, 0.0, 4.0));
48+
writeln(integrate(f, 0.0, 8.0));
49+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
4.0
2+
64.0
3+
1024.0
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/usr/bin/env bash
2+
3+
# skip valgrind testing: if CHPL_TEST_VGRND_EXE is set and 'on'
4+
if [ -n "$CHPL_TEST_VGRND_EXE" ] && [ "$CHPL_TEST_VGRND_EXE" == "on" ]; then
5+
echo "True"
6+
exit 0
7+
fi
8+
9+
FILE_DIR=$(cd $(dirname ${BASH_SOURCE[0]}) ; pwd)
10+
$FILE_DIR/../../skipIfAndInstallPackage.sh $FILE_DIR scipy

test/library/packages/Python/examples/scipy/python_libs.notest

Whitespace-only changes.

0 commit comments

Comments
 (0)