introduction to gams
TRANSCRIPT
-
7/31/2019 Introduction to GAMS
1/20
Introduction to GAMS:
Conditionals, Subsets and Tuples in
GAMS
Bruce A. McCarl
&Levan ElbakidzeDepartment of Agricultural
Economics
Texas A&M University
-
7/31/2019 Introduction to GAMS
2/20
-
7/31/2019 Introduction to GAMS
3/20
Conditionals allow GAMS modelers to write
expressions that operate over less than full seor incorporate various model features
conditionally depending on data.
Fundamentally, they are used to:
Control whether an item is calculatedOn a set element by element basis
Control the inclusion ofterms in equations
In = calculations
In a .. model equation specificationsControl inclusion ofset dependent terms in sums
Control inclusion of equations in a model
On a set element by element basis
Control whether a display is output to the LST fi
Here we cover ways to do this first with
conditionals and later with a set or subset
Conditionals, Subsets and Tuples in GAMS
-
7/31/2019 Introduction to GAMS
4/20
Conditionals, Subsets and Tuples in GAMS
Basics of a $ Conditional
A conditional is entered into GAMS by adding a
$ into a GAMS statement. That causes an actionto occur if the conditional is true. The basic $
conditional form isterm$logical condition
which says include the term only if the logical
condition is true.
Suppose in a model we wish to set the parameter
X equal to 10 only if the parameter y is greater
than zero. A very basic conditional
(conditional.gms) that imposes this is as followsX $ (Y gt 0) = 10;
which says set X = 10only ifthe scalar y is
greater than zero.Many different logical condition forms are
possible as I review later in these notes.
-
7/31/2019 Introduction to GAMS
5/20
Conditionals, Subsets and Tuples in GAMSControlling whether an item is calculated
$conditionals can appear in a model to restrict
whether calculations are done. General format isnamedparameter$logicalcondition=term;
and specifies that the named parameter is set equal t
the term only if the logical condition is true.
Examples of whether an item is computed
X $(qq gt 0) =3;
qq $(sum(I,q(i)) gt 0) =4;
a(i)$(qq gt 0) =q(i)/qq;
qq $(sum(i,abs(a(i))) gt 0) =1/sum(i,a(i));Examples of whether elements of an item are
computed
Q(i)$(a(i) gt 0) = -a(i);
a(i) $(abs(a(i)) gt 0) = q(i)/a(i);
The replacement is active only if the condition istrue. Above if X started at 7 and qq0 then X would = 3. The last 2
statements compute some but not all QThis is known in GAMS terminology as a conditional
on the left hand side.
-
7/31/2019 Introduction to GAMS
6/20
Conditionals, Subsets and Tuples in GAMSControlling inclusion of terms in equations
$ conditionals can restrict whether terms are included in
eplacements or model equations. General formatterm$logicalcondition
causing terms to be included only if the condition holds.
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);
The right versus left hand side conditional case
merits mention here. Consider
Q(i)= (a(i) + 1)$(a(i) gt 0);
X = [sum(I,q(i))+4]$(qq gt 0);Which are treated as
Q(i)= 0+ (a(i) + 1)$(a(i) gt 0);
X = 0+ [sum(I,q(i))+4]$(qq gt 0);These are somewhat like .
Q(i)$(a(i) gt 0)= (a(i) + 1);X$(qq gt 0) = [sum(I,q(i))+4];But in above cases the items in pinkwill equal zero when
he conditional is not true but in the maroon case will
etain their prior value. This is important left versus right
hand side conditional characteristic.
-
7/31/2019 Introduction to GAMS
7/20
Conditionals, Subsets and Tuples in GAMS
Controlling inclusion of set dependent terms
$conditionals are frequently used to restrict the elements
of a set that will be explicitly entered into a sum, loop,or other set operation (e.g. prod, smax,smin). In
particular there may be a restriction one wishes to place
on the set elements that can validly enter the calculation
Inclusion is controlled by a logical condition. Generally
this logical condition will incorporate set elementdependent terms. The general format in a SUM context
is
sum(namedset$set dependentlogical condition,term)
where for example
0/ iqi
iaXis written as
X=sum(I$(q(i) gt 0),a(i));
Similarly one can writeLoop((I,j)$(cost(I,j) lt 0),X=x+cost(I,j));
X=smin(I$(sum(j,cost(I,j)) gt 0),q(i));X=sum(I$(q(i) gt 5),1));
All include the term associated with particular set
elements in the sum or loop or smin only if the
logical condition is true.
-
7/31/2019 Introduction to GAMS
8/20
Conditionals, Subsets and Tuples in GAMSControlling whether equations are included
conditionals can be used to restrict whether modelquations are active in a model. The general format isquationname$logicalcondition.. equationspecification;
nd specifies that the equation is active in the model only i
he logical condition is true.
Eq1 $(qq gt 0).. xvar=e=3;Eq2 $(sum(I,q(i)) gt 0).. yvar=l=4;
Eq3(i)$(a(i) gt 0).. ivar(i)=g=a(i);
Eq5(i)$(qq gt 0).. ivar(i)=g=a(i);n these cases, the whole equation called equationname
see the Eq1, Eq2 and Eq5 cases above) will be entered
nto the model only if the logical condition is true. When
he conditional involves set dependent terms then only the
pecific cases associated with true conditionals will occur
see the Eq3 case above)
When the $ is on the left hand side, the equation is only
ncluded in the model and calculated if the logical
ondition is true. This can make the program faster
-
7/31/2019 Introduction to GAMS
9/20
Conditionals, Subsets and Tuples in GAMS
Conditionally displaying information
Displays may be conditioned to appear only if a
logical condition is met. (Note the display command
is discussed in the Report Writing chapter of the
documentation).
One can have the keyword display followed by a
$condition. Therein the display will only occur if the
$condition is true.
display$conditionlistofitems;
One can also use the if syntax as
if(condition, display listofitems);
Both are illustrated below
scalar x /0/,y /10/;if(x gt 0,
display "X and y if x is positive",x,y;);*note next command is redundant to abovedisplay$(x+y le 0)
"display when sum of x and y le 0",x,y;x=2;display$(x > -1)
"display$ at third place",x;*note will not get to next line
if((x+y > 2),display "X and y if x+y is greater than 2",x,y;);
http://c/classsource/basic/report_writing.dochttp://c/classsource/basic/report_writing.doc -
7/31/2019 Introduction to GAMS
10/20
Conditionals, Subsets and Tuples in GAMS
Forms of $ logical conditions
Logical conditions can involve numerical comparisons,
existence of numbers or set elements, and index
characteristics in sets. Each case is slightly different
and will be discussed separately.
Numerical comparisons
Logical conditions can compare two numerical
expressions . The general form is
Term$(terma operator termb)
The operators are as follows:Relation GAMS operator Explanation
Equality EQ or = Is terma = termb
Not Equal NE or Is terma termb
Greater than GT or > Is terma > termb
Greater or = GE or >= Is terma > termbLess than LT or < Is terma < termb
Less or = LE or >= Is terma < termb
-
7/31/2019 Introduction to GAMS
11/20
Conditionals, Subsets and Tuples in GAMS
Numerical $ condition forms
Relation GAMS operator ExplanationEquality EQ or = Is terma = termb
Not Equal NE or Is terma termb
Greater than GT or > Is terma > termb
Greater or = GE or >= Is terma > termb
Less than LT or < Is terma < termbLess or = LE or >= Is terma < termb
Examples
Eq3$(x=2).. zz=e=3;
Xx=Sum(I$(x eq sum(j,y(I,j))+2),1);
Xx=Sum(I$(x sum(j,y(I,j))+2),1);Xx=Sum(I$(x ne 22),1);
Eq4$(x yx+2),z=z+1);
Loop(I$(x gt yx+2),z=z+1);Eq5$(x>=2).. zz=e=3;
Xx=Sum(I$(x ge yx+2),z=z+1);
Eq6(i,j)$(y(I,j)
-
7/31/2019 Introduction to GAMS
12/20
Conditionals, Subsets and Tuples in GAMS
Element or item presence condition forms
General form
Action$Number or numeric expression
Action$Subsetelement
Such conditions can be formed which are true if
1. A data item exists with a nonzero valuexx$yx = 3; equivilant to xx$(yx ne 0)=3;
2.A numerical expression exists (again with existence
being defined as the expression result being nonzero)
xx$sum((i,j),y(i,j)) = 3;
Important subcase is are there some data for an itemxx$sum((i,j)$y(i,j),1) = 3;
or xx$sum((i,j),1$y(i,j)) = 3;
or xx$sum((i,j),abs(y(i,j))) = 3;
3.A subset element exists
rx(i)$subsetofi(i) = 3;4. Some of a group of set elements exist
xx$sum(i$subsetofi(i),1)=3; (note $ nesting)
-
7/31/2019 Introduction to GAMS
13/20
Conditionals, Subsets and Tuples in GAMSSet element position
Logical conditions can be formed which depend on setsin terms of the relative placement of the element being
worked on and element text comparisons.
Element position
Ord returns number of an element from 1 to N
Card returns total number of elements in a set.Use with numerical conditions from above
Example
If one wishes to do special things with respect to the
first, last and intermediate elements in a set one could
use code likeFIRSTBAL(time)$(ord(time) eq 1)..
SELL(time) + STORE(time) =L= INVENTORY;
INTERBAL(TIME)
$(ORD(time) GT 1 and ORD(time) lt
CARD(time))..
SELL(TIME)=L=STORE(TIME-1)-
STORE(TIME);
LASTBAL(TIME)$(ORD(time) eq CARD(time))..
SELL(TIME)=L= STORE(TIME-1);
or
loop(time$(ORD(time) GT 1 and
ORD(time) lt CARD(time)),Z=z+1;);
-
7/31/2019 Introduction to GAMS
14/20
Conditionals, Subsets and Tuples in GAMS
Set element text contents
Logical conditions can test the text content of set
element names matching a particular text string or
matching up with names for a set element in another set.
These involve the sameas or diag commands.SAMEAS(setelement,othersetelement)
is true if setelement name is the same as name of
othersetelement and is false otherwise.
sameas(asetelement,texttotest) is true if name of
asetelement equals texttotest and false otherwise.
DIAG works identically but returns numerical values of
one if the text matches and zero otherwise.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);
The red uses of sameas and diag will only permit I and j to be
part of the sum when elements are both Boston. The blue
cases will only operate for the element of I associated with the
name new york.
-
7/31/2019 Introduction to GAMS
15/20
Conditionals, Subsets and Tuples in GAMS
Nesting logical condition
Sometimes complex logical conditions are needed
to insure several things are true or at least one of
several things. Such complex conditionals are
called nested. Common nesting operators are
And, Or, Not.and - perform an action if two or more
conditionals to apply simultaneously
or - perform an action if at least one of two or
more conditionals apply
not - do something when a conditional is not rueNested $ - statements can involve multiple $
conditions
Examplesu(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)));
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)) );
u(k)$(not s(k)) = a(k);
loop(k,if(not (s(k) lt 0), u(k) = a(k)) );u(k)$(s(k)$t(k)) = a(k) ;
-
7/31/2019 Introduction to GAMS
16/20
Conditionals, Subsets and Tuples in GAMSNesting logical condition
Nested operators are acted on in a fixed precedence
order and are also operated on in an order relative tomathematical operators. The default precedence order
in the absence of parentheses is shown below in
decreasing order.
Operation Operator Precedence
Exponentiation ** 1Multiplication, Division * / 2
Addition, Subtraction + - 3
Numerical Relationships < ,=, >
lt , le ,eq,ne , ge, gt
Not not 5
And and 6
Or, Xor or, xor 7
When operators with the same precedence appear inan expression or logical condition they are performed
from left to right. It is always advisable to use
parentheses rather than relying on the precedence
order of operators.u(k)$([not s(k)] and {u(k) or t(k)}) = a(k);
u(k)$(s(k) or {u(k) and t(k)}) = a(k);u(k)$(s(k) or [not {u(k) and t(k)}]) = a(k);
-
7/31/2019 Introduction to GAMS
17/20
Conditionals, Subsets and Tuples in GAMS
The conditional alternativethe Subset
Mathematically one often sees algebraic
statements where the index positions to address aresubsets of larger sets of index positions. This can
be done in GAMS using subsets and tuples.
Namely suppose in a case where we have 40
elements we wish to sum elements 1 to 20
20
1i
iZX
we can define a subset of I containing elements 1-20 viaset subseti(i) /i1*i20/;
then we can writeX=sum(I$subseti(i),z(i));
orX=sum(subseti,z(subseti));
orX=sum(subseti(i),z(i));
The first and last of which vary I over values that
appear in the subset and the middle which addresses
only the subset.
One can also compute the subsetSubseti(i)$(ord(i) le 20)=yes;
and then use as above
-
7/31/2019 Introduction to GAMS
18/20
Conditionals, Subsets and Tuples in GAMS
The conditional alternativethe tuple
Often the conditionals required in a model are complex and
re used in a repetitive manner. It can be simpler tomploy a tuple (a set that is defined over other sets see the
ets chapter of the documentation) that encapsulates the
onditionals and only use it. In the model below the
ogical condition in red that appears repetitively can be
eplaced with the tuple making the model visually simpler
COSTEQ.. TCOST =E= SUM((PLANT,MARKET)
$(supply(plant) and demand(market)
and distance(plant,market))
, SHIPMENTS(PLANT,MARKET)* COST(PLANT,MARKET));
UPPLYEQ(PLANT).. SUM(MARKET
$(supply(plant) and demand(market) anddistance(plant,market)),SHIPMENTS(PLANT,
MARKET)) =L= SUPPLY(PLANT);
EMANDEQ(MARKET).. SUM(PLANT
$(supply(plant)and demand(market)
and Distance(plant,market))
,SHIPMENTS(PLANT, MARKET)) =G= DEMAND(MARKET);
where the alternative with the tuple iset thistuple(plant,market)tuple expressing conditional;histuple(plant,market)$(supply(plant)and demand(market)and
istance(plant,market)) =yes;
COSTEQ2..TCOST =E= SUM(thistuple(plant,market)
, SHIPMENTS(PLANT,MARKET)*COST(PLANT,MARKET));
UPPLYEQ(PLANT).. SUM(thistuple(plant,market)
,SHIPMENTS(PLANT, MARKET)) =L= SUPPLY(PLANT);
EMANDEQ(MARKET).. SUM(thistuple(plant,market)
,SHIPMENTS(PLANT, MARKET)) =G= DEMAND(MARKET);
-
7/31/2019 Introduction to GAMS
19/20
Conditionals, Subsets and Tuples in GAMS
The conditional alternativethe tupleA tuple refers to a set defined over other sets. The set
may either be a one dimensional subset or amultidimensional set. Tuples are useful in calculations
and in imposing conditionals.
set thistuple(plant,market) tuple 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));
SUPPLYEQ(PLANT).. SUM(thistuple(plant,market)
,SHIPMENTS(PLANT, MARKET)) =L= SUPPLY(PLANT);
DEMANDEQ(MARKET).. SUM(thistuple(plant,market)
,SHIPMENTS(PLANT, MARKET)) =G= DEMAND(MARKET);
The statementSUM(thistuple(plant,market)
,SHIPMENTS(PLANT, MARKET))
Adds the terms by summing the PLANT and MARKET
set cases that appear in the tuple thistuple(plant,market)and given the computation above correspond to a plant
with nonzero supply a market with nonzero demand
linked by a nonzero distance.
http://c/WINDOWS/advanced/calculating.dochttp://c/WINDOWS/advanced/conditional.dochttp://c/WINDOWS/advanced/conditional.dochttp://c/WINDOWS/advanced/calculating.doc -
7/31/2019 Introduction to GAMS
20/20
Conditionals, Subsets and Tuples in GAMS
Other conditional implementation possibilities
Conditionals appear in a few other forms
If -- One can use 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 (x ne 0, DATA(I)=12 ; );
While -- One can use the while statement to repeatedlyexecute a block of statements until a logical condition is
satisfied.
while(x=10) ;