跳轉到內容

GLPK/條件約束

來自華夏公益教科書

取決於引數的約束

[編輯 | 編輯原始碼]

有時,約束只有在滿足可以用引數表達的條件時才有效。

以下不是合法的 GMPL

if (flag) {
    s.t. c : x <= 5;
} else {
    s.t. c : x <= 3;
}

但我們可以在 GMPL 中使用以下方式建模

/*
 * This model demonstrates how to let the existence of simple constraints
 * depend on a parameter.
 */

/* This flag controls if constraint c0 or contraint c1 is active */
param flag := 1;

var x;

maximize obj: x;

s.t. c0{i in {1} : flag == 0} : x <= 3;
s.t. c1{i in {1} : flag == 1} : x <= 5;

solve;

display x;

end;

對於索引條件,我們可以做同樣的事情

/*
 * This model demonstrates how to let the existence of indexed constraints
 * depend on a parameter.
 */

/* This flag controls if constraint c0 or contraint c1 is active */
param flag := 0;

set I := {1..3};
var x{I}, <= 10; 

maximize obj: sum{i in I} x[i];

s.t. c0{i in I : i < 3 && flag == 0} : x[i] <= 3;
s.t. c1{i in I : i > 1 && flag == 1} : x[i] <= 5;

solve;

display x;

end;

取決於二元變數的約束

[編輯 | 編輯原始碼]

如果約束的相關性取決於二元變數,我們可以使用 BigM 方法

/*
 * This model demonstrates how to let the relevance of indexed constraints
 * depend on a binary variable.
 */

/* Big M, chosen as small as possible */
param M := 7;

set I := {1..3};
var x{I}, <= 10; 

/* Binary variable controlling which constraint is active */
var y, binary;

maximize obj: sum{i in I} x[i];

s.t. c0{i in I : i < 2} : x[i] <= 3 + M * y;
s.t. c1{i in I : i > 1} : x[i] <= 5 + M * (1 - y); 

solve;

display x, y;

end;
華夏公益教科書