Last active
March 11, 2022 21:34
-
-
Save mikofski/ac30065073d0d32d6ea3569f6e24e5ec to your computer and use it in GitHub Desktop.
SciPy Cython Optimize Zeros API
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
from scipy.optimize.cython_optimize cimport brentq | |
# import math from Cython | |
from libc cimport math | |
ARGS = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments | |
XLO, XHI = 0.5, 1.0 # lower and upper search boundaries | |
XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters | |
# user defined struct for extra parameters | |
ctypedef struct test_params: | |
double C0 | |
double C1 | |
# user defined callback | |
cdef double f(double x, void *args): | |
cdef test_params *myargs = <test_params *> args | |
return myargs.C0 - math.exp(-(x - myargs.C1)) | |
# Cython wrapper function | |
cdef double brentq_wrapper_example(dict args, double xa, double xb, | |
double xtol, double rtol, int mitr): | |
# Cython automatically casts dictionary to struct | |
cdef test_params myargs = args | |
return brentq( | |
f, xa, xb, <test_params *> &myargs, xtol, rtol, mitr, NULL) | |
# Python function | |
def brentq_example(args=ARGS, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL, | |
mitr=MITR): | |
'''Calls Cython wrapper from Python.''' | |
return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr) | |
x = brentq_example() | |
# 0.6999942848231314 | |
from scipy.optimize.cython_optimize cimport zeros_full_output | |
# cython brentq solver with full output | |
cdef zeros_full_output brentq_full_output_wrapper_example( | |
dict args, double xa, double xb, double xtol, double rtol, | |
int mitr): | |
cdef test_params myargs = args | |
cdef zeros_full_output my_full_output # simplified output | |
# put result into full_output | |
brentq(f, xa, xb, &myargs, xtol, rtol, mitr, &my_full_output) | |
return my_full_output | |
# Python function | |
def brent_full_output_example(args=ARGS, xa=XLO, xb=XHI, xtol=XTOL, | |
rtol=RTOL, mitr=MITR): | |
'''Returns full output''' | |
return brentq_full_output_wrapper_example(args, xa, xb, xtol, rtol, | |
mitr) | |
result = brent_full_output_example() | |
# {'error_num': 0, | |
# 'funcalls': 6, | |
# 'iterations': 5, | |
# 'root': 0.6999942848231314} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment