Free Windows student version available for download

Notes on GAMS for Optimization
by Ronald L. Rardin
May 21, 1999

GAMS (General Algebraic Modeling System) is a software product of the GAMS Development Corporation which solves mathematical programs inputed in a way similar to how they are presented in books and research papers. It includes the capability to globally solve linear programs and integer linear programs, as well as to find local optima of nonlinear programs and integer nonlinear programs that have all nonlinearities in continuous variables.

GAMS has an enormous number of features and options which allow it to support the most sophisticated mathematical programming and econometric applications. Fortunately, what a beginner needs to know to use the language in solving standard mathematical programs is much less.

These Notes are Professor Ron Rardin's overview of the features most often needed in coding and solving optimization models.

In the interest of simplicity and good style, many features of the language are presented in a much more limited and rigid form than actually allowed by the full GAMS. Users with more complicated questions should download the manual (about 250 pages) GAMS: A User's Guide which is available online in .pdf format.

Professor Rardin retains all copyrights to these Notes. Reproduction of any part of them for sale is prohibited without his expressed written consent, but noncommercial use or reproduction is authorized as long as the original source and author are acknowledged. (Accessed 3586 times from 1714 different hosts since 18-Jan-98)

Part I: Basics
Input (.gms) and Output (.lst) Files
GAMS from a Command Line
GAMS in the Integrated Development (Windows) Environment
Examples of Elementary GAMS Input Files
GAMS Statement Formats
Option Statements
Defining Decision Variables
Defining Equations (Objectives and Constraints)
Model Statements
Solve Statements
Decision Variable Bounds, Levels and Duals
Error Messages and Debugging

Part II: Indexing and Symbolic Parameters
Example of GAMS Input with Parameters and Subscripts
Defining Subscripts and Indexes with Sets
Subscripted Systems of Variables
Subscripted (For Every) Systems of Constraints
Indexed Summations and Products
Symbolic Parameters
Parameter Tables (Two of More Subscripts)

Part III: Advanced Index/Subscripting
$-Restrictions on Subscript Ranges and ord() Functions
Index Lag/Lead Offsets
Domains and Aliases
Subsets of Index Sets (Dynamic Sets)

Part IV: Specialized Input/Output and Options
Supplemental Print
Diagnostic Print
Included Files and Spreadsheet Input
Output to a File
Option Choices

Part V: Loops and Conditional Statements
Indexed Loops
While Loops
For Loops
If/Elseif/Else Statements
Model Outcome Status Conditions

Part I: Basics

Although GAMS can handle very sophisticated models, the basic elements needed to code models without subscripts and symbolic parameters are quite simple. This initial Part I of these Notes explains all that is needed to get started.

Input (.gms) and Output (.lst) Files

Users prepare models for GAMS solution by encoding them in a
filename.gms
input (text) file using a modeling language which parallels the standard mathematical programming format of books and research papers. Several examples are provided below.

When the input file is ready, the system is invoked to solve one or more versions of the model, with output (including any error messages) sent to corresponding file

filename.lst
Many output options are available in GAMS (see Part IV), but the default produced in the .lst file by each run is usually sufficient for student use.

Default output begins with an echo of the input like the following. If syntax errors were detected, GAMS includes numbered messages within the echo output and provides a key at the end of the listing.


   1  * Echo print example with an error
   2  positive variable x1 "product 1", x2 "product 2";
   3  free variable p "profit";
   4  equations objective, capacity;
   5  objective.. z =e= 10*x1 + 20*x2;
****              $140
   6  capacity.. x1 + x2 =l= 100;
   7  model tiny /all/;
   8  solve tiny using lp maximizing z;
****                                 $257

Error Messages
140  Unknown symbol
257  Solve statement not checked because of previous errors

Once all errors are corrected, the SOLVE SUMMARY part of the .lst file details results of the optimization.


               S O L V E      S U M M A R Y

     MODEL   TINY                OBJECTIVE  Z         
     TYPE    LP                  DIRECTION  MAXIMIZE
     SOLVER  CPLEX               FROM LINE  8

**** SOLVER STATUS     1 NORMAL COMPLETION         
**** MODEL STATUS      1 OPTIMAL                   
**** OBJECTIVE VALUE             2000.0000

                       LOWER     LEVEL     UPPER    MARGINAL  

---- EQU OBJECTIVE       .         .         .        1.000      
---- EQU CAPACITY       -INF    100.000   100.000    20.000      

                       LOWER     LEVEL     UPPER    MARGINAL  

---- VAR X1              .         .        +INF    -10.000      
---- VAR X2              .      100.000     +INF       .         
---- VAR Z              -INF   2000.000     +INF       .         

  X1          product 1
  X2          product 2
  Z           profit

