Few issues with the script:
In defining objective -
return sign*(sum(x1+x2+x3+x4+x5+x6))
Can't use sum function and "+" sign together.
In defining constraints :
Need to define constraints types in addition to constraint functions.
constraint function:
def constraint1(x):
return 5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5])
def constraint2(x):
return 6000-(x[2]+x[3]+0.922*x[4]+0.619*x[5])
def constraint3(x):
return 6450-(x[3]+0.969*x[4]+0.777*x[5])
Constraint Type (Missing):
(Assuming all 3 constraints are inequalities)
cons1 = {'type': 'ineq', 'fun': constraint1}
cons2 = {'type': 'ineq', 'fun': constraint2}
cons3 = {'type': 'ineq', 'fun': constraint3}
cons=[cons1,cons2,cons3]
Above will define your constraints as
5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5]) >= 0
Final code with few minor improvements:
import numpy as np
from scipy.optimize import minimize
# this is my objective function
def objective(x, sign = -1.0):
x1=x[0]
x2=x[1]
x3=x[2]
x4=x[3]
x5=x[4]
x6=x[5]
return sign*sum((x1,x2,x3,x4,x5,x6)) # to get maximum by using '-1' sign
def constraint1(x):
return 5900-(x[0]+x[1]+0.949*x[2]+0.933*x[3]+0.824*x[4]+0.519*x[5])
def constraint2(x):
return 6000-(x[2]+x[3]+0.922*x[4]+0.619*x[5])
def constraint3(x):
return 6450-(x[3]+0.969*x[4]+0.777*x[5])
b1=(0,600)
b2=(0,475)
b3=(0,450)
b4=(0,500)
b5=(0,825)
b6=(0,6800)
bnds=(b1,b2,b3,b4,b5,b6)
cons1 = {'type': 'ineq', 'fun': constraint1}
cons2 = {'type': 'ineq', 'fun': constraint2}
cons3 = {'type': 'ineq', 'fun': constraint3}
cons=[cons1,cons2,cons3]
x0=[1,1,1,1,1,1]
result =minimize(objective,x0, method='SLSQP',bounds=bnds,constraints=cons,options={'maxiter': 10000, 'maxfev': None, 'disp': True, 'adaptive': True})
if result.success:
fitted_x = result.x
print(fitted_x)
else:
raise ValueError(result.message)
Result:
Optimization terminated successfully. (Exit mode 0)
Current function value: -9363.537325000863
Iterations: 32
Function evaluations: 248
Gradient evaluations: 31
[ 503.10524364 418.45708136 450. 366.975 825.
6800. ]