Conditionals

advertisement
Conditionals
Frequently GAMS modelers need to be able to write expressions that operate over less than full
sets or incorporate various model features conditionally depending on data. Such tasks are
accomplished in GAMS using conditionals.
Basic forms of conditionals........................................................................................................ 2
$ conditionals......................................................................................................................... 2
Ways $ conditionals are employed ................................................................................... 3
Controlling indices in sums etc .................................................................................... 3
Suppressing calculation of a result (left hand side)...................................................... 4
Suppressing model equations (left hand side).............................................................. 4
Suppressing terms in equations (right hand side)......................................................... 5
Conditionally displaying information .......................................................................... 6
Terminating a program................................................................................................. 6
Abort........................................................................................................................ 6
Conditional placement and program execution speed ...................................................... 7
If............................................................................................................................................. 7
Else.................................................................................................................................... 7
Elseif ................................................................................................................................. 7
While ..................................................................................................................................... 7
Repeat .................................................................................................................................... 8
Forms of logical / true false statements...................................................................................... 8
Numerical comparisons ......................................................................................................... 8
Eq ...................................................................................................................................... 8
= ........................................................................................................................................ 8
Ne...................................................................................................................................... 8
<> ...................................................................................................................................... 8
Gt....................................................................................................................................... 9
> ........................................................................................................................................ 9
Lt ....................................................................................................................................... 9
< ........................................................................................................................................ 9
Ge...................................................................................................................................... 9
>= ...................................................................................................................................... 9
Le .................................................................................................................................... 10
<= .................................................................................................................................... 10
Eqv .................................................................................................................................. 10
<=>.................................................................................................................................. 10
Imp .................................................................................................................................. 10
-> ..................................................................................................................................... 10
Data existence...................................................................................................................... 11
Existence/nonzero data item or result ............................................................................. 11
Computation over a set ................................................................................................... 12
Set comparisons................................................................................................................... 12
Element position ............................................................................................................. 13
Ord.............................................................................................................................. 13
Card ............................................................................................................................ 13
Element text comparison................................................................................................. 13
Sameas........................................................................................................................ 13
Diag ............................................................................................................................ 13
Subset or tuple membership............................................................................................ 14
Acronym comparisons......................................................................................................... 15
Nesting logical conditions........................................................................................................ 15
Nesting operators................................................................................................................. 15
And.................................................................................................................................. 16
Or .................................................................................................................................... 16
Xor .................................................................................................................................. 17
Not................................................................................................................................... 17
Nested conditionals.............................................................................................................. 18
Complex $ conditions ..................................................................................................... 18
Cautions about nested operators and precedence order .................................................. 18
Precedence order ........................................................................................................ 18
Note of caution ........................................................................................................... 19
The conditional alternative – the tuple..................................................................................... 20
Alphabetic list of features ........................................................................................................ 21
Basic forms of conditionals
There are four types of run time conditionals (for compile time conditionals see the Conditional
Compile chapter).
The GAMS $ condition
The If statement
The While statement
The Repeat statement
Each is covered below.
$ conditionals
A $ condition is placed in GAMS calculations and causes an action to occur if the conditional is
true. The basic $ conditional form is
term$logical condition
which says do something with term if the logical condition is true. The forms of logical
conditions are reviewed below. For now I will use a conditional that a named item be nonzero
for illustration
X$(y gt 0) = 10;
In this case the conditional says set X=10 if the scalar y is greater than zero.
Ways $ conditionals are employed
$conditionals appear in a number of ways in models. Fundamentally, they are used to:
Restrict the elements of a set that are referenced in an expression so that less than the full
set of elements enters into the calculation.
Restrict whether calculations are done.
Restrict whether terms are included.
Restrict whether equations are defined in a model.
Controlling indices in sums etc
$conditionals are frequently used to restrict the elements of a set that will be explicitly entered
into a calculation or process considered so that only a selected subset of the elements are added
into a sum or otherwise enter the calculation. The selection is controlled by the logical condition.
Generally this involves building a logical condition, which incorporates set element dependent
terms. The general format is
sum(namedset$logical condition,
term usually dependent on namedset)
where instead of sum I could also use any other set operator like smin, smax or loop.
Examples
(conditional.gms)
X=sum(I$(q(i) gt 0),a(i));
Loop((I,j)$(cost(I,j) gt 0),
X=x+cost(I,j));
X=smin(I$(q(i) gt 0),q(i));
X=sum(I$(q(i) gt 0),1));
All include the Ith case in the sum or loop or smin only if the logical condition is true. In the first
and last two cases, element I will be considered only if the data from the q parameter associated
with set element I is positive.
Notes
The general form is that the set operator appears then the target set(s) is identified and
then a $ appears followed by a logical condition then a term to be included in the
calculation which is usually dependent on the target set(s)).
The $ only allows a term associated with an element of the set to be added into the
calculation if the logical condition is true.
Many other logical condition forms are possible as explained below.
Suppressing calculation of a result (left hand side)
$conditionals can appear in a model to restrict whether calculations are done. The general
format for such a case is
namedparameter$logical condition=term;
and specifies that the namedparameter is set equal to the term only if the logical condition is true.
Examples
(conditional.gms)
X$(qq gt 0)=3;
qq $(sum(I,q(i)) gt 0)=4;
Q(i)$(a(i) gt 0) = -a(i);
a(i) $(abs(a(i)) gt 0) = q(i)/a(i);
qq $ (sum(i,abs(a(i))) gt 0)=1/sum(i,a(i));
All say implement this replacement statement for this parameter only if the logical condition is
true. Thus above if X started with a value of 7 and qq was negative causing a false evaluation of
the logical condition then X would finish the above statements with a value of 7. On the other
hand, if qq was positive then X would finish the above statements with a value of 3.
Notes
In these cases the namedparameter value will be altered only if the logical condition is
true. Otherwise, if the logical condition is false, the value of the item namedparameter
will be whatever it’s original value was (or the default value of zero).
This is known in GAMS terminology as a conditional on the left hand side.
Many other logical condition forms are possible as explained below.
The second case contains a common trick where a computation is done based on a count
of elements passing a logical condition.
The fourth and fifth assignments contain a common procedure where a division is done
only if the denominator is non-zero.
When the $ is on the left hand side, the equation is only computed if the logical condition
is true potentially making the program faster.
Suppressing model equations (left hand side)
$conditionals can be used to restrict whether model equations are present in a model. The
general format for such a case is
equation name$logical condition..
equation specification;
and specifies that the named equation is defined as that given in the equation specification only if
the logical condition is true.
Examples
(conditional.gms)
..
xvar=e=3;
Eq1$(qq gt 0)
..
Eq2$(sum(I,q(i)) gt 0)
..
Eq3(i)$(a(i) gt 0)
yvar=l=4;
ivar(i)=g= -a(i);
All say define this equation only if the logical condition is true.
Notes
In these cases, the whole named equation (see the Eq1 case above) or cases thereof when
defined over a set (see the Eq3 case above) will be entered into the model only if the
logical condition is true.
This is known in GAMS terminology as a conditional on the left hand side of an
equation specification.
Many other logical condition forms are possible as explained below.
When the $ is on the left hand side the equation is only computed if the logical condition
is true potentially making the program faster
Suppressing terms in equations (right hand side)
$ conditionals can appear in a model to restrict whether terms are included in a replacement
statement or equations. The general format for such a case is
term$logical condition
and specifies that the term is present only if the logical condition is true.
Examples
(conditional.gms)
..
Eq4
xvar+yvar$(qq gt 0)=e=3;
X=sum(I,q(i))$(qq gt 0)+4;
Q(i)=a(i)+1$(a(i) gt 0);
All say include this term only if the logical condition is true.
Notes
In these cases the term or case thereof when defined over a set will be included only if the
logical condition is true.
This is known in GAMS terminology as a conditional on the right hand side.
Many other logical condition forms are possible as explained below.
The conditionally dependent term may appear in replacement (=) statements or model
equation (..) specification commands.
When the $ is placed outside a sum then the sum is only computed if the logical condition
is true potentially making the program faster.
Right hand side conditionals do not stop replacements from occurring, but left hand side
ones do as elaborated on in the Calculating chapter.
Conditionally displaying information
Conditionals may be used to cause the display of information if certain conditions are met. In
such cases one usually employs a conditional in conjunction with the display command (Note the
display command discussed in the Report Writing chapter). One of two forms of the command
generally appear. The first involves the if syntax as discussed below where a display is executed
if a particular condition is found to be true. Second, one can have the word display followed by
a $condition. Therein the display will only occur if the $condition is true.
The general format for a these conditional display commands is
if(condition, display listofitems);
display$condition listofitems;
as illustrated just below (conddisp.gms)
scalar x /0/,y /10/;
if(x gt 0,display "X and y at first place if x is positive",x,y;);
*note next command is redundant to above
display$(x+y le 0) "display when sum of x and y le 0",x,y;
x=2;
display$(x > -1) "display with display$ at third place",x;
*note will not get to next line
if((x+y > 2),display "X and y at first place if x+y is greater than 2",x,y;);
Terminating a program
Abort
Conditionals may be used to cause the execution of the program to be terminated. In such cases
one usually employs a conditional in conjunction with the abort command. The abort command
operates just like a display command with the same syntax excepting the word abort replacing
display. The general format for a these conditional display commands is
if(condition,abort listofitems);
abort$condition listofitems;
An example is given below (abort.gms)
scalar x /0/;
if(x > 0,abort "i stopped at first place",x;);
*note next command is redundant to above
abort$(x > 0) "i stopped with abort$ at first place",x;
display "i got past first place" ,x;
x=2;
abort$(x > 0) "i stopped with abort$ at second place",x;
*note will not get to next line
if(x > 0,abort "i stopped at second place",x;);
When encountered the abort command causes the job to stop with an execution error and
displays the information in the command.
Abort can also be used unconditionally to stop a job just inserting the line
abort listofitems;
in the program
Conditional placement and program execution speed
As discussed above $ commands can be employed to cause calculations to not be done
potentially causing faster executing code. For example the statement (conditional.gms)
X=sum(I,a(i)) $qq;
Eq5(i)$qq..
sum(j,ijvar(I,j))=g= -a(i);
will generally be faster than
X=sum(I$qq,a(i));
Eq6(i)..
sum(j,ijvar(I,j)) $qq =g= -a(i) $qq;
because some work is avoided. In general, conditionals are important tools to speed up
execution. The Speed chapter elaborates.
If
Else
Elseif
Another way of imposing conditionals involves use of the if statement syntax that also involves
the else and elseif statements. In general, if statements can be written as $ conditions, but the use
of if can make GAMS code more readable. If statements are covered in the Control Structures
chapter.
While
Another way of imposing conditionals involves use of the while statement. In general, the while
allows one to repeatedly execute a block of statements until a logical condition is satisfied.
While statements are covered in the Control Structures chapter.
Repeat
Another way of imposing conditionals involves use of the repeat statement. In general, the
repeat causes one to execute a block of statements over and over until a logical condition is
satisfied. Repeat statements are covered in the Control Structures chapter.
Forms of logical / true false statements
Logical conditions can involve numerical relationships, the presence of numbers, sets, or
acronyms. Each is slightly different and will be discussed separately.
Numerical comparisons
Local conditions can be formed which compare two numerical expressions to see if they are
equal, unequal, or if one or the other is larger. The forms are as follows:
Eq
=
I may wish to establish a conditional that is true if two numerical expressions are equal and is
false otherwise. Here the syntax is
Numeric expression1 eq numeric expression 2
or
Numeric expression1
=
numeric expression 2
where eq or = can be used interchangeably. Examples from formconditional.gms
If(x eq 2, z=2);
=2)..
Eq1$(x
zz=e=3;
Loop(I$(sqrt(x)+1
=
y+2),z=z+1)
Ne
<>
I may wish to establish a conditional that is true if two numerical expressions are unequal and is
false otherwise. Here the syntax is
Numeric expression1 ne numeric expression 2
or
Numeric expression1
<>
numeric expression 2
where ne or <> can be used interchangeably. Examples from formconditional.gms
If(x ne 2, z=2);
<>2)..
Eq2$(x
zz=e=3;
Loop(I$(sqrt(x)
<>
y+2),z=z+1)
Gt
>
I may wish to establish a conditional that is true if one numerical expression is greater than
another and is false otherwise. Here the syntax is
Numeric expression1 gt numeric expression 2
or
Numeric expression1
>
numeric expression 2
where gt or > can be used interchangeably. Examples from formconditional.gms
If(x gt 2, z=2);
>2)..
Eq3$(x
zz=e=3;
Loop(I$(sqrt(x)
>
y+2),z=z+1)
Lt
<
I may wish to establish a conditional that is true if one numerical expression is less than another
and is false otherwise. Here the syntax is
Numeric expression1 lt numeric expression 2
or
Numeric expression1
<
numeric expression 2
where Lt or < can be used interchangeably.
Examples from formconditional.gms
If(x Lt 2, z=2);
<2)..
Eq4$(x
zz=e=3;
Loop(I$(sqrt(x)
Ge
>=
<
y+2),z=z+1)
I may wish to establish a conditional that is true if one numerical expression is greater than or
equal to another and is false otherwise. Here the syntax is
Numeric expression1 Ge numeric expression 2
or
Numeric expression1
>=
numeric expression 2
where ge or >= can be used interchangeably.
Examples from formconditional.gms
If(x ge 2, z=2);
>=2)..
Eq5$(x
zz=e=3;
Loop(I$(sqrt(x)
>=
y+2),z=z+1)
Le
<=
I may wish to establish a conditional that is true if one numerical expression is less than or equal
to another and is false otherwise. Here the syntax is
Numeric expression1 le numeric expression 2
or
Numeric expression1
<=
numeric expression 2
where Le or <= can be used interchangeably.
Examples from formconditional.gms
If(x Le 2, z=2);
<=2)..
Eq6$(x
zz=e=3;
Loop(I$(sqrt(x)
<=
y+2),z=z+1)
Eqv
<=>
Imp
->
GAMS contains logical equivalence operators. The syntax for the operators is
item1 opr item2
where opr is
Eqv
for logical equivalence
<=>
for logical equivalence
Imp
for logical implication
->
for logical implication
or
and
or
These operate with results as follows
Result of imp condition Result of eqv condition
item1 item1
0
0
0
1
1
0
1
1
item1 -> item2
item1 imp item2
1
1
0
1
item1 <=> item2
item1 eqv item2
1
0
0
1
Example
impeqv.gms
LOOP(CASE,
result(case,"isimp")=0;
result(case,"isimp")=0;
result(case,item)=data(case,item);
IF(DATA(case,"a") imp data(case,"b")
,result(case,"isimp")=1;);
IF(DATA(case,"a") eqv data(case,"b"),
result(case,"iseqv")=1;);
);
Data existence
Local conditions can be formed which are true if a data item exists with existence defined as the
presence of a nonzero value or if a numerical expression exists (again with existence being
defined as the expression result being nonzero). The forms are as follows:
Existence/nonzero data item or result
I may wish to establish a conditional that is true if a numerical value of a scalar item, set indexed
parameter or calculation result is nonzero and is false otherwise. Here the syntax is
Action$Numeric expression
or
If(Numeric expression, statements);
or
While(Numeric expression, statements);
Examples from dataconditional.gms
Z=z+2$x;
If(x, z=2);
Eq5$doiwantconstraint.. zz=e=3;
Loop(I$q(i),z=z+1)
While(x*x-1, z=z+2;x=x-1);
all of which will be executed if the item being tested in the conditional is nonzero.
This all could be expressed as $(Numeric expression <> 0) but this syntax is often utilized
because it is more compact.
Computation over a set
I may wish to establish a conditional that is true if a numerical value of a sum, prod, smax or
smin over a set is nonzero and is false otherwise. Here the syntax is
Action$Sum(set,expression)
or
If(Smin(set,expression), statements);
or
While(Smax(set,expression), statements);
Examples
dataconditional.gms
Z=z+2$sum(I$q(i),1);
If(smin(I,q(i)), z=2);
Eq5$prod(I,q(i)).. zz=e=3;
Eq6(j)$sum(I,abs(data(I,j))).. zz=e=3;
Loop(I$sum(j,abs(data(I,j))),z=z+1)
While(prod(I,q(i)), z=2;q(i)=q(i)-2);
Notes
In these cases the term subject to the conditional will be evaluated or the calculation will
be executed if the final result of the set dependent expression is nonzero.
This all could be expressed as $(Numeric expression ne 0) but the syntax $(Numeric
expression) is often utilized because it is more compact.
The conditional as in the expression sum(I$q(i),1) reveals a commonly used GAMS trick
for seeing whether there is any nonzero data in an item (by counting it and when the
count is zero all the data are zero).
Including the conditional expression $sum(j,abs(data(I,j)) is a common GAMS trick for
seeing whether there is any nonzero data across all the j alternatives in a row I of
data(I,j).
Set comparisons
Logical conditions can be formed which depend on sets in terms of the relative placement of the
element being worked on, whether an item falls in a subset or tuple and element text
comparisons The forms are as follows:
Element position
Ord
Card
The ord and card functions as discussed in the sets chapter can be used in conditionals.
Ord(setelement) returns the number of the element being referenced relative to the total number
of elements in the set. Card(setname) gives the total number of elements in the named set.
These numerical values can be subjected to any of the numerical comparisons above.
Examples
setconditional.gms
If one wishes to do special things with respect to the first, last and intermediate elements in a set
one could use code like
FIRSTBAL(period)$(ord(period) eq 1)..
SELL(period) + STORE(period) =L= INVENTORY;
INTERBAL(PERIOD)
$(ORD(period) GT 1 and ORD(period) lt CARD(period))..
SELL(PERIOD) =L= STORE(PERIOD-1) - STORE(PERIOD);
LASTBAL(PERIOD)$(ORD(period) eq CARD(period))..
SELL(PERIOD)=L= STORE(PERIOD-1);
or
loop(period
$(ORD(period) GT 1 and ORD(period) lt CARD(period)),
Z=z+1;);
Notes
Ord does not work with sets that contain calculated elements or are otherwise unordered,
only sets with a priori explicitly specified values.
Ord refers to the relative position of each element in the set not necessarily the order in
which they are typed. In particular, the order may be different as determined by the rules
for set ordering as discussed in the Rules for Item Capitalization and Ordering chapter.
Card works with any sets whether they contain calculated elements or not.
Element text comparison
Sameas
Diag
Logical conditions can be formed which depend on name of a set element matching a particular
text string or matching up with names for a set element in another set. This can be done in
GAMS using the sameas or diag commands. SAMEAS returns a value of true or false using the
syntax
SAMEAS(setelement,othersetelement)
or
sameas(asetelement,”text”)
where the first sameas is true if the name of setelement is the same as the name of
othersetelement and is false otherwise. Similarly, sameas(asetelement,”texttotest”) is true if
name of asetelement is the same as the texttotest and false otherwise.
DIAG works identically but returns numerical values of one if the text matches and zero
otherwise.
Diag(setelement,othersetelement)
or
diag(asetelement,”text”)
Examples
(setconditional.gms)
The following red uses of sameas and diag will only permit the case of I and j to be part of the
sum where the elements for both are Boston and do not require the sets to be subsets of each
other. The blue cases will only operate for the element of I associated with the name “new
york”.
Set
cityI
/ “new york”, Chicago, boston/;
Set
cityj
/boston/;
Scalar ciz,cir,cirr;
ciZ=sum(sameas(cityI,cityj),1);
ciR=sum((cityI,cityj)$ sameas(cityI,cityj),1);
ciRR=sum(sameas(cityI,”new york”),1);
ciZ=sum((cityi,cityj)$diag(cityI,cityj) ,1);
ciRR=sum(cityi$diag(cityI,"new york"),1);
Subset or tuple membership
A logical condition may involve whether a set element is in a particular subset or tuple. The
general syntax for the subset test is
Action$subset(set element)
or
If(subset(quoted set element), Action);
or
While(subset(quouted set element), Action);
or in the tuple case is
Action$tuple name(set1 element, set2 element)
or
If(tuple name(set1 element, set2 element), Action);
or
While(tuple name(set1 element, set2 element), Action);
where the set element may be either a particular element set off in quotes or a set name if that set
name is controlled within the action or earlier in a Loop statement.
Examples
(setconditional.gms)
ciZ=sum((allcity,cityj) $cityi(allcity),1);
ciZ$cityi("boston")=sum(allcity,1);
loop((allcity,cityj) $ tuple(allcity,cityj),
ciz=ciz+ord(allcity)+ord(cityj)*100);
if(cityj("boston"),ciz=1);
if(tuple(“orlando”,"boston"),ciz=1);
Acronym comparisons
Logical conditions can be based on acronyms, which are character string values, but many only
involve the eq , = , ne , or <> operators. The syntax is
If(parameter containing acronym op acronym ,action);
or
Action$(param. containing acronym op acronym)
where op is one of the eq , = , ne , or <> operators.
Examples
(Acronym.gms)
acronyms nameforit,nextone;
acronym acronym3
acronym doit
parameter textstrings(i)
/i1 nameforit
i2 nextone
i3 acronym3/ ;
loop(i,
if(textstrings(i)=nameforit,put 'Something special'););
aa(i)$(textstrings(i) =doit).. 3*x(i)=e=1;
Nesting logical conditions
Individual logical conditions can be nested to generate more complex logical conditions.
Nesting operators
Sometimes it is desirable to use complex logical conditions where several things are
simultaneously true or at least one of several things. This can be done by combining conditions
using logical operators or complex (nested) $ conditions. The logical operators are And, Or, Xor
and Not.
And
When one wishes to perform an action if two or more conditionals to apply simultaneously one
can join them with an and operator. This involves using syntax like
Action$(logical condition 1 and logical condition 2 and
Logical condition 3)
or
If((logical condition 1 and logical condition 2 and
Logical condition 3), Action);
or
While((logical condition 1 and logical condition 2 and
Logical condition 3), Action);
Examples
(complexcond.gms)
u(k)$(s(k) and t(k)) = a(k);
u(k)$(s(k) and u(k) and t(k)) = a(k);
loop(k,if(s(k) lt 0 and t(k), u(k) = a(k)) );
Notes
All of the logical conditions must be simultaneously true for the total logical condition to
be true.
The and operator can be mixed with other and , or , not, xor , nested $ in a complex
logical condition. When this is done GAMS will execute the various statement
components according to a predefined operator precedence . However it is advisable to
be cautious and use parentheses to carefully control the meaning of the condition.
Or
When one wishes to perform an action if at least one of two or more conditionals apply one can
join them with an or operator. This involves using syntax like
Action$(logicalcondition1 or logicalcondition2 or
logicalcondition3)
or
If(logicalcondition1 or logicalcondition2 or
logicalcondition3), Action);
or
While(logicalcondition1 or logicalcondition2 or
logicalcondition3), Action);
Examples
(complexcond.gms)
u(k)$(s(k) or t(k)) = a(k);
u(k)$(s(k) or u(k) or t(k)) = a(k);
loop(k,if(s(k) lt 0 or t(k), u(k) = a(k)) );
Notes
Any one or more than one of the logical conditions must be simultaneously true for the
total logical condition to be true.
The or operator can be mixed with other and , or , not, xor , nested $ in a complex
logical condition. When this is done GAMS will execute the various statement
components according to a predefined operator precedence. However it is advisable to be
cautious and use parentheses to carefully control the meaning of the condition.
Xor
When one wishes to perform an action one and only one of two or more conditionals apply one
can join them with an xor operator. This involves using syntax like
Action$(logical condition 1 xor logical condition 2 xor
Logical condition 3)
or
If(logical condition 1 xor logical condition 2 xor
Logical condition 3, Action);
or
While(logical condition 1 xor logical condition 2 xor
Logical condition 3, Action);
Examples
(complexcond.gms)
u(k)$(s(k) xor t(k)) = a(k);
u(k)$(s(k) xor u(k) xor t(k)) = a(k);
loop(k,if(s(k) lt 0 xor t(k), u(k) = a(k)) );
Notes
One and only one not more than one of the logical conditions can be simultaneously true
if the total logical condition to be true.
The xor operator can be mixed with other and , or , not, xor , nested $ in a complex
logical condition. When this is done GAMS will execute the various statement
components according to a predefined operator precedence. However it is advisable to be
cautious and use parentheses to carefully control the meaning of the condition.
Not
When one wishes to do something when a conditional is not true one can prefix it a not operator.
This involves using syntax like
Action$( not logical condition 1)
or
If(not logical condition 1, Action);
or
While(not logical condition 1), Action);
Examples
(complexcond.gms)
u(k)$(not s(k)) = a(k);
loop(k,if(not (s(k) lt 0), u(k) = a(k)) );
Notes
When a logical condition is preceded by a not then the logical condition must be false for
the not of it to be true.
The not operator can be mixed with other and , or , not, xor , nested $ in a complex
logical condition. When this is done GAMS will execute the various statement
components according to a predefined operator precedence. However it is virtually
imperative that you set the not off in parentheses to insure the meaning of the statement.
Nested conditionals
Complex $ conditions
$ conditions can be nested. The term $(logical condition 1$( logical condition 2)) can also be
written as $( logical condition 1 and logical condition 2). For nested $ conditions, all succeeding
expressions after the first $ must be enclosed in parentheses. Consider the following example
(complexcond.gms),
u(k)$(s(k)$t(k)) = a(k) ;
The assignment will be made only for those members of k that are also members or associated
with data in both s and t. Note the position of the parenthesis in the $ condition. The statement
above can be rewritten as
u(k)$(s(k) and t(k)) = a(k) ;
To assist with the readability of statements, one should usually employ the operator and instead
of nesting dollar operators.
Cautions about nested operators and precedence order
Precedence order
Nested operators are acted on in a fixed precedence order and are also operated on in an order
relative to mathematical operators. The default precedence order in the absence of parentheses is
shown below in decreasing order.
Operation
Operator
Exponentiation
Multiplication, Division
Addition, Subtraction
Numerical Relationships
**
*/
+< ,<=, = , <>, >=, >
lt , le ,eq, ne , ge, gt
not
and
or, xor
Not
And
Or, Xor
Precedence
1
2
3
4
5
6
7
When operators with the same precedence appear in an expression or logical condition they are
performed from left to right.
Note of caution
It is always advisable to use parentheses rather than relying on the precedence order of operators.
It prevents errors and makes the intention clear. It is especially important to encapsulate not
operators in parentheses to limit their scope.
Examples
(complexcond.gms)
(s(k) and {u(k) xor t(k)}) = a(k);
u(k)$(s(k) and {u(k) or t(k)}) = a(k);
u(k)$([not s(k)] and {u(k) or t(k)}) = a(k);
u(k)$(s(k) xor {u(k) and t(k)}) = a(k);
u(k)$(s(k) xor [not {u(k) and t(k)}]) = a(k);
u(k)$
Notes
You can use (),[] and {} in pairs interchangeably.
When the not operator is mixed with other and, or, not, xor, nested $ in a complex
logical condition it is virtually imperative that you set the not off in parentheses to
insure the meaning of the statement.
When more than one and, or, not, xor, nested $ operator are used in a complex logical
condition GAMS will execute the various statement components according to a
predefined operator precedence.
The conditional alternative – the tuple
Often the conditionals that are required in a model are complex and are used in a repetitive
manner. It is sometimes simpler to establish a tuple that encapsulates the conditionals and only
use it instead of the tuple.
Example
In the model below the logical condition that appears can be replaced with the tuple and the
model is visually simpler plus potentially easier to maintain. (tuple.gms)
TCOSTEQ..
TCOST =E= SUM((PLANT,MARKET)
$(
supply(plant)
and demand(market)
and distance(plant,market))
, SHIPMENTS(PLANT,MARKET)*
COST(PLANT,MARKET));
SUPPLYEQ(PLANT).. SUM(MARKET
$(
supply(plant)
and demand(market)
and distance(plant,market))
,SHIPMENTS(PLANT, MARKET))
=L= SUPPLY(PLANT);
DEMANDEQ(MARKET).. SUM(PLANT
$(
supply(plant)
and demand(market)
and Distance(plant,market))
, SHIPMENTS(PLANT, MARKET))
=G= DEMAND(MARKET);
where the alternative with the tuple is
set thistuple(plant,market) thistuple expressing conditional;
thistuple(plant,market)$(
supply(plant)
and demand(market)
and distance(plant,market))
=yes;
TCOSTEQ2..
TCOST =E= SUM(thistuple(plant,market)
, SHIPMENTS(PLANT,MARKET)*
COST(PLANT,MARKET));
SUPPLYEQ2(PLANT).. SUM(thistuple(plant,market)
,SHIPMENTS(PLANT, MARKET))
=L= SUPPLY(PLANT);
DEMANDEQ2(MARKET).. SUM(thistuple(plant,market)
, SHIPMENTS(PLANT, MARKET))
=G= DEMAND(MARKET);
Notes
More on tuples appears in the Sets and Calculating chapter.
One should be careful here with the fact that a tuple is only calculated in a static manner
and the calculation will only be updated if it is reissued as discussed in the Calculating
chapter.
Alphabetic list of features
$
=
>
>=
<
<=
<=>
<>
->
Abort
Abort
Acronym comparisons
And
Card
Conditional
Diag
Display
Eq
Eqv
Ge
Gt
If
Imp
Le
Symbol to set off conditionals.
Relation operator in testing whether one item is equal to
another.
Relation operator in testing whether one item is greater
than another.
Relation operator in testing whether one item is greater
than or equal to another.
Relation operator in testing whether one item is less than
another.
Relation operator in testing whether one item is less than or
equal to another.
Relation operator in testing whether one item is logically
equivalent to another.
Relation operator in testing whether one item is not equal to
another.
Relation operator in testing whether one item logically
implies another.
Conditional job termination and data display.
Command to stop GAMS job and display data
Conditionals over acronyms.
Relational operator that links sub-logical conditions being
true when all sub conditions are true.
Use of function for number of elements in a set in
conditionals.
Concept that involves execution of statements only when
logical condition is true.
Function that is a one if text for set elements match and
zero otherwise.
Conditional data displays.
Relation operator in testing whether one item is not equal to
another.
Relation operator in testing whether one item is logically
equivalent to another.
Relation operator in testing whether one item is greater
than or equal to another.
Relation operator in testing whether one item is greater
than another.
Conditional control of multiple lines.
Relation operator in testing whether one item logically
implies another.
Relation operator in testing whether one item is less than or
equal to another.
Lt
Ne
Nested conditionals
Not
Or
Ord
Precedence order
Repeat
Sameas
Speed
Subset
Tuple
While
Xor
Relation operator in testing whether one item is less than
another.
Relation operator in testing whether one item is not equal to
another.
Use of multiple layers of conditionals.
Relation operator that makes a condition true what a logical
condition is false.
Relational operator that links sub-logical conditions being
true when at least one sub condition is true.
Function that returns number of element in set.
Precedence order incorporating numbers and logical
conditions.
Statement that executes multiple lines repetitively until a
conditional is true.
Function that tests if text for set elements match and false
otherwise.
Speed implications of conditional placement.
Concept where one set is a subset of another.
Concept where a multi dimensional set is used to encode a
conditional.
Statement that executes multiple lines repetitively while a
conditional is true.
Relational operator that links sub-logical conditions being
true when only one sub condition is true.
Download