Search code examples
pythonoptimizationscipyminimize

ValueError for SQLQP(scipy.optimize.minimize)


I'm trying to solve this problem in my book I've been studied but I can't solve this! Therefore I request the solution here. It would be huge pleasure if you help me :)

from scipy.optimize import minimize

def objective(x):
    x1 = x[0]
    x2 = x[1]
    x3 = x[2]
    x4 = x[3]
    return x1*x4*(x1+x2+x3)+x3

def constraint1(x):
    return x[0]*x[1]*x[2]*x[3]-25.0

def constraint2(x):
    sum_sq = 40
    for i in range(4):
        sum_sq = sum_sq - x[i]**2
    return sum_sq

x0 = [1, 5, 5, 1]

print(objective(x0))

b = (1, 0, 5, 0)
bnds = (b,b,b,b)
con1 = {'type':'ineq', 'fun':constraint1}
con2 = {'type':'ineq', 'fun':constraint2}
cons = [con1,con2]

sol = minimize(objective,x0,method='SLSQP',bounds=bnds,constraints=cons)

print(sol)

and Error revealed like this

ValueError                                Traceback (most recent call last)
Cell In[21], line 29
     26 con2 = {'type':'ineq', 'fun':constraint2}
     27 cons = [con1,con2]
---> 29 sol = minimize(objective,x0,method='SLSQP',bounds=bnds,constraints=cons)
     31 print(sol)
.
.
.
ValueError: too many values to unpack (expected 2)

it's the answer revealed in my book but, I can't get them even I tried few solutions in stack overflow

fun: 17.01401724549506
jac: array([14.572, 1.379, 2.379, 9.564])
message: 'Optimization terminated successfully.'
nfev: 30
nit: 5
njev: 5
status: 0
success: True
x: array([1., 4.743, 3.821, 1.379])

Solution

  • The bounds should be a list of (lo,up).

    So use:

    b = (1, 5)
    bnds = [b,b,b,b]
    

    Please read the documentation at https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html.