I am using dlib
's find_min_global
function, an optimization algorithm which helps to find values which minimize the output of a function. For example
import dlib
def holder_table(x0,x1):
return -abs(sin(x0)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))
x,y = dlib.find_min_global(holder_table,
[-10,-10], # Lower bound constraints on x0 and x1 respectively
[10,10], # Upper bound constraints on x0 and x1 respectively
80) # The number of times find_min_global() will call holder_table()
Here the holder_table
function returns the value that needs to be minimized for different values of x0
and x1
.
Here the holder_table
function takes in only the values that need to be optimized that is x0
and x1
. But the function that I want to use with the dlib
function takes more than x0
and x1
. The function definiton looks like so
def holder_table(a,b,x0,x1):
return -abs(sin(b*x0/a)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))
The values a, b
are not fixed and are the outputs of another function. Now, I can directly call the function the returns a, b
inside the holder_table
but I dont want to end up re-calculating them because each time holder_table
is called a, b
gets re-calculated and the process is time consuming.
How do I pass a, b
to the holder_table
function?
Your question is not 100% clear but it looks like you want a partial application. In Python this can be done using the dedicated functools.partial
object, or quite simply with a closure (using either an inner function or lambda)
def holder_table(a,b,x0,x1):
return -abs(sin(b*x0/a)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))
def main():
a, b = some_heavy_function(...)
holder_table_partial = lambda ax, ay: holder_table(a, b, ax, ay)
x, y = dlib.find_min_global(
holder_table_partial, [-10,-10], [10,10], 80
)