Search code examples
python-3.xoptimizationscipyscipy-optimizescipy-optimize-minimize

callback function throws a error in scipy.optimize.minimize class


I am using scipy.minimize for an optimization problem.

This is my code


import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds

#bounds = Bounds([25, 36], [26, 38],[10,27],[6,28],[0,1800],[0,800],[0,100],[25,60],[2,7])

bounds = Bounds([20,6,20,23],[35,9,50,26])

energy_history = []
x_values = []

def objective(x):
    return (-0.20859863*x[0:1] -1.5088649*x[1:2] +0.10707853*x[2:3] +1.6829923*x[3:4] -0.008870916*x[0:1]*x[1:2] + 0.0007393111*x[0:1]*x[2:3] +0.010610705*x[0:1]*x[3:4] + 0.005123541*x[1:2]*x[2:3] +  0.086458616*x[1:2]*x[3:4] -0.007695199*x[2:3]*x[3:4] + 0.00016993227*x[0:1]*x[0:1] -0.026582083*x[1:2]*x[1:2]  + 0.00014467833*x[2:3]*x[2:3] -0.051599417*x[3:4]*x[3:4] - 9.540932)

def callback(x):
    fobj = objective(x)
    x_values.append(x)
    energy_history.append(fobj)


x0 = np.array([34,8,49,25])
res = minimize(objective, x0, method='trust-constr',
               options={'verbose': 1}, bounds=bounds,callback=callback)



optimal_values= res.x

print('optimal values found: ' + str(res.x))
print('energy consumed: ' + str(res.fun))

I get an error when I run this.

Error is with the callback function, it says

TypeError: callback() takes 1 positional argument but 2 were given

Where am I going wrong?


Solution

  • According to the docs, the callback-function signature depends on the solver chosen. (Which is not very nice.)

    While it's callback(x) for all others, in your case it's callback(x, status) as you are using method='trust-constr'.

    Just add this additional parameter to yours (and ignore it if you don't have use for the status-information).