I am trying to solve an optimization problem in Python environment using Scipy minimize. My problem is to apply the constraints that have if-else conditions in them. My input arguments are arrays and my objective function returns a scalar according to the three scalar variables I pick from the arrays and feed to the problem.
Here is my main problem - constraints that I have to write somehow:
# constraint 1
x_3 < x_1 + x_2
# constraint 2
if x_1 > x_2:
x_3 + x_2 > x_1
# constraint 3
if x_2 > x_1:
x_2 - x_3 < x_1
And here is the code that I come up with to solve my problem so far:
import numpy as np
from scipy import interpolate
from scipy.optimize import minimize
# My inputs are arrays as such
x_1 = np.linspace(0.9, 1.1, 21)
x_2 = np.linspace(0.7, 1, 31)
x_3 = np.linspace(0.8, 0.9, 11)
# Just to have a simplified problem here,
# I just made up this Obj_func. In reality, I have got
# some FEM running which returns me a scalar in return
# to the x_1, x_2, x_3 parameters I give from the arrays above.
# You can change this Obj_fun if it does not make sense as long as
# it gives a single scalar "y".
def Obj_func(x, x_1, x_2, x_3):
x_1, x_2, x_3 = x
y = x_1 + 5*x_2 - 2*x_3
return y
# I assume I can write my first constraint as such:
def ConstOne (args):
x_1 = args[0]
x_2 = args[1]
x_3 = args[2]
return x_1 + x_2 - x_3
constraints=({'type': 'ineq',
'fun': ConstOne})
# But I don't know how I can write the second and third constraints
# with if conditions
# initial guess
x0 = (1, 0.75, 0.85)
# input arrays entering to the optimization as arguments
args = (x_1, x_2, x_3)
# solve the optimization problem
print (minimize(Obj_func ,x0 , args, method='SLSQP', constraints=constraints))
I am open to any suggestions and solutions. Thank you!