I am trying to optimize a function of two variables. I want one variable to be fixed at 50 and another be between -5 and 5. I wrote the following code:
x0 = np.array([50, 0.0])
res = minimize(error, x0, constraints=[
{'type': "eq", "fun": lambda x: x[0] - 50},
{'type': "ineq", "fun": lambda x: -abs(x[1]) + 5},
])
where minimize
is a function from scipy.optimize
.
The first constraint is x[0] == 50
and second one is -5 <= x[1] <= 5
.
I get the following response: message: 'Inequality constraints incompatible'
. But when I set the second variable to be not zero (e.g. x0 = np.array([50, 0.1])
) it finds a solution successfully. What can be the reason of such behavior?
The constraints need to be differentiable, and your second constraint is not. If you express the constraint in terms of x[1]**2
instead of abs(x[1])
, it should work. You could also eliminate the abs
by splitting the constraint into two separate constraints, one for the upper bound and one for the lower bound.