0

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?

Bakhanov A.
  • 146
  • 1
  • 7
  • I'm pretty sure the constraints have to be differentiable. Have you tried expressing the `x[1]` constraint in terms of `x[1]**2` instead of `abs(x[1])`? – user2357112 May 02 '20 at 22:13
  • @user2357112supportsMonica Wow! Thank you! It worked. Write it as an answer if you want – Bakhanov A. May 02 '20 at 22:15
  • Just a quick note, if you fix a variable's value then it is no longer a variable but a constant & a known so doesn't need 'optimizing' – DrBwts May 03 '20 at 09:58

1 Answers1

1

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • By the way the second option does not work. Initially I created two constraints and I got the same error message as I got with abs function. – Bakhanov A. May 02 '20 at 22:26