如何在GLPK中为我的变量写一个if条件?

Fig*_*gör 5 linear-programming glpk mathprog

这是我的完整问题:

在此输入图像描述

信息:

*最大.总投资:125美元

*支付是购买的单位x支付/单位的总和

*每次投资成本:购买成本+成本/单位x如果您购买至少一个单位的单位数量

*费用是每笔投资的总和

约束:

*您可能不会同时投资2和5.

*只有投资2和3中的至少一个,您才可以投资1.

*您必须至少投资3,4,5中的两个.

*您的投资额不得超过最大单位数.

问题:最大化利润:支付 - 成本

 xi: # of units i ? {1,2,3,4,5}
 yi=1 if xi>0 else yi=0
 cost = sum{i in I} buyInCost_i * yi + cost-unit_i*xi
 pay-off = sum{i in I} (pay-off/unit)_i*xi
 profit = pay-off - cost

 Maximize profit

 Subject to

 y2+y5 <= 1
 y1<= y2+y3
 y3+y4+y5 >= 2
 x1<=5, x2<=4, x3<=5, x4<=7, x5<=3
 cost<=125
Run Code Online (Sandbox Code Playgroud)

这是我的问题:

例如,我有这个二进制变量y

 yi=1 if xi>0 else yi=0  and i ? {1,2,3,4,5}
Run Code Online (Sandbox Code Playgroud)

我宣称我是一个数据集

 set I;

 data;

 set I := 1 2 3 4 5;
Run Code Online (Sandbox Code Playgroud)

我不知道如何在glpk中将if else条件添加到y变量中.你能帮帮我吗?

我的建模:

 set I;

 /*if x[i]>0 y[i]=1 else y[i]=0 ?????*/
 var y{i in I}, binary;

 param a{i in I};
 /* buy-in cost of investment i */

 param b{i in I};
 /* cost per unit of investment i */

 param c{i in I};
 /* pay-off per unit of investment i */

 param d{i in I};
 /* max number of units of investment i */

 var x{i in I} >=0;
 /* Number of units that is bought of investment i */

 var po := sum{i in I} c[i]*x[i];

 var cost := sum{i in I} a[i]*y[i] + b[i]*x[i];

 maximize profit: po-cost;

 s.t. c1: y[2]+y[5]<=1;
 s.t. c2: y[1]<y[2]+y[3];
 s.t. c3: y[3]+y[4]+y[5]>=2;
 s.t. c4: x[1]<=5 
     x[2]<=4
     x[3]<=5
     x[4]<=7
     x[5]<=3;

 s.t. c5: cost <=125;
 s.t. c6{i in I}: M * y[i] > x[i];   // if condition of y[i] 

 set I := 1 2 3 4 5;
 param a :=
1 25
2 35
3 28
4 20
5 40;

 param b :=
1 5
2 7
3 6
4 4
5 8;

 param c :=
1 15
2 25
3 17
4 13
5 18;

 param d :=
1 5
2 4
3 5
4 7
5 3;

 param M := 10000;
Run Code Online (Sandbox Code Playgroud)

我收到此语法错误:

      problem.mod:21: syntax error in variable statement 
      Context: ...I } ; param d { i in I } ; var x { i in I } >= 0 ; var po :=
      MathProg model processing error
Run Code Online (Sandbox Code Playgroud)

Nic*_*lle 10

你不能直接这样做(没有办法if在LP中"直接"写一个约束).

但是,有一些解决方法.例如,你可以写:

M * yi > xi
Run Code Online (Sandbox Code Playgroud)

where M是一个大常量(大于任何值xi).

这条路:

  • 如果xi > 0,那么约束等同于yi > 0,这是yi == 1因为yi是二进制(如果M足够大).
  • if xi == 0,那么约束总是被验证,并且yi将等于0你的目标随着你的目标而增加yi而你正在最小化.

在这两种情况下,约束都等同于if测试.