22

I am using the scipy.optimize module to find optimal input weights that would minimize my output. From the examples I've seen, we define the constraint with a one-sided equation; then we create a variable that's of the type 'inequality'. My question is how does the optimization package know whether the sum of the variables in my constraint need to be smaller than 1 or larger than 1?

...

def constraint1(x):
    return x[0]+x[1]+x[2]+x[3]-1

....

con1 = {'type': 'ineq', 'fun': constraint1}

link to full solution I'm using in my example: http://apmonitor.com/che263/index.php/Main/PythonOptimization

Nick ODell
  • 15,465
  • 3
  • 32
  • 66
trystuff
  • 686
  • 1
  • 8
  • 18
  • 6
    [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) says "Equality constraint means that the constraint function result is to be zero whereas **inequality means that it is to be non-negative**." – endolith Aug 25 '17 at 18:51

1 Answers1

37

Refer to https://docs.scipy.org/doc/scipy-0.18.1/reference/tutorial/optimize.html and scroll down to Constrained minimization of multivariate scalar functions (minimize), you can find that

This algorithm allows to deal with constrained minimization problems of the form:

enter image description here

where the inequalities are of the form C_j(x) >= 0.

So when you define the constraint as

def constraint1(x):
    return x[0]+x[1]+x[2]+x[3]-1

and specify the type of the constraint as

con1 = {'type': 'ineq', 'fun': constraint1}

it automatically assumes that the constraint is in the standard form x[0]+x[1]+x[2]+x[3]-1>=0 i.e., x[0]+x[1]+x[2]+x[3]>=1

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
  • 1
    Just as a remark, I was searching for `x[0]+x[1]+x[2]+x[3]<10` and this works through simple bringing 10 to the left then multiply it all with -1. In any case, try to get the the standard form and then adjust as necessary. – Guenter Sep 08 '21 at 07:57