|
| 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 | +} |
0 commit comments