The first main part of each SOLVE SUMMARY reviews results for model equations. Values are given for each objective and constraint, with the LEVEL of each constraint providing the amount of the associated resource used in the final solution and MARGINAL showing the corresponding dual variable (Lagrange multiplier) value. Any value having only a decimal point is = 0.

The second part of each SOLVE SUMMARY details results for all decision variables. These reports show the final LEVEL for each variable along with any upper and lower bounds and a MARGINAL value corresponding to the variable's reduced cost. Again, values having only a decimal point = 0.

Errors may also be reported during solving. Such execution errors usually result from an infeasible or unbounded model, program limits being exceeded, or improper computations such as taking the logarithm of a nonpositive number.

GAMS from a Command Line

Users can run GAMS from a UNIX or MDOS command line by preparing the filename.gms input file with any text editor and then typing
gams filename
Results and any error messages can be seen by editing or printing the resulting filename.lst output file stored in the current directory.

When running in command-line mode, it is recommended that each .gms file begin with the commands

$offsymxref offsymlist
option limrow=0, limcol=0;
which turn off all output except an echo of the input file and a SOLVE SUMMARY for each solve command of the input. These options are the default in the Windows IDE version.

GAMS in the Integrated Development (Windows) Environment

Windows-95 and Windows-NT users of GAMS can run the system in a new Integrated Development Environment (IDE). (A free copy of the restricted, student version is available for download at http://www.ecn.purdue.edu/~rardin/gams/download.html.)

To run the IDE version of GAMS, users must first launch the system by selecting Gams and gamside on the Programs menu (accessible from Start).

The result should be a screen similar to many other Windows applications, with a menu bar along the top and a main Edit Window for GAMS applications. As with most such systems, input and output operations are controlled by the File pulldown menu, with other menu items used in edit operations, and in running the GAMS system.

Users should begin each session by selecting a "project". A project is a system file you save but never have to touch. Still, its location is important because the folder (directory) of the current project file is where .gms input and .lst output files are saved by default. This allows you to easily keep all the input and output files for any task together in the same directory, and use different directories for different projects. The starting project file (if any) shows at the top of the main GAMS window. To select another, or create a new one, use the Project item on the File menu.

The IDE version provides for standard, mouse-driven editing of .gms files in the main GAMS Edit Window. If the appropriate file is not already displayed, use the New or Open commands on the File menu to activate one. Then create or correct the file with the mouse and tools provided on the Edit and Search menus. The Matching Parenthesis button helps with the many parentheses in GAMS by skipping the cursor to the parenthesis that corresponds to the one it is now positioned in front of.

Once a .gms file is ready to run, the Run item on the main menu bar invokes GAMS. In addition, it automatically causes a .lst output to be stored in the current project directory (but not displayed).

The .lst output file can be activated using the Open command on the File menu. However, it is usually easier to first survey an IDE run by examining the separate Process Window, which is automatically displayed. A brief log of the run appears there, and clicking on any of the boldface lines (including run error messages) will activate the entire .lst output file and position you on that message. In particular, clicking on Reading solution for model will open the .lst and position the window at the SOLVE SUMMARY.

Syntax errors in GAMS input show in red in the Process Window. Clicking on any such red error message brings up the corresponding .gms file in the main GAMS window and positions the cursor at the point where the error was detected.

Examples of Elementary GAMS Input Files

Three examples from Professor Rardin's Optimization in Operations Research (Prentice-Hall, 1998) illustrate the elements of GAMS input files for simple cases with no subscripts or symbolic parameters. Sections to follow explain the concepts used and develop extensions to more serious models (See also other examples in http://www.ecn.purdue.edu/~rardin/oorbook/software/).

Formulation GAMS Input

LP Example 5.1: Top Brass Trophy
max 12x1+9x2 (profit) s.t. x1 <= 1000 (footballs) x2 <= 1500 (soccer balls) x1+x2 <= 1750 (plaques) 4x1+2x2 <= 4800 (wood) x1, x2 >= 0

* Rardin Example 5.1 file topbrass.gms

free variable profit "profit"; positive variables x1 "football trophies", x2 "soccer trophies";
equations obj "max profit", foot "footballs", socc "soccer balls", plaq "plaques", wood "wood";
obj.. 12*x1 + 9*x2 =e= profit; foot.. x1 =l= 1000; socc.. x2 =l= 1500; plaq.. x1 + x2 =l= 1750; wood.. 4*x1 + 2*x2 =l= 4800;
model topbrass /all/; solve topbrass using lp maximizing profit;
Formulation GAMS Input

ILP Example 12.2: River Power
min 7x1+12x2+5x3+11x4 (total cost) s.t. 300x1+600x2+500x3+1600x4 >= 700 (demand) x1, x2, x3, x4 = 0 or 1

* Rardin Example 12.2 file rivpower.gms

option optcr=0.0;
free variable cost "total cost"; binary variables x1 "use 1", x2 "use 2", x3 "use 3", x4 "use 4";
equations obj "min total cost", dem "demand";
obj.. 7*x1 + 12*x2 + 5*x3 + 14*x4 =e= cost; dem.. 300*x1 + 600*x2 + 500*x3 + 1600*x4 =g= 700;
model rivpower /all/; solve rivpower using mip minimizing cost;
Formulation GAMS Input

NLP Example 14.7: Service Desk Design
max 2x1+2x2+2 (outer perimeter) s.t. (x1)2/25+(x2)2/16 <= 1 (10m limit) x1 >= 3.5 (outside) x2 >= 2.75 (2m inside)

* Rardin Example 14.7 file servdesk.gms

free variable outer "outer perimeter"; positive variables x1 "inner half width", x2 "inner depth";
equations obj "max outer perimeter", dist "10m distance limit", out "outside conveyers", in "2m inside";
obj.. 2*x1 + 2*x2 + 2 =e= outer; dist.. sqr(x1)/25 + sqr(x2)/16 =l= 1; out.. x1 =g= 3.5; in.. x2 =g= 2.75;
model servdesk /all/; solve servdesk using nlp maximizing outer;

GAMS Statement Formats

GAMS commands follow a simple syntax:

Option Statements

GAMS offers many user-controllable options, but defaults usually suffice. Two exceptions are More information on options is contained in the Option Choices section below.

Defining Decision Variables

As indicated in the above examples, the first main part of a simple GAMS input file is a declaration of the decision variables by type. Such declarations must precede any use of the variable names later in the file.

Allowed types and corresponding GAMS keywords are as follows:

Type GAMS Keyword
unrestricted (continuous) variable(s) free variable(s)
nonnegative (continuous) variable(s) positive variable(s)
nonpositive (continuous) variable(s) negative variable(s)
0-1 variable(s) binary variable(s)
nonnegative integer variable(s) integer variable(s)

Any type can also be indexed over one or more subscript sets (see Part II).

In addition to the usual decision variables of the model, there must always be free variable(s) defined to represent the objective function value(s). For example, free variable profit plays this role in the Top Brass Trophy illustration above.

Defining Equations (Objectives and Constraints)

The objective function and main constraints of GAMS mathematical programs are entered as "equation(s)". Two steps are required. First, one or more equation(s) statements declare names for the equations of the model. For example
equation dem "annual demand";
declares an equation named dem and notes that it corresponds to annual demand.

The second part of defining an equation is to add detail on each declared equation name in a separate statement beginning

equationname..
and continuing with left-hand side and right-hand side expressions separated by one of the following operators

Equation Type Operator
equals =e=
less than or equal to =l=
greater than or equal to =g=

For example, the annual demand equation declared above might be detailed as

dem .. x1 + x2 + x3 =g= 120 - x0;

One such equation always sets the objective function equal to the (free) objective value variable. Any equation can be indexed over one or more subscript sets to define a whole system of similar constraints (see Part II).

The syntax of equation detail statements follows the pattern of C and similar languages with + for addition, - for subtraction, * for multiplication, / for division, and ** for exponentiation. Terms need not be collected, and they may appear on either side of the relational operator. Parentheses may be added to group quantities or aid readability.

A variety of standard functions may also be included:

FunctionDescription
abs()absolute value
arctan()arctangent
ceil()integer ceiling
cos()cosine
exp()exponential
floor()integer floor
log()natural logarithm
log10()common logarithm
max( ,..., )max of arg1, arg2, ...
FunctionDescription
min( ,..., )min of arg1, arg2, ...
mod( , )arg1 modulo arg2
power( , )arg1 to arg2 (integer) power
round( , )round arg1 to arg2 (integer) decimal places
sign()+, 0, - sign
sin()sine
sqr()square
sqrt()square root
uniform( , )random number between arg1 and arg2

Model Statements

GAMS can define many models within a single file by collecting different combinations of equations under different names. That is why the user is required to give a name to his/her model even if there is only one.

For simple cases this is accomplished with the statement

model modelname /all/;
In more complicated situations the all can be replaced by a list of relevant equation names such as
model small /obj,demand/;
model big /obj,demand,detail/;
(see an actual example in http://www.ecn.purdue.edu/~rardin/oorbook/software/gams/hiwayptl.gms).

Solve Statements

GAMS does not solve any problems itself. Instead it translates the model into the input required by one of several "solvers" it has available. A solve statement in the format
solve modelname using solvertype maximizing objectivevaluevariable;
or
solve modelname using solvertype minimizing objectivevaluevariable;
invokes a solver where modelname is the declared name of the model, objectivevaluevariable is the free variable representing the objective function value, and solvertype is one of the following:

GAMS TypeDescription
LP exact solution of a linear program
MIP exact solution of an integer linear program
RMIP solution of the LP relaxation of an integer linear program
NLP local optimization of a nonlinear program over smooth functions
DNLP local optimization of a nonlinear program with nonsmooth functions
MIDNLP local optimization of an integer nonlinear program with nonlinearities all in the continuous variables
RMIDNLP local optimization of the continuous relaxation of an integer nonlinear program with nonlinearities all in the continuous variables

There is a default solver for each of these model types. The defaults are detailed in online documentation, and, for the IDE version, under Options on the File menu. Default solvers can also be changed with an option command. For example,

option nlp=minos5;
in a .gms file makes the default NLP solver MINOS5.

Input files often contain more than one solve statement, each optimizing a different case. For example, the following sequence solves a nonlinear programming model three times from different starting values of the decision variable x:

x.l=2.0;
solve nlmodel using nlp minimizing z;
x.l=20.0;
solve nlmodel using nlp minimizing z;
x.l=200.0;
solve nlmodel using nlp minimizing z;

Decision Variable Bounds, Levels and Duals

Decision variables in GAMS equations are unknowns to be determined. However, it is sometimes convenient to be able to refer to bounds on allowed values for variables. For this purpose every GAMS decision variable and equation has several associated quantities distinguished by suffixes:

Suffixed FormDescription
variable.l variable level or current value
variable.lo variable lower bound
variable.up variable upper bound
variable.m variable reduced cost
constraint.m constraint dual value

Upper and lower bounds may be assigned values to impose constraints. For example the statements

x.lo=1e-5;
x.up=92.0;
have the effect of enforcing constraints
10-5 <= x <= 92.0
The small positive lower bound can be particularly useful in nonlinear programming where functions may not be defined at zero.

It is sometimes also necessary to set the current level of a variable. This is particularly true in nonlinear programming where it is advisable to pick starting solutions because results may depend on initial variable values. For example, the statement

x.l=56.2;
before a solve statement will cause the algorithm to begin its search with x=56.2.

Note that the statement x=56.2; would not be allowed for a GAMS decision variable x because the variable name itself cannot be assigned a value. Add an appropriate suffix (usually .l) to correct the resulting error.

Error Messages and Debugging

GAMS provides very thorough syntax checking of models, and additional errors may be detected during solving. Like all computer systems, however, the meaning of error messages can sometimes be obscure. The following shows some of the most common message wording and the probable problem:

Error KeywordsLikely Problem
unknown symbolA set, variable, equation or parameter name is used without being previously declared.
symbol redefinedA set, variable, equation or parameter name is declared more than once. Remember xx, XX and xX are the same name.
unrecognized item
skip to a new statement
An extra semicolon or comma has interrupted a part of a statement. May be due to a constant with a comma in it.
=l=, =e=, or =g= operator expectedAn equation lacks a suitable relational operator. Remember you cannot use =, <= or >=.
suffix is missingAn operation on a decision variable or constraint does not indicate whether .l, .lo .up, or .m is intended.
endog arguments
endog operands
The model has nonlinear elements not consistent with the problem type in the solve statement.
variable wrong typeThe model has variable types not consistent with the problem type in the solve statement.
log of negative number
sqrt of a negative number
Argument of a function is outside range. Probably need a starting solution or bound on variables.
division by zero
gradient too big
A denominator is too close to zero. Probably need a starting solution or bound on variables.
no solutionThe model is infeasible or unbounded, or no solution was discovered before termination criteria were reached.
set identifier or quoted element expectedAn explicit subscript has been used without placing it in quotes.
incompatible operands for relational operatorA subscript is probably being treated as numeric rather than string. Consider using the ord() function.
domain violationA subscript name used is not the same as the original declaration of the variable, equation or parameter. If your really need to do this, consider an alias.
more/less indicesThe number of subscripts is not the same as the original declaration of the variable, equation or parameter.
uncontrolled setA subscript is dangling, i.e. the index of neither that of a sum nor that of a system of constraints
set under control alreadyA subscript is simultaneously used in two ways -- probably as the index of both a sum and a system of constraints. If you really need to do this, consider an alias.
licensing errorYour licenses do not permit solving the specified model, probably because you have exceeded the size limits of the student version

If a review of the errors is not enough to find the problems in a GAMS model, consider the extensive debug print options outlined in Part IV.

Part II: Indexing and Symbolic Parameters

The real power of GAMS modeling comes not with simple models like the examples above, but in being able to handle large numbers of variables, constants and constraints through indexing with subscripts and using symbolic names for model parameters. This section introduces the basic methods for using indexing and parameters, and Part III treats more complex cases.

Example of GAMS Input with Parameters and Subscripts

The following example illustrates all the most common elements. Subsequent sections provide further details and discuss refinements.

Consider a facilities location problem in the form (SUM denotes the usual sigma for summations):

min  SUMi SUMj djci,jxi,j + s SUMi fiyi
s.t. SUMi xi,j = 1 
     SUMj xi,j <= 5yi
     yLA + yATL <= 1
     xi,j >= 0
     yi = 0 or 1

for all j
for all i

for all i,j
for all i

where xi,j and yi are the decision variables for i=LA,CHI,ATL and j=1,...,5. The rest of the symbols in the model are constant parameters with s=100, and ci,j, dj and fi as shown in the following table:

ci,j
j=1j=2j=3j=4j=5 fi
i=LA 249383.1
i=CHI 600123.1
i=ATL 142033.1
dj 110151219

The corresponding GAMS input would be


* Facilities location example with subscripts and symbolic constants

option optcr=0.0;

sets
i "facilities" /LA, CHI, ATL/,
j "customers" /1 * 5/;

scalar s "scaling constant" /100/;
parameter d(j) "demand at j"
/1 11, 3 15, 4 12, 5 19/;
parameter f(i) "fixed cost at i";
f(i) = 3.1;
table c(i,j) "i to j transportation cost"
     1   2   3   4   5
LA   2   4   9   3   8
CHI  6           1   2
ATL  1   4   2   0   3 ;

free variable cost "total cost";
positive variable x(i,j) "fraction of j serviced by i";
binary variable y(i) "whether i is opened";

equations
obj "min total cost",
switch(i) "switching at i",
sumone(j) "do customer all of j",
laoratl "LA or ATL";

obj..
sum((i,j), d(j)*c(i,j)*x(i,j)) + s*sum(i, f(i)*y(i)) =e= cost;
switch(i)..
sum(j, x(i,j)) =l= card(j)*y(i);
sumone(j)..
sum(i, x(i,j)) =e= 1;
laoratl..
y('LA') + y('ATL') =l= 1;

model facloc /all/;
solve facloc using mip minimizing cost;

Defining Subscripts and Indexes with Sets

Subscript indexes are defined in GAMS with set(s) statements. Each entry declares the name of an index and shows it elements between /'s. All such elements are treated as strings. For example, the i set above consists of strings 'LA', 'CHI' and 'ATL'.

If the set is a sequence of consecutive integers, the shorthand

/ lowerlimit * upperlimit /     gives     lowerlimit,...,upperlimit
Elements of the set are still treated as strings even though they look like integers.

A handy function card( setname ) returns the number of elements in the specified set. Notice that switch(i) constraints in the above example use the value of this function as a model constant.

Subscripted Systems of Variables

Attaching one or more subscript names in parentheses to any variable declaration creates an entity for every combination of subscripts in the sets(s). For example binary variable y(i); in the above facilities location example creates a yi for each i. Similarly, positive variable x(i,j); creates an xi,j for every combination of i and j.

Once a set name has been associated with some a variable, that same index name must normally be used whenever the variable is referenced. Cases where more than one subscript name is needed are handled with aliases (see Domains and Aliases.)

The fact that elements of sets are taken as strings means they must be enclosed in quotes when called out explicitly. For example in the above model, a single side constraint

xLA,3 <= yLA  would be expressed x('LA','3') =l= y('LA');
Leaving out quotes leads to a host of errors even though the 3 seems to be a number.

Subscripted (For Every) Systems of Constraints

Equations may be subscripted in much the same way as variables to implement systems of constraints with one element for each index or combination of indexes. The appropriate subscript or subscripts are simply included in parentheses after both parts of the equation definition. For example, the statements
equation vub(i,j);
vub(i,j)..x(i,j) =l= y(i);
has the effect of enforcing constraints
xi,j <= yi for all i and j

Sometimes indexing is desired over only part of the elements of an index set. For example an equation may exist for all i and all j> i. The $-restriction feature of GAMS, which handles such cases, is outlined in Part III below.

Indexed Summations and Products

Most indexed summations and products are also naturally expressed in terms of defined subscript sets. GAMS operator
sum( subscript range, expression )
computes the sum of the specified expressions of subscripts over all combinations of their elements.

The objective function of the above example illustrates:

obj .. sum((i,j), d(j)*c(i,j)*x(i,j)) + s*sum(i, f(i)*y(i)) =e= cost;
The first summation totals terms djci,jxi,j for all combinations of i and j, and the second sums fiyi over all i.

A similar approach can be used to express indexed products. The operator

prod( subscript range, expression )
returns the product of specified expressions.

Sometimes indexing is desired over only part of the elements of an index set. For example we may want to sum over all i and all j> i. The $-restriction feature of GAMS, which handles such cases, is outlined in Part III below.

Symbolic Parameters

Decision variables are the only necessarily symbolic quantities of mathematical programs, but it is usually convenient to also use symbolic names for constants and parameters. Such symbolic parameters may be employed freely in GAMS encodings, both with and without subscripts.

When the parameter has no subscripts, the scalar statement is used. For example, the statement

scalar s "scaling constant" /100/;
in the above example defines a constant s=100. As usual, information between the double quotes is explanatory text, and the assigned value is placed between slashes.

Subscripted symbolic parameters may be defined in a similar way with parameter statements. For example the above statement

parameter d(j) "demand for j" /1 11, 3 15, 4 12, 5 19/;
defines a constant dj for each j and assigns values to elements j = 1, 3, 4 and 5. Values are assigned in subscript-value pairs separated by commas. Any unmentioned components are automatically set = 0.

When a parameter has more than one subscript, its nonzero elements can be defined in a similar way with subscript combinations concatinated with periods. For example the statement

parameter c(i,j) "i to j transportation cost" /LA.1 2, CHI.1 6, ATL.5 3/;
would define all ci,j constants in the above example and set values for three. Others would default to = 0. (See also the often easier table alternative of the next section.)

The /-delimited value lists may be omitted in all these examples. Values must then be assigned after the declaration by placing parameter names on the left side of an = sign. Some examples include

scalar s;
s = 100;
gives scalar constant s the value 100
parameter f(i);
f(i)=3.1;
makes all parameters fi = 3.1
parameter totc(i);
totc(i) = sum( j, c(i,j) );
computes all parameters totci as sums over j of corresponding ci,j

Notice that, in contrast to decision variables, no suffix is required on parameters.

Parameter Tables (Two or More Subscripts)

When a symbolic parameter has two or more subscript dimensions, it is often easier to use a table statement than a parameter statement to declare the parameter and assign nonzero values.

Subscript set elements are arranged around the borders and nonzero values aligned with them in a matrix. The above example model illustrates for two subscripts:


table c(i,j) "i to j transportation cost"
     1   2   3   4   5
LA   2   4   9   3   8
CHI  6           1   2
ATL  1   4   2   0   3 ;
This statement both defines double-subscripted parameter ci,j and assigns nonzero values. For example, cLA,3 = 9. Unspecified values are taken =0.

If a symbolic parameter has more than two subscripts, some must me concatenated by periods to reduce to a two-dimensional table. For example, the sixteen components of a table yieldi,j,k,l over sets

sets i /A,B/, j /1,2/, k /90,95/, l /Y,Z/;
could be inputed in a table by combining i and j along the vertical axis, and k and l along the horizontal as

table yield(i,j,k,l) "process yield"
        90.Y   90.Z    95.Y    95.Z
A.1                    1.23
A.2
B.1
B.2                            45   ;
Here yieldA,1,95,Y = 1.23, yieldB,2,95,Z = 45, and all other yieldi,j,k,l=0.

Part III: Advanced Index/Subscripting

A wide range of optimization models can be encoded using only the features of GAMS presented so far. Still, extensions are needed in some specialized situations, especially where subscript ranges are not a simple as the "for all" cases treated above. This part of the Notes surveys some of the more advanced subscripting features of GAMS.

$-Restrictions on Subscript Ranges and ord() Functions

Defining variables, parameters, equations, summations, etc. over index sets provides for each combination of elements of the sets. Often only a portion of the combinations should actually be referenced.

GAMS accommodates such situations with a $-operator read to mean "such that". Appending a $-restriction to any subscript(s) makes the operation apply only to subscript combinations satisfying the specified condition. For example,

StatementMeaning
positive variable x(j)$(condition); defines xj for all j satisfying condition
equation switch(i,j);
switch(i,j)$(
condition)..
x(i,j) =l= y(i);
defines an xi,j <= yi constraint for all (i,j) satisfying condition
y.lo(i,j)$(condition) = 10; sets the lower bound of yi,j equal to 10 for all (i,j) satisfying condition
sum( (i,j,k)$(condition), expression ); sums expression over all (i,j,k) satisfying condition

The condition used in a $-restriction can be any sort of logical expression using relational operators over model quantities

OperatorMeaning
lt le eq ne ge gt less than, less than or equal to, equal, not equal, greater than or equal to, greater than
not and or not, and, or

For example the statement

parameter c(i,j)$( a(i) gt 0 and b(j) gt 0 );
defines a parameter ci,j for all (i,j) with both parameter ai > 0 and parameter bj > 0.

Because set elements are treated as strings in GAMS, it is often necessary to convert them to numbers in order to express $-conditions. An ord( ) function is provided for this purpose which returns the ordinal position (beginning with 1) of an element of a set. For example if ci,j are to be summed over all i and all j > i the natural coding sum( (i,j)$( j gt i ), c(i,j) ) produces errors because j and i are not numeric quantities. However, they can be converted with the ord() function (assuming elements of the sets were originally defined in sequence) to obtain correct form

sum( (i,j)$( ord(j) gt ord(i) ), c(i,j) );

Index Lag/Lead Offsets

Particularly with time-expanded models, equations are often needed that deal with elements of sets separated by fixed offsets. For example, an inventory variable it might appear in balance equations for t=1,...,12 of the form
it = it-1 + xt - dt
where xt is the production in period t, and dt is the demand in period t.

Even though it stretches the principle that elements of sets are treated as strings rather than numbers, GAMS allows such equations to be coded

balance(t).. i(t) =e= i(t-1) + x(t) - d(t);
over set t /1*12/. The -1 simply means take the previous element of the set; -2 would mean the second previous; +1 would mean the next element; +2 would mean the element after next; etc.

Subscripted quantities outside the set in such + and - constructions are taken = 0. For example, in the above balance(t), i('1'-1) is assumed =0.

An alternative is to wraparound indexing from one end of a set to another. Double operators ++ and -- are used. Changing the above example in this way to

balance(t).. i(t) =e= i(t--1) + x(t) - d(t);
would make ('1'--1) be 12.

Domains and Aliases

After a GAMS variable, equation or parameter is defined over a subscript set or combination of sets, all subsequent references to it in sums, etc. must have either constant subscripts in quotes or the same set index names in the same sequence. Failure to do so produces a domain violation error.

GAMS provides an alias option to escape this limitation when, for example, a variable is defined as x(j) but later referred to as x(k). The statement

alias (j,k);
makes k another name for the previously defined set j. Thereafter, they may be used interchangeably.

Subsets of Index Sets (Dynamic Sets)

A final way of producing more complex indexing is to define subsets of previously defined sets. The syntax is to define a new set name indexed over the parent set(s), which serves as an indicator function of membership in the subset (true or "on" when in the set, false or "off" when not).

For example, consider a model posed on a network or graph, and let

set i /1 * 4/;
alias (i,j);
define the list of nodes i,j=1,...4. Also assume only arcs (1,2), (1,3), (2,4), (3,2) and (3,4) are present in the digraph of interest.

Declaration

set arc(i,j) / 1.2, 1.3, 2.4, 3.2, 3.4 /;
enumerates the existing arcs in a new subset arc(i,j) defined within the full range of i and j combinations. Then a subsequent
sum( (i,j)$arc(i,j), x(i,j) );
sums only over (i,j) enumerated in the subset. The $arc(i,j) is taken to mean "such that the pair (i,j) belongs to the subset". (See a full example in http://www.ecn.purdue.edu/~rardin/oorbook/software/gams/optoven.gms).

Unlike underlying sets, which must remain "static" through all modeling and computation, subsets are "dynamic", i.e. their membership can be changed as processing evolves. The syntax is simply to assign the values yes or no to particular indices of the set. For example arc(i,j)=yes makes the arc set in the above example complete; all arcs belong to the subset. A later statement arc('3','2')=no would delete arc (3,2).

Dynamic (sub)sets can also be defined by classic set operations on other subsets.

StatementMeaning
sub3(i) = sub1(i) + sub2(i); subset3 = the union of subset1 and subset2
sub3(i) = sub1(i) * sub2(i); subset3 = the intersection of subset1 and subset2
sub3(i) = sub1(i) - sub2(i) subset3 = the set difference of subset1 and subset 2
sub3(i) = not sub1(i); subset3 = the complement of subset1

Part IV: Specialized Input/Output and Options

Supplemental Print

The default .lst file output is usually adequate for beginning users of GAMS. However, many variations are available if needed.

One case is where the user wants to print values not part of the standard output. The display statement is used for this purpose. For example the sequence

parameter dist(i,j);
dist(i,j) = abs( h(i)-h(j) ) + abs( k(i) - k(j) );
display dist;
would compute a distance matrix using previously defined coordinates (hi,ki) for points and then output the results for user information. Such listings of parameter values are not part of the default GAMS output.

Another common use of display statements is to replace for a voluminous default output. First, statement

option solprint = off;
turns off all standard solution output. Then display statements are used to print only results of interest, e.g.
display x.l, budget.m;

Diagnostic Print

When a user is having trouble identifying what is wrong with a model, it may help to activate some of the extensive diagnostic output available in GAMS. In particular,
option limrow = integer;
calls for outputing the first integer rows from each equation (system) defined in the model. Nonzero coefficients are shown along with corresponding variable names. Similarly
option limcol = integer;
causes outputing of nonzero coefficients for the first integer components of each variable defined in the model. These outputs will have terms fully collected and coefficients evaluated so that the user can see if there were errors.

Included Files and Spreadsheet Input

In most simple cases, an entire GAMS model can be contained in a single .gms file. GAMS supports an include capability for more complicated situations where parts of a model definition will be reused in different files, or some parameter data comes from outside sources such as spreadsheet software. Included files are merely inserted as if they were the next lines of .gms input whenever a statement of the form
$include 'includefile.gms'
is encountered. Here includefile.gms (in single quotes) is the name of the .gms file with code to be inserted. Any sequence that would be correct within the main .gms file is acceptable from an included one. Notice that the $include statement does not end with a semicolon because it is a $-command.

This include feature provides a convenient way to import parameter values from spreadsheet software. For example, the main file

sets i /1*2/, t /95*98/;
table sales(i,t)
$include 'sales.gms'
;
could import the following spreadsheet output as included file sales.gms:

        95    96    97   98
1      1.3   2.0   2.7  3.6
2      4.9   4.6   4.3  4.5

Output to a File

GAMS can also send output external files for use by other programs. First a file statement opens an output file, and then put commands write output on the file. For example the sequence
file soln /training.out/;
put soln;
put "final x and y =";
put x.l, y.l;
put /;
opens a file soln as training.out, signifies that the next puts will be to that file, writes text "final x and y =" to the file, and then writes the current values of a variables x and y followed by an end-of-line.

Option Choices

In addition to the few mentioned above, GAMS has many options that can be set with option statements. Ones of common interest include

OptionDescription
decimalsdecimal places in standard outputs
seedpseudo random number seed
limcolcolumns displayed in diagnostic output
limrowrows displayed in diagnostic output
iterlimmaximum iterations per solve
domlimmaximum function domain violations per solve
reslimmaximum time per solve
optcrmaximum fraction suboptimal in MIPs
optcamaximum absolute suboptimality in MIPs
lpLP solver
nlpNLP solver
mipMIP solver
dnlpDNLP solver
midnlpMIDNLP solver
solprintdefault print 'off' or 'on'

All these parameters have default values that are usually satisfactory, but explicit option statements may be used to make a different choice. For example

option lp = cplex;
resets the LP solver to CPLEX.

Part V: Loops and Conditional Statements

Many of the above indexed operations, especially those using $-operators, generate complex loops with internal logical tests. Thus it is not necessary to use explict looping and conditional statements to do most GAMS modeling. Still, the capabilities are provided, and they are sometimes very helpful.

Indexed Loops

The easiest loops are implemented by the loop command, which simply repeats one or more activities for all values of its subscript reference. For example the following sequence solves nonlinear program dsgn from 20 random starts and reports all solutions:
model dsgn /all/;
option solprint = off;
set t /1*20/;
loop( t,
   x.l(j) = uniform( x.lo(j), x.up(j) );
   solve dsgn using nlp minimizing cost;
   display x.l, cost.l;
);
More complicated examples may nest one loop within another, or use $-operators to avoid doing the loop for every value of the indices.

While Loops

Classic while loops can also be implemented to repeat activies until a condition is fulfilled. For example the above multistart search of an NLP could have been written:
model dsgn /all/;
option solprint = off;
scalar t /1/;
while( (t le 20),
   x.l(j) = uniform( x.lo(j), x.up(j) );
   solve dsgn using nlp minimizing cost;
   display x.l, cost.l;
   t = t + 1;
);
Any valid conditional statement can be used to control the loop.

For Loops

Standard for loops are also available in GAMS. The above NLP example illustrates this case too:
model dsgn /all/;
option solprint = off;
scalar t;
for( t = 1 to 20,
   x.l(j) = uniform( x.lo(j), x.up(j) );
   solve dsgn using nlp minimizing cost;
   display x.l, cost.l;
);

If/Elseif/Else Statements

A final standard form of programming command that can be implemented in GAMS is if, if/else, if/elseif or if/elseif/else logical statements. The following sequence illustrates by setting parameter s to +1, 0, or -1, depending on the sign of the current value of variable x:
if( x.l gt 0 ),
   s = 1;
elseif( x.l lt 0 ),
   s = -1;
else
   s = 0;
);

Model Outcome Status Conditions

Any of the conditions discussed above in the section on $-operations can be employed to control while loops, and if/else/else logic. In addition, it is often convenient to be able to check the status of the last solve of a model. That model status is available as quantity modelname.modelstat. The following table shows the possible values:

modelstat valueDescription
1optimal
2locally optimal
3unbounded
4infeasible
5locally infeasible
6incomplete solution, infeasible
7incomplete solution, feasible
8integer solution
9incomplete solution, noninteger
10integer infeasible

Thus, for example, if some statements are to be executed only if the last solve terminated optimal, the following sequence would be appropriate:

model plan /all/;
solve plan using lp minimizing cost;
if( (plan.modelstat eq 1),
   statements
);