Python Scipy optimize does not respect constraints

133 Views Asked by At

Using Python scipy function Optimize/Minimize, constraint is not respected despite the optimization finishing as "Optimization terminated successfully".

from scipy.optimize import minimize

def obj_fun(x):
   # I do here calculations depending on x and put the result in r
   fr = f1(x)
   pr = f2(x)
   r = abs((fr/pr)-1)
   print(r)
   return r


constr = {'type':'ineq', 'fun': lambda x: obj_fun(x)-0.01}
res = minimize(obj_fun,(0,0,0,0,0), constraints=constr, method='SLSQP')

And it returns:

7.41234e-05
7.41256e-05
...
...
7.4567e-05

fun: 7.4567e-05
...
message: 'Optimization terminated successfully.'
nfev: 161
nfit:19
njev:15
status:0
success: True
x: array([6.5, 6.5, 3.5, 3.6, 3.5])

As you can see, I printed the value inside the objective function just to confirm what is calculated. And all the values are much smaller than 0.01 until it stops but still gives a "success" status somehow...

Tried different solvers and different ways to write the constraints but my understanding is that the constraints should mean: (obj_fun(x) - 0.01) > 0 but clearly the optimization answer is much smaller than 0.01.

0

There are 0 best solutions below