I want to use the sum of a series of linear expressions as objective and constraints. These linear expressions are chosen to be included or not based on some conditions. I can achieve it in Excel Solver but don't know how to code it in python.

I've seen a solution of adding conditional constraints here but it couldn't take the sum of all the needed expressions before binding a limit.

Here is the model to be solved.


$x_0\ge0,\ x_1\ge0,\ x_2\ge0,\ x_3\ge0 $

There are $n$ linear expressions:

$f_i(x_0,x_1,x_2,x_3) = a_{i0}x_0 + a_{i1}x_1 + a_{i2}x_2 + a_{i3}x_3 + b_i\quad (i=0,1,\dots,n)$

Objective: to minimize the objective function below

$ objective = 0\\ for\ i\ in\ range(n): \\ \quad if\ f_i(x_0,x_1,x_2,x_3)\ge0:\\ \quad\quad objective\ = objective\ + f_i(x_0,x_1,x_2,x_3)\\ $

Constraints: sum $\ge$ -5000

$ sum=0\\ for\ i\ in\ range(n): \\ \quad if\ f_i(x_0,x_1,x_2,x_3)\lt0:\\ \quad\quad sum\ = sum\ + f_i(x_0,x_1,x_2,x_3)\\ $


1 Answer 1


To minimize $\sum_i \max(f_i,0)$, introduce a nonnegative variable $y_i$ and minimize $\sum_i y_i$ subject to $y_i\ge f_i$.

To enforce $\sum_i \min(f_i,0)\ge -5000$, introduce a nonpositive variable $z_i$ and impose $\sum_i z_i\ge -5000$ subject to $z_i\le f_i$.

SAS (disclaimer: I work at SAS) can automatically linearize your problem as follows:

   var X {0..3} >= 0;
   impvar F {i in 0..n} = sum {j in 0..3} a[i,j]*X[j] + b[i];
   min MyObj = sum {i in 0..n} max(F[i],0);
   con MyCon: sum {i in 0..n} min(F[i],0) >= -5000;
   solve linearize;
  • $\begingroup$ Thank you so much!! I've built the model as you instructed, and it runs successfully. It's my first time to ask a question on this platform, never expect it's so helpful. I will then spend some time trying to figure out the logic of transforming a model in this way. Thanks again. $\endgroup$
    – Shwing
    Commented Jun 19 at 6:47
  • $\begingroup$ By the way, could you recommend some learning materials to better understand the way you transform the objective and constraints here? Thanks in advance. $\endgroup$
    – Shwing
    Commented Jun 19 at 7:01
  • $\begingroup$ I added a link to my answer. You can also find many more examples here: or.stackexchange.com/questions/tagged/linearization $\endgroup$
    – RobPratt
    Commented Jun 19 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.