I am new in ampl and I want to use if condition in ampl with the following information:
I have a binary variable X[p,r], where {p in P, r in R}. Now I want to make a new constraint such that the variable R[p,r] is used where X[p,r]=0. I do not know how I can write it or even if the ampl can handle it or not, I tried the following constraint but they did not work:
s.t. a1{r in R, p in P and X[p,r]=0}:
s.t. a2{r in R p in P and X[p,r]=0};
s.t. a2{r in R ,p in P, and X[p,r]=0};
s.t. a2{r in R, p in P: and X[p,r]=0};
You cannot include a decision variable in the "for all" part of the constraint (in AMPL, the part inside the {...}
). Instead, you need build into the constraint itself the logic that says the constraint is only active if X[p,r] = 0
. The way to do that depends on the type of constraint: >=, =, or <=. I'll write each case separately, and I'll do it in a generic way instead of specific to your problem.
In the explanation below, I assume that the constraint is written as
a[1]y[1] + ... + a[n]y[n] >=/=/<= b,
where a[i]
and b
are constants and y[i]
are decision variables. I also assume we want the constraint to hold if x = 0
, where x
is a binary decision variable, and we don't care whether the constraint holds if x = 1
.
Let M
be a new parameter (constant) that equals a large number.
Greater-than-or-equal-to constraints:
The constraint is a[1]y[1] + ... + a[n]y[n] >= b
. Rewrite it as
a[1]y[1] + ... + a[n]y[n] >= b - Mx.
Then, if x = 0
, the constraint holds, and if x = 1
, it has no effect since the right-hand side is very negative.
(If all of the a[i]
are nonnegative, you can instead use
a[1]y[1] + ... + a[n]y[n] >= bx,
which is tighter.)
Less-than-or-equal-to constraints:
The constraint is a[1]y[1] + ... + a[n]y[n] <= b
. Rewrite it as
a[1]y[1] + ... + a[n]y[n] <= b + Mx.
Then, if x = 0
, the constraint holds, and if x = 1
, it has no effect since the RHS is very large.
Equality constraints:
The constraint is a[1]y[1] + ... + a[n]y[n] = b
. Rewrite it as
a[1]y[1] + ... + a[n]y[n] <= b + Mx
a[1]y[1] + ... + a[n]y[n] >= b - Mx.
Then, if x = 0
, the equality constraint holds, and if x = 1
, the constraints have no effect.
Note: If your model is relatively large, i.e., it takes a non-negligible amount of time to solve, then you need to be careful with big-M
-type formulations. In particular, you want M
to be as small as possible while still enforcing the logic of the constraints above.
来源:https://stackoverflow.com/questions/56025131/if-condition-in-ampl