hi im trying to minimize a simple 3 variable function with some range costraints in the x variables .. but im getting 'Inequality constraints incompatible - any idea ? thanks !!
from scipy.optimize import minimize
def f(x):
return (int(558*x[0]*x[1]*x[2])-(x[2]*(558-int(558*x[0])))-(x[2]*558))
x0 = [0.4, 1.0, 2.0]
#real data Ranges
#x[0] 0..1
#x[1] 1..3
#x[2] 5..50
cons=(
{'type': 'ineq','fun': lambda x: x[0]},
{'type': 'ineq','fun': lambda x: 1-x[0]},
{'type': 'ineq','fun': lambda x: x[1]-1},
{'type': 'ineq','fun': lambda x: 3-x[1]},
{'type': 'ineq','fun': lambda x: x[2]-5},
{'type': 'ineq','fun': lambda x: 50-x[2]}
)
res = minimize(f, x0, constraints=cons)
print(res)
full result is
fun: -33490.99993615066
jac: array([ 6.7108864e+07, 6.7108864e+07, -8.9300000e+02])
message: 'Inequality constraints incompatible'
nfev: 8
nit: 2
njev: 2
status: 4
success: False
x: array([ 0.4 , 1. , 49.99999993])
Hello I suspect that the problem comes from the numerical method used.
By default with constraints, minimize
use Sequential Least Squares Programming (SLSQP) which is a gradient method. Therefore the function to be minimized has to be regular, but given your use of int
it is not.
Using the alternative method: Constrained Optimization BY Linear Approximation (COBYLA) which is of a different nature I get the following
from scipy.optimize import minimize
def f(x):
return (int(558*x[0]*x[1]*x[2])-(x[2]*(558-int(558*x[0])))-(x[2]*558))
x0 = [0.4, 1.0, 2.0]
#real data Ranges
#x[0] 0..1
#x[1] 1..3
#x[2] 5..50
cons=(
{'type': 'ineq','fun': lambda x: x[0]},
{'type': 'ineq','fun': lambda x: 1-x[0]},
{'type': 'ineq','fun': lambda x: x[1]-1},
{'type': 'ineq','fun': lambda x: 3-x[1]},
{'type': 'ineq','fun': lambda x: x[2]-5},
{'type': 'ineq','fun': lambda x: 50-x[2]}
)
res = minimize(f, x0, constraints=cons, method="cobyla")
print(res)
with the display
fun: -55800.0
maxcv: 7.395570986446986e-32
message: 'Optimization terminated successfully.'
nfev: 82
status: 1
success: True
x: array([-7.39557099e-32, 1.93750000e+00, 5.00000000e+01])