GAMSUsersGuide PDF
GAMSUsersGuide PDF
This documentation guides GAMS User through several topics in GAMS system. Some introductions to software systems
are like reference manuals: they describe each command in detail. Others take you step by step through a small number of
examples. This guide uses elements of both approaches.
Introduction and Tutorial - This is a self-contained tutorial that guides you through a single example, a small
transportation model, in some detail: you can quickly investigate the flavor of GAMS by reading it.
Language Basics - This part introduces the components of the GAMS language in an ordered way, interspersed with
detailed examples that are often drawn from the model library. All models from the model library are enclosed in
square parenthesis (for example, [TRNSPORT]). Some specialized material has deliberately been omitted in this
process because the primary aim is to make GAMS accessible to the widest possible audience, especially those without
extensive experience with computers or mathematical programming systems. Some familiarity with quantitative
methods and mathematical representations is assumed.
GAMS Programs - The structure of the GAMS language and its components
Set Definition - The declaration and initialization of sets, subsets, and domain checking.
Data Entry: Parameters, Scalars and Tables - Three basic forms of GAMS data types : Parameters, Scalars and
Tables.
Data Manipulations with Parameters - The declaration and assignment of GAMS parameters.
Variables - The declaration and attributes of GAMS variables.
Equations - The definition and declaration of GAMS equations.
Model and Solve Statements Model - The specificiation of a GAMS model and how to solve it.
GAMS Output - The control of GAMS compilation output, execution output, output produced by a solve
statement, and error reporting.
Conditional Expressions, Assignments and Equations - The conditional assignments, expressions and equations
in GAMS.
Dynamic Sets - The membership assignment, the usage of dollar controls, and set operations.
Sets as Sequences: Ordered Sets - Special features used to deal with a set as if it were a sequence.
The Display Statement - The syntax, control, and label order in display.
The Put Writing Facility - The put writing facility of the GAMS language.
Programming Flow Control Features - The GAMS programing flow control features : loop, if-elseif, while, and
for statements.
Special Language Features - Special features in GAMS that do not translate across solvers, or are specific to
certain smodel types.
iv
Advanced Topics - This part discusses advanced topics and can be studied as needed. Users with large, complex, or
expensive models will find much useful material in this part.
Glossary - An alphabetically list of GAMS terms.
The GAMS Model Library - Introduction of GAMS Model Library.
The GAMS Call - The list and detailed description of GAMS command line parameters.
Dollar Control Options - The list and detailed description of dollar control options.
The Option Statement - The list and detailed description of options.
The Save and Restart Feature - The GAMS save and restart feature and the work file.
Secure Work Files - The access control command, its usage, and obfuscated work files.
Compressed and Encrypted Input Files - The encryption, compression and decompression of GAMS input files.
The Grid and Multi-Threading Solve Facility - The basic concepts and Grid Features.
Extrinsic Functions - The extrinsic function library and comparison with external equations.
External Equations - A facility for connecting code written in different programming languages to equations and
variables in a GAMS model.
GAMS Return Codes - The structure of error codes, the return codes of the GAMS compiler and execution
system, and the driver return codes.
GAMS Data eXchange (GDX) - GAMS Data eXchange (GDX) facilities and utilities for Binary Data Exchange.
Data and Model Exchange with Other Applications - The different ways to exchange data and model between
GAMS and other applications.
* Data Exchange with ASCII Files
* Data Exchange with Excel
* Data Exchange with Databases
* Data Export to HTML and XML Files
* Data and Model Export to LaTeX
* Data Export to Gnuplot
* Data and Model Exchange with MPS files
* Data Exchange with NETGEN and GNETGEN - Network Problems
Stochastic Programming (SP) with EMP - the stochastic programming (SP) extension of GAMS Extended
Mathematical Programming (EMP).
Mathematical Programming System for General Equilibrium analysis (MPSGE) - A mathematical programming
system for general equilibrium analysis which operates as a subsystem within GAMS.
* MPSGE Models in GAMS
* Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
* Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
* A Library of Small Examples for Self-Study
* Comparing the Performance of Flexible Functional Forms
* General Equilibrium with Public Goods
* Kevin O'Rourke: CGE and Economic History
* Linking Implan Social Accounts to MPSGE
* A partial list of publications based on MPSGE
* The MPSGE guide is also available as PDF
Table of Contents
II Language Basics 29
3 GAMS Programs 31
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
vi TABLE OF CONTENTS
4 Set Definition 43
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2 Simple Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.1 The Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.2 Set Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.3 Set Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.4 Associated Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.5 Sequences as Set Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.6 Declarations for Multiple Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3 The Alias Statement: Multiple Names for a Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4 Subsets and Domain Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5 Multi-dimensional Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.1 Mapping One-to-one Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 Mapping Many-to-many Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.3 Projection and Aggregation of Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
6 Singleton Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
7 Variables 75
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.1 The Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
2.2 Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
2.3 Styles for Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
3 Variable Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.1 Bounds on Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.2 Fixing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.3 Activity Levels of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4 Variables in Display and Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.1 Assigning Values to Variable Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.2 Variable Attributes in Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.3 Displaying Variable Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
8 Equations 81
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2 Equation Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2.1 The Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2.2 An Illustrative Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3 Equation Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
viii TABLE OF CONTENTS
18 Glossary 193
41 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE 505
1 An Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
2 The Theory of Consumer Demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
4 Modeling Consumer Demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
4.1 Example 1: Evaluating a Demand Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
4.2 Exercises 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
4.3 Example 2: Evaluating the MRS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
4.4 Exercises 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
4.5 Example 3: Leisure Demand and Labor Supply . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
4.6 Exercises 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
5 The Pure Exchange Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
6 Modeling Pure Exchange with MPSGE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
6.1 Example 4: A 2x2 Exchange Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
6.2 Exercises 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
6.3 Example 5: Import Tariffs and Market Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
6.4 Exercises 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
42 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae 527
1 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
2 The Calibrated Share Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
3 Excercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
4 Flexibility and Non-Separable CES functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
5 Two NNCES calibrations for a 3-input cost functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
6 A Comparison of Locally-Identical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
7 Numerical calibration of NNCES given KLEM elasticities . . . . . . . . . . . . . . . . . . . . . . . . . . 537
8 Calibrating Labor Supply and Savings Demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
9 A Maquette Illustrating Labor Supply and Savings Demand Calibration . . . . . . . . . . . . . . . . . . . 544
Index 561
Part I
Introduction
1 Motivation
Substantial progress was made in the 1950s and 1960s with the development of algorithms and computer codes to solve
large mathematical programming problems. The number of applications of these tools in the 1970s was less then expected,
however, because the solution procedures formed only a small part of the overall modeling effort. A large part of the time
required to develop a model involved data preparation and transformation and report preparation. Each model required many
hours of analyst and programming time to organize the data and write the programs that would transform the data into the
form required by the mathematical programming optimizers. Furthermore, it was difficult to detect and eliminate errors
because the programs that performed the data operations were only accessible to the specialist who wrote them and not to the
analysts in charge of the project.
GAMS was developed to improve on this situation by:
Providing a high-level language for the compact representation of large and complex models
The design of GAMS has incorporated ideas drawn from relational database theory and mathematical programming and
has attempted to merge these ideas to suit the needs of strategic modelers. Relational database theory provides a structured
framework for developing general data organization and transformation capabilities. Mathematical programming provides a
way of describing a problem and a variety of methods for solving it. The following principles were used in designing the
system:
1. All existing algorithmic methods should be available without changing the user's model representation. Introduction of
new methods, or of new implementations of existing methods, should be possible without requiring changes in existing
models. Linear, nonlinear, mixed integer, mixed integer nonlinear optimizations and mixed complementarity problems
can currently be accommodated.
2. The optimization problem should be expressible independently of the data it uses. This separation of logic and data
allows a problem to be increased in size without causing an increase in the complexity of the representation.
4 Introduction
3. The use of the relational data model requires that the allocation of computer resources be automated. This means that
large and complex models can be constructed without the user having to worry about details such as array sizes and
scratch storage.
2.2 Documentation
The GAMS model representation is in a form that can be easily read by people and by computers. This means that the GAMS
program itself is the documentation of the model, and that the separate description required in the past (which was a burden to
maintain, and which was seldom up-to-date) is no longer needed. Moreover, the design of GAMS incorporates the following
features that specifically address the user's documentation needs:
A GAMS model representation is concise, and makes full use of the elegance of the mathematical representation.
All data transformations are specified concisely and algebraically. This means that all data can be entered in their
most elemental form and that all transformations made in constructing the model and in reporting are available for
inspection.
Explanatory text can be made part of the definition of all symbols and is reproduced whenever associated values are
displayed.
All information needed to understand the model is in one document.
Of course some discipline is needed to take full advantage of these design features, but the aim is to make models more
accessible, more understandable, more verifiable, and hence more credible.
2.3 Portability
The GAMS system is designed so that models can be solved on different types of computers with no change. A model
developed on a small personal computer can later be solved on a large mainframe. One person can develop a model that is
later used by others, who may be physically distant from the original developer. In contrast to previous approaches, only one
document need be moved the GAMS statement of the model. It contains all the data and logical specifications needed to
solve the model.
Notation Description
[] the enclosed construct is optional
{} the enclosed construct may be repeated zero or more times
there is an or operator across the arguments on both sides of the symbol
6 Introduction
Chapter 2
1 Introduction
The introductory part of this book ends with a detailed example of the use of GAMS for formulating, solving, and analyzing
a small and simple optimization problem. Richard E. Rosenthal of the Naval Postgraduate School in Monterey, California
wrote it. The example is a quick but complete overview of GAMS and its features. Many references are made to other parts
of the book, but they are only to tell you where to look for more details; the material here can be read profitably without
reference to the rest of the book.
The example is an instance of the transportation problem of linear programming, which has historically served as a 'laboratory
animal' in the development of optimization technology. [See, for example, Dantzig (1963) 1 . ] It is a good choice for
illustrating the power of algebraic modeling languages like GAMS because the transportation problem, no matter how large
the instance at hand, possesses a simple, exploitable algebraic structure. You will see that almost all of the statements in the
GAMS input file we are about to present would remain unchanged if a much larger transportation problem were considered.
In the familiar transportation problem, we are given the supplies at several plants and the demands at several markets for a
single commodity, and we are given the unit costs of shipping the commodity from plants to markets. The economic question
is: how much shipment should there be between each plant and each market so as to minimize total transport cost?
The algebraic representation of this problem is usually presented in a format similar to the following.
Indices:
i = plants
j = markets
Given Data:
ai = supply of commodity of plant i (in cases)
b j = demand for commodity at market j
ci j = cost per unit shipment between plant i and market j
Decision Variables:
1 Dantzig, George B. (1963). Linear Programming and Extensions, Princeton University Press, Princeton N.J.
8 A GAMS Tutorial by Richard E. Rosenthal
Note that this simple example reveals some modeling practices that we regard as good habits in general and that are consistent
with the design of GAMS. First, all the entities of the model are identified (and grouped) by type. Second, the ordering
of entities is chosen so that no symbol is referred to before it is defined. Third, the units of all entities are specified, and,
fourth, the units are chosen to a scale such that the numerical values to be encountered by the optimizer have relatively small
absolute orders of magnitude. (The symbol $K here means thousands of dollars.)
The names of the types of entities may differ among modelers. For example, economists use the terms exogenous variable
and endogenous variable for given data and decision variable, respectively. In GAMS, the terminology adopted is as follows:
indices are called sets, given data are called parameters, decision variables are called variables, and constraints and the
objective function are called equations.
The GAMS representation of the transportation problem closely resembles the algebraic representation above. The most
important difference, however, is that the GAMS version can be read and processed by the computer.
Table 1: Data for the transportation problem (adapted from Dantzig, 1963) illustrates Shipping Distances from Plants to
Markets (1000 miles) as well as Market Demands and Plant Supplies.
As an instance of the transportation problem, suppose there are two canning plants and three markets, with the data given
in table Table 1. Shipping distances are in thousands of miles, and shipping costs are assumed to be $90.00 per case per
thousand miles. The GAMS representation of this problem is as follows:
Sets
i canning plants / seattle, san-diego /
j markets / new-york, chicago, topeka / ;
Parameters
Variables
x(i,j) shipment quantities in cases
z total transportation costs in thousands of dollars ;
Positive Variable x ;
2 Structure of a GAMS Model 9
Equations
cost define objective function
supply(i) observe supply limit at plant i
demand(j) satisfy demand at market j ;
If you submit a file containing the statements above as input to the GAMS program, the transportation model will be
formulated and solved. Details vary on how to invoke GAMS on different of computers, but the simplest ('no frills') way to
call GAMS is to enter the word GAMS followed by the input file's name. You will see a number of terse lines describing the
progress GAMS is making, including the name of the file onto which the output is being written. When GAMS has finished,
examine this file, and if all has gone well the optimal shipments will be displayed at the bottom as follows.
You will also receive the marginal costs (simplex multipliers) below.
chicago topeka
seattle 0.036
san-diego 0.009
These results indicate, for example, that it is optimal to send nothing from Seattle to Topeka, but if you insist on sending one
case it will add .036 $K (or $36.00) to the optimal cost. (Can you prove that this figure is correct from the optimal shipments
and the given data?)
Type Component
Inputs Sets
Declaration
Assignment of members
Type Component
Variables
Declaration
Assignment of type
There are optional input components, such as edit checks for bad data and requests for customized reports of results. Other
optional advanced features include saving and restoring old models, and creating multiple models in a single run, but this
tutorial will discuss only the basic components.
Before treating the individual components, we give a few general remarks.
1. A GAMS model is a collection of statements in the GAMS Language. The only rule governing the ordering of
statements is that an entity of the model cannot be referenced before it is declared to exist.
2. GAMS statements may be laid out typographically in almost any style that is appealing to the user. Multiple lines per
statement, embedded blank lines, and multiple statements per line are allowed. You will get a good idea of what is
allowed from the examples in this tutorial, but precise rules of the road are given in the next Chapter.
3. When you are a beginning GAMS user, you should terminate every statement with a semicolon, as in our examples.
The GAMS compiler does not distinguish between upper-and lowercase letters, so you are free to use either.
4. Documentation is crucial to the usefulness of mathematical models. It is more useful (and most likely to be accurate)
if it is embedded within the model itself rather than written up separately. There are at least two ways to insert
documentation within a GAMS model. First, any line that starts with an asterisk in column 1 is disregarded as a
comment line by the GAMS compiler. Second, perhaps more important, documentary text can be inserted within
specific GAMS statements. All the lowercase words in the transportation model are examples of the second form of
documentation.
5. As you can see from the list of input components above, the creation of GAMS entities involves two steps: a declaration
and an assignment or definition. Declaration means declaring the existence of something and giving it a name.
Assignment or definition means giving something a specific value or form. In the case of equations, you must make the
declaration and definition in separate GAMS statements. For all other GAMS entities, however, you have the option of
making declarations and assignments in the same statement or separately.
6. The names given to the entities of the model must start with a letter and can be followed by up to thirty more letters or
digits.
3 Sets
Sets are the basic building blocks of a GAMS model, corresponding exactly to the indices in the algebraic representations of
models. The Transportation example above contains just one Set statement:
4 Data 11
Sets
i canning plants / seattle, san-diego /
j markets / new-york, chicago, topeka / ;
The effect of this statement is probably self-evident. We declared two sets and gave them the names i and j. We also assigned
members to the sets as follows:
i = {Seattle, San Diego}
j = {New York, Chicago, Topeka}.
You should note the typographical differences between the GAMS format and the usual mathematical format for listing the
elements of a set. GAMS uses slashes '/' rather than curly braces '{}' to delineate the set simply because not all computer
keyboards have keys for curly braces. Note also that multiword names like 'New York' are not allowed, so hyphens are
inserted.
The lowercase words in the sets statement above are called text. Text is optional. It is there only for internal documentation,
serving no formal purpose in the model. The GAMS compiler makes no attempt to interpret the text, but it saves the text and
'parrots' it back to you at various times for your convenience.
It was not necessary to combine the creation of sets i and j in one statement. We could have put them into separate statements
as follows:
The placement of blank spaces and lines (as well as the choice of upper- or lowercase) is up to you. Each GAMS user tends
to develop individual stylistic conventions. (The use of the singular set is also up to you. Using set in a statement that
makes a single declaration and sets in one that makes several is good English, but GAMS treats the singular and plural
synonymously.)
A convenient feature to use when you are assigning members to a set is the asterisk. It applies to cases when the elements
follow a sequence. For example, the following are valid set statements in GAMS.
Alias (t,tp);
the name tp is like a t 0 in mathematical notation. It is useful in models that are concerned with the interactions of elements
within the same set.
The sets i, j, t, and m in the statements above are examples of static sets, i.e., they are assigned their members directly by the
user and do not change. GAMS has several capabilities for creating dynamic sets, which acquire their members through the
execution of set-theoretic and logical operations. Dynamic sets are discussed in Chapter Dynamic Sets. Another valuable
advanced feature is multidimensional sets, which are discussed in Section Multi-dimensional Sets.
4 Data
The GAMS model of the transportation problem demonstrates all of the three fundamentally different formats that are
allowable for entering data. The three formats are:
12 A GAMS Tutorial by Richard E. Rosenthal
Lists
Tables
Direct assignments
The next three sub-sections will discuss each of these formats in turn.
Parameters
This statement has several effects. Again, they may be self-evident, but it is worthwhile to analyze them in detail. The
statement declares the existence of two parameters, gives them the names a and b, and declares their domains to be i and j,
respectively. (A domain is the set, or tuple of sets, over which a parameter, variable, or equation is defined.) The statement
also gives documentary text for each parameter and assigns values of a(i) and b(j) for each element of i and j. It is
perfectly acceptable to break this one statement into two, if you prefer, as follows.
Here are some points to remember when using the list format.
1. The list of domain elements and their respective parameter values can be laid out in almost any way you like. The only
rules are that the entire list must be enclosed in slashes and that the element-value pairs must be separated by commas
or entered on separate lines.
2. There is no semicolon separating the element-value list from the name, domain, and text that precede it. This is because
the same statement is being used for declaration and assignment when you use the list format. (An element-value list
by itself is not interpretable by GAMS and will result in an error message.)
3. The GAMS compiler has an unusual feature called domain checking, which verifies that each domain element in the
list is in fact a member of the appropriate set. For example, if you were to spell 'Seattle' correctly in the statement
declaring Set i but misspell it as 'Seatle' in a subsequent element-value list, the GAMS compiler would give you an
error message that the element 'Seatle' does not belong to the set i.
4. Zero is the default value for all parameters. Therefore, you only need to include the nonzero entries in the element-value
list, and these can be entered in any order .
4 Data 13
5. A scalar is regarded as a parameter that has no domain. It can be declared and assigned with a Scalar statement
containing a degenerate list of only one value, as in the following statement from the transportation model.
If a parameter's domain has two or more dimensions, it can still have its values entered by the list format. This is very useful
for entering arrays that are sparse (having few non-zeros) and super-sparse (having few distinct non-zeros).
The effect of this statement is to declare the parameter d and to specify its domain as the set of ordered pairs in the Cartesian
product of i and j. The values of d are also given in this statement under the appropriate heading. If there are blank entries
in the table, they are interpreted as zeroes.
As in the list format, GAMS will perform domain checking to make sure that the row and column names of the table are
members of the appropriate sets. Formats for entering tables with more columns than you can fit on one line and for entering
tables with more than two dimensions are given in Chapter Data Entry: Parameters, Scalars and Tables.
It is important to emphasize the presence of the semicolon at the end of the first line. Without it, the GAMS compiler would
attempt to interpret both lines as parts of the same statement. (GAMS would fail to discern a valid interpretation, so it would
send you a terse but helpful error message.)
The effects of the first statement above are to declare the parameter c, to specify the domain (i,j), and to provide some
documentary text. The second statement assigns to c(i,j) the product of the values of the parameters f and d(i,j).
Naturally, this is legal in GAMS only if you have already assigned values to f and d(i,j) in previous statements.
The direct assignment above applies to all (i,j) pairs in the domain of c. If you wish to make assignments for specific
elements in the domain, you enclose the element names in quotes. For example,
c(Seattle,New-York) = 0.40;
comfortable writing assignment statements in GAMS. (Notice, however, that GAMS has some efficiencies shared by neither
FORTRAN nor C. For example, we were able to assign c(i,j) values for all (i,j) pairs without constructing 'do loops'.)
The GAMS standard operations and supplied functions are given later. Here are some examples of valid assignments. In all
cases, assume the left-hand-side parameter has already been declared and the right-hand-side parameters have already been
assigned values in previous statements.
csquared = sqr(c);
e = m*csquared;
w = l/lamda;
eoq(i) = sqrt( 2*demand(i)*ordcost(i)/holdcost(i));
t(i) = min(p(i), q(i)/r(i), log(s(i)));
euclidean(i,j) = qrt(sqr(xi(i) - xi(j) + sqr(x2(i) - x2(j)));
present(j) = future(j)*exp(-interest*time(j));
The summation and product operators to be introduced later can also be used in direct assignments.
5 Variables
The decision variables (or endogenous variables ) of a GAMS-expressed model must be declared with a Variables statement.
Each variable is given a name, a domain if appropriate, and (optionally) text. The transportation model contains the following
example of a Variables statement.
Variables
x(i,j) shipment quantities in cases
z total transportation costs in thousands of dollars ;
This statement results in the declaration of a shipment variable for each (i,j) pair. (You will see in Chapter Equations, how
GAMS can handle the typical real-world situation in which only a subset of the (i,j) pairs is allowable for shipment.)
The z variable is declared without a domain because it is a scalar quantity. Every GAMS optimization model must contain
one such variable to serve as the quantity to be minimized or maximized.
Once declared, every variable must be assigned a type. The permissible types are given in table Table 3.
Table 3 : Permissible variable types
The variable that serves as the quantity to be optimized must be a scalar and must be of the free type. In our transportation
example, z is kept free by default, but x(i,j) is constrained to non-negativity by the following statement.
Positive variable x ;
Note that the domain of x should not be repeated in the type assignment. All entries in the domain automatically have the
same variable type.
Section The .lo, .l, .up, .m Database describes how to assign lower bounds, upper bounds, and initial values to variables
6 Equations 15
6 Equations
The power of algebraic modeling languages like GAMS is most apparent in the creation of the equations and inequalities that
comprise the model under construction. This is because whenever a group of equations or inequalities has the same algebraic
structure, all the members of the group are created simultaneously, not individually.
Equations
cost define objective function
supply(i) observe supply limit at plant i
demand(j) satisfy demand at market j ;
Keep in mind that the word Equation has a broad meaning in GAMS. It encompasses both equality and inequality
relationships, and a GAMS equation with a single name can refer to one or several of these relationships. For example, cost
has no domain so it is a single equation, but supply refers to a set of inequalities defined over the domain i.
Sum(j, x(i,j))
that is equivalent to j xi j .
A slightly more complex summation is used in the following example:
Sum((i,j), c(i,j)*x(i,j))
that is equivalent to i j ci j xi j .
The last expression could also have been written as a nested summation as follows:
In Section The Dollar Condition, we describe how to use the dollar operator to impose restrictions on the summation operator
so that only the elements of i and j that satisfy specified conditions are included in the summation.
Products are defined in GAMS using exactly the same format as summations, replacing Sum by Prod. For example,
is equivalent to: j xi j .
Summation and product operators may be used in direct assignment statements for parameters. For example,
16 A GAMS Tutorial by Richard E. Rosenthal
Equation definitions are the most complex statements in GAMS in terms of their variety. The components of an equation
definition are, in order:
2. The domain
5. Left-hand-side expression
7. Right-hand-side expression
The power to create multiple equations with a single GAMS statement is controlled by the domain. For example, the
definition for the demand constraint will result in the creation of one constraint for each element of the domain j, as
shown in the following excerpt from the GAMS output.
DEMAND(new-york)..X(seattle,new-york) + X(san-diego,new-york)=G=325 ;
DEMAND(chicago).. X(seattle,chicago) + X(san-diego,chicago) =G=300 ;
DEMAND(topeka).. X(seattle,topeka) + X(san-diego,topeka) =G=275 ;
The key idea here is that the definition of the demand constraints is exactly the same whether we are solving the
toy-sized example above or a 20,000-node real-world problem. In either case, the user enters just one generic equation
algebraically, and GAMS creates the specific equations that are appropriate for the model instance at hand. (Using
some other optimization packages, something like the extract above would be part of the input, not the output.)
In many real-world problems, some of the members of an equation domain need to be omitted or differentiated from the
pattern of the others because of an exception of some kind. GAMS can readily accommodate this loss of structure using
a powerful feature known as the dollar or 'such-that' operator, which is not illustrated here. The domain restriction
feature can be absolutely essential for keeping the size of a real-world model within the range of solvability.
It is important to understand the difference between the symbols '=' and '=e='. The '=' symbol is used only in direct
assignments, and the '=e=' symbol is used only in equation definitions. These two contexts are very different. A direct
assignment gives a desired value to a parameter before the solver is called. An equation definition also describes a
desired relationship, but it cannot be satisfied until after the solver is called. It follows that equation definitions must
contain variables and direct assignments must not.
Variables can appear on the left or right-hand side of an equation or both. The same variable can appear in an equation
more than once. The GAMS processor will automatically convert the equation to its equivalent standard form (variables
on the left, no duplicate appearances) before calling the solver.
An equation definition can appear anywhere in the GAMS input, provided the equation and all variables and parameters
to which it refers are previously declared. (Note that it is permissible for a parameter appearing in the equation to be
assigned or reassigned a value after the definition. This is useful when doing multiple model runs with one GAMS
input.) The equations need not be defined in the same order in which they are declared.
7 Objective Function
This is just a reminder that GAMS has no explicit entity called the objective function. To specify the function to be optimized,
you must create a variable, which is free (unconstrained in sign) and scalar-valued (has no domain) and which appears in an
equation definition that equates it to the objective function.
This statement may seem superfluous, but it is useful to advanced users who may create several models in one GAMS run. If
we were to use the explicit list rather than the shortcut /all/, the statement would be written as
The domains are omitted from the list since they are not part of the equation name. The list option is used when only a subset
of the existing equations comprises a specific model (or sub-model) being generated.
Once a model has been declared and assigned equations, we are ready to call the solver. This is done with a solve statement,
which in our example is written as
Solution Description
lp for linear programming
18 A GAMS Tutorial by Richard E. Rosenthal
Solution Description
qcp for quadratic constraint programming
nlp for nonlinear programming
dnlp for nonlinear programming with discontinuous derivatives
mip for mixed integer programming
rmip for relaxed mixed integer programming
miqcp for mixed integer quadratic constraint programming
rmiqcp for relaxed mixed integer quadratic constraint programming
minlp for mixed integer nonlinear programming
rminlp for relaxed mixed integer nonlinear programming
mcp for mixed complementarity problems
mpec for mathematical programs with equilibrium constraints
rmpec for relaxed mathematical program with equilibrium constraints
cns for constrained nonlinear systems
emp for extended mathematical programming
9 Display Statements
The solve statement will cause several things to happen when executed. The specific instance of interest of the model will be
generated, the appropriate data structures for inputting this problem to the solver will be created, the solver will be invoked,
and the output from the solver will be printed to a file. To get the optimal values of the primal and/or dual variables, we can
look at the solver output, or, if we wish, we can request a display of these results from GAMS. Our example contains the
following statement:
that calls for a printout of the final levels, x.l, and marginal (or reduced costs), x.m, of the shipment variables, x(i,j).
GAMS will automatically format this printout in to dimensional tables with appropriate headings.
x.up(i,j) = capacity(i,j) ;
x.lo(i,j) = 10.0 ;
x.up(seattle,new-york) = 1.2*capacity(seattle,new-york) ;
It is assumed in the first and third examples that capacity(i,j) is a parameter that was previously declared and assigned
values. These statements must appear after the variable declaration and before the Solve statement. All the mathematical
expressions available for direct assignments are usable on the right-hand side.
In nonlinear programming it is very important for the modeler to help the solver by specifying as narrow a range as possible
between lower and upper bound. It is also very helpful to specify an initial solution from which the solver can start searching
for the optimum. For example, in a constrained inventory model, the variables are quantity(i), and it is known that the
optimal solution to the unconstrained version of the problem is a parameter called eoq(i). As a guess for the optimum of
the constrained problem we enter
quantity.l(i) = 0.5*eoq(i) ;
(The default initial level is zero unless zero is not within the bounded range, in which case it is the bound closest to zero.)
It is important to understand that the .lo and .up fields are entirely under the control of the GAMS user. The .l and .m
fields, in contrast, can be initialized by the user but are then controlled by the solver.
Appending these commands to the original transportation problem input results in the following output:
For an example involving marginal, we briefly consider the ratio constraints that commonly appear in blending and refining
problems. These linear programming models are concerned with determining the optimal amount of each of several available
raw materials to put into each of several desired finished products. Let y(i,j) be the variable for the number of tons of raw
material i put into finished product j. Suppose the ratio constraint is that no product can consist of more than 25 percent of
one ingredient, that is,
Unfortunately, this relaxed constraint has no realistic significance. The constraint we are interested in relaxing (or tightening)
is the nonlinear form of the ration constraint. For example, we would like to know the marginal benefit arising from changing
the ratio constraint to
We can in fact obtain the desired marginals by entering the following transformation on the undesired marginals:
Notice that the assignment statement for amr accesses both .m and .l records from the database. The idea behind the
transformation is to notice that
is equivalent to
11 GAMS Output
The default output of a GAMS run is extensive and informative. For a complete discussion, see Chapter GAMS Output. This
tutorial discusses output partially as follows:
Echo Print
Reference Maps
Status Reports
Error Messages
Model Statistics
Solution Reports
A great deal of unnecessary anxiety has been caused by textbooks and users' manuals that give the reader the false impression
that flawless use of advanced software should be easy for anyone with a positive pulse rate. GAMS is designed with the
understanding that even the most experienced users will make errors. GAMS attempts to catch the errors as soon as possible
and to minimize their consequences.
11 GAMS Output 21
Whether or not errors prevent your optimization problem from being solved, the first section of output from a GAMS run is
an echo, or copy, of your input file. For the sake of future reference, GAMS puts line numbers on the left-hand side of the
echo. For our transportation example, which luckily contained no errors, the echo print is as follows:
3 Sets
4 i canning plants / seattle, san-diego /
5 j markets / new-york, chicago, topeka / ;
6
7 Parameters
8
9 a(i) capacity of plant i in cases
10 / seattle 350
11 san-diego 600 /
12
13 b(j) demand at market j in cases
14 / new-york 325
15 chicago 300
16 topeka 275 / ;
17
18 Table d(i,j) distance in thousands of miles
19 new-york chicago topeka
20 seattle 2.5 1.7 1.8
21 san-diego 2.5 1.8 1.4 ;
22
23 Scalar f freight in dollars per case per thousand miles /90/ ;
24
25 Parameter c(i,j) transport cost in thousands of dollars per case;
26
27 c(i,j) = f * d(i,j) / 1000 ;
28
29 Variables
30 x(i,j) shipment quantities in cases
31 z total transportation costs in thousands of dollars ;
32
33 Positive Variable x ;
34
35 Equations
36 cost define objective function
37 supply(i) observe supply limit at plant i
38 demand(j) satisfy demand at market j ;
39
40 cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ;
41
42 supply(i) .. sum(j, x(i,j)) =l= a(i) ;
43
44 demand(j) .. sum(i, x(i,j)) =g= b(j) ;
45
46 Model transport /all/ ;
47
48 Solve transport using lp minimizing z ;
49
50 Display x.l, x.m ;
51
22 A GAMS Tutorial by Richard E. Rosenthal
The reason this echo print starts with line number 3 rather than line number 1 is because the input file contains two dollar-
print-control statements. This type of instruction controls the output printing, but since it has nothing to do with defining the
optimization model, it is omitted from the echo. The dollar print controls must start in column 1.
The $title statement causes the subsequent text to be printed at the top of each page of output. The $offupper statement is
needed for the echo to contain mixed upper- and lowercase. Other available instructions are given in Chapter Dollar Control
Options.
Unfortunately, you cannot always expect error messages to be so accurate in their advice. The compiler cannot
read your mind. It will at times fail to comprehend your intentions, so learn to detect the causes of errors by
picking up the clues that abound in the GAMS output. For example, the missing semicolon could have been
detected by looking up the c entry in the cross-reference list (to be explained in the next section) and noticing
that it was never assigned.
SYMBOL TYPE REFERENCES
C PARAM DECLARED 15 REF 17
Example 3 : Many errors are caused merely by spelling mistakes and are caught before they can be damaging. For example,
with 'Seattle' spelled in the table differently from the way it was introduced in the set declaration, we get the following
error message.
4 sets
5 i canning plants /seattle, san-diego /
6 j markets /new-york, chicago, topeka / ;
7
8 table d(i,j) distance in thousand of miles
9 new-york chicago topeka
10 seatle 2.5 1.7 1.8
**** $170
11 san-diego 2.5 1.8 1.4 ;
Error Message
170 DOMAIN VIOLATION FOR ELEMENT
Example 4 : Similarly, if we mistakenly enter dem(j) instead of b(j) as the right-hand side of the demand constraint, the
result is
45 demand(j) .. sum(i, x(i,j) ) =g= dem(j) ;
**** $140
Error Message
140 UNKNOWN SYMBOL, ENTERED AS PARAMETER
Example 5 : The next example is a mathematical error, which is sometimes committed by novice modelers and which
GAMS is adept at catching. The following is mathematically inconsistent and, hence, is not an interpretable statement.
The first reference map is a cross-reference map such as one finds in most modern compilers. It is an alphabetical, cross-
referenced list of all the entities (sets, parameters, variables, and equations) of the model. The list shows the type of each
entity and a coded reference for each appearance of the entity in the input. The cross-reference map for our transportation
example is as follows (we do not display all tables).
For example, the cross-reference list tells us that the symbol A is a parameter that was declared in line10, defined (assigned
value) in line 11, and referenced in line 43. The symbol I has a more complicated entry in the cross-reference list. It is shown
to be a set that was declared and defined in line 5. It is referenced once in lines 10, 19, 26, 28, 31, 38, 45 and referenced
twice in lines 41 and 43. Set I is also used as a controlling index in a summation, equation definition or direct parameter
assignment in lines 28, 41, 43 and 45.
For the GAMS novice, the detailed analysis of the cross-reference list may not be important. Perhaps the most likely benefit
he or she will get from the reference maps will be the discovery of an unwanted entity that mistakenly entered the model
owing to a punctuation or syntax error.
The second part of the reference map is a list of model entities grouped by type and listed with their associated documentary
text. For example, this list is as follows.
sets
i canning plants
j markets
parameters
a capacity of plant i in cases
b demand at market j in cases
c transport cost in 1000s of dollars per case
d distance in thousands of miles
f freight in dollars per case per thousand miles
variables
11 GAMS Output 25
equations
cost define objective function
demand satisfy demand at market j
supply observe supply limit at plant i
models
transport
Once you succeed in building an input file devoid of compilation errors, GAMS is able to generate a model. The question
remains, and only you can answer it, does GAMS generate the model you intended?
The equation listing is probably the best device for studying this extremely important question.
A product of the solve command, the equation listing shows the specific instance of the model that is created when the current
values of the sets and parameters are plugged into the general algebraic form of the model. For example, the generic demand
constraint given in the input file for the transportation model is
The default output is a maximum of three specific equations for each generic equation. To change the default, insert an input
statement prior to the solve statement:
option limrow = r ;
where c is the desired number of columns. (Setting limrow and limcol to 0 is a good way to save paper after your model
has been debugged.)
In nonlinear models, the GAMS equation listing shows first-order Taylor approximations of the nonlinear equations. The
approximations are taken at the starting values of the variables.
The last section of output that GAMS produces before invoking the solver is a group of statistics about the model's size, as
shown below for the transportation example.
26 A GAMS Tutorial by Richard E. Rosenthal
MODEL STATISTICS
The BLOCK counts refer to the number of generic equations and variables. The SINGLE counts refer to individual rows and
columns in the specific model instance being generated. For nonlinear models, some other statistics are given to describe the
degree of non-linearity in the problem.
S O L V E S U M M A R Y
The status reports are preceded by the same string as an error message, so you should probably develop the habit of
searching for all occurrences of this string whenever you look at an output file for the first time. The desired solver status
is 1 NORMAL COMPLETION, but there are other possibilities, documented in Section Output Produced by a Solve Statement,
which relate to various types of errors and mishaps.
There are eleven possible model status's, including the usual linear programming termination states (1 OPTIMAL, 3
UNBOUNDED, 4 INFEASIBLE), and others relating to nonlinear and integer programming. In nonlinear programming, the
status to look for is 2 LOCALLY OPTIMAL. The most the software can guarantee for nonlinear programming is a local
optimum. The user is responsible for analyzing the convexity of the problem to determine whether local optimality is
sufficient for global optimality.
In integer programming, the status to look for is 8 INTEGER SOLUTION. This means that a feasible integer solution has been
found. More detail follows as to whether the solution meets the relative and absolute optimality tolerances that the user
specifies.
The single dots '.' in the output represent zeroes. The entry EPS, which stands for epsilon, mean very small but nonzero. In
this case, EPS indicates degeneracy. (The slack variable for the Seattle supply constraint is in the basis at zero level. The
marginal is marked with EPS rather than zero to facilitate restarting the optimizer from the old basis.)
If the solvers results contain either infeasibilities or marginal costs of the wrong sign, then the offending entries are marked
with INFES or NOPT, respectively. If the problem terminates unbounded, then the rows and columns corresponding to extreme
rays are marked UNBND.
At the end of the solvers solution report is a very important report summary, which gives a tally of the total number of
non-optimal, infeasible, and unbounded rows and columns. For our example, the report summary shows all zero tallies as
desired.
After the solver's report is written, control is returned from the solver back to GAMS. All the levels and marginals obtained by
the solver are entered into the GAMS database in the .l and .m fields. These values can then be transformed and displayed
in any desired report. As noted earlier, the user merely lists the quantities to be displayed, and GAMS automatically formats
and labels an appropriate array. For example, the input statement.
chicago topeka
seattle 0.036
san-diego 0.009
As seen in reference maps, equation listings, solution reports, and optional displays, GAMS saves the documentary text and
'parrots' it back throughout the output to help keep the model well documented.
12 Summary
This tutorial has demonstrated several of the design features of GAMS that enable you to build practical optimization models
quickly and effectively. The following discussion summarizes the advantages of using an algebraic modeling language such
as GAMS versus a matrix generator or conversational solver.
By using an algebra-based notation, you can describe an optimization model to a computer nearly as easily as you can
describe it to another mathematically trained person.
Because an algebraic description of a problem has generality, most of the statements in a GAMS model are reusable
when new instances of the same or related problems arise. This is especially important in environments where models
are constantly changing.
You save time and reduce generation errors by creating whole sets of closely related constraints in one statement.
You can save time and reduce input errors by providing formulae for calculating the data rather than entering them
explicitly.
The model is self-documenting. Since the tasks of model development and model documentation can be done
simultaneously, the modeler is much more likely to be conscientious about keeping the documentation accurate and up
to date.
The output of GAMS is easy to read and use. The solution report from the solver is automatically reformatted so that
related equations and variables are grouped together and appropriately labeled. Also, the display command allows
you to modify and tabulate results very easily.
If you are teaching or learning modeling, you can benefit from the insistence of the GAMS compiler that every equation
be mathematically consistent. Even if you are an experienced modeler, the hundreds of ways in which errors are
detected should greatly reduce development time.
By using the dollar operator and other advanced features not covered in this tutorial, one can efficiently implement
large-scale models. Specific applications of the dollar operator include the
1. It can enforce logical restrictions on the allowable combinations of indices for the variables and equations to
be included in the model. You can thereby screen out unnecessary rows and columns and keep the size of the
problem within the range of solvability.
2. It can be used to build complex summations and products, which can then be used in equations or customized
reports.
3. It can be used for issuing warning messages or for terminating prematurely conditioned upon context-specific
data edits.
Part II
Language Basics
Chapter 3
GAMS Programs
1 Introduction
This chapter provides a look at the structure of the GAMS language and its components. It should be emphasized again
that GAMS is a programming language, and that programs must be written in the language to use it. A GAMS program is
contained in a disk file, which is normally constructed with a text editor of choice. When GAMS is 'run', the file containing
the program (the input file) is submitted to be processed. After this processing has finished the results, which are in the output
file(s), can be inspected with a text editor. On many machines a few terse lines appear on the screen while GAMS runs,
keeping the user informed about progress and error detection. But it is the responsibility of the user to inspect the output file
carefully to see the results and to diagnose any errors.
The first time or casual reader can skip this chapter: the discussion of specific parts of the language in the next Chapters does
not assume an understanding of this chapter.
statement;
statement;
statement; statement; statement;
the words that you are now reading is an example of a very
long statement which is stretched over two lines;
Blanks and end-of-lines can generally be used freely between individual symbols or words. GAMS is not case sensitive,
meaning that lower and upper case letters can be mixed freely but are treated identically. Up to 255 characters can be placed
on a line and completely blank lines can be inserted for easier reading.
Not all lines are a part of the GAMS language. Two special symbols, the asterisk '' and the dollar symbol '$' can be used
in the first position on a line to indicate a non-language input line. An asterisk in column one means that the line will not be
32 GAMS Programs
processed, but treated as a comment. A dollar symbol in the same position indicates that compiler options are contained in
the rest of the line.
Multiple files can be used as input through the use of the $include facility described in Chapter Dollar Control Options . In
short, the statement,
$include file1
inserts the contents of the specified file (file1 in this case) at the location of the call. A more complex versions of this is the
$batinclude which is described in Chapter Dollar Control Options .
A declaration statement describes the class of symbol. Often initial value are provided in a declaration, and then it may be
called a definition. The specification of symbolic relationships for an equation is a definition. The declaration and definition
statements are:
acronym
alias
equation declaration
equation definition
model
parameter
scalar
set
table
variable
Execution statements are instructions to carry out actions such as data transformation, model solution, and report generation.
The execution statements are:
abort
assignment
display
execute
for
loop
option
repeat
2 The Structure of GAMS Programs 33
solve
while
Although there is great freedom about the order in which statements can be placed in a GAMS program, certain orders are
commonly used. The two most common arrangements are discussed in the next sub-section.
Solution:
Solve
Displays
For example, sets and parameters may be declared first with the statements
set c "crops" ;
parameter yield "crop yield" ;
The first statement declares that the identifier c is a set and the second defines the elements in the set
Attention
Sets and parameters used in the equations must be declared before the equations are specified; they can be defined,
however, after the equation specifications but before a specific equation is used in a solve statement. This gives GAMS
programs substantial organizational flexibility.
acronyms
equations
models
parameters
sets
variables
Scalars and tables are not separate data types but are a shorthand way to declare a symbol to be a parameter, and to use
a particular format for initializing the numeric data.
Definitions have common characteristics, for example:
The domain list and the text are always optional characteristics. Other examples are:
In the last example a number of identifiers (separated by commas) are declared in one statement.
4 Language Items
Before proceeding with more language details, a few basic symbols need to be defined and the rules for recognizing and
writing them in GAMS established. These basic symbols are often called lexical elements and form the building blocks of the
language. They are:
characters
comments
delimiters
identifiers (indents)
labels
numbers
Attention
As noted previously, we can use any mix of lower and upper case. GAMS makes no distinction between upper and
lower case.
4.1 Characters
A few characters are not allowed in a GAMS program because they are illegal or ambiguous on some machines. Generally
all unprintable and control characters are illegal. The only place where any character is legal is in an '$ontext-$offtext' block
as illustrated in the section on comments below. For completeness the full set of legal characters are listed in Table 1. Most
of the uncommon punctuation characters are not part of the language, but can be used freely in text or comments.
Table 1 Legal Characters
abort
acronym
acronyms
alias
all
and
assign
binary
card
diag
display
else
eps
eq
equation
4 Language Items 37
equations
file
files
for
free
ge
gt
if
inf
integer
le
loop
lt
maximizing
minimizing
model
models
na
ne
negative
no
not
option
options
or
ord
parameter
parameters
positive
prod
putpage
puttl
repeat
sameas
38 GAMS Programs
scalar
scalars
semicont
semiint
set
sets
smax
smin
solve
sos1
sos2
sum
system
table
then
until
using
variable
variables
while
xor
yes
..
=l=
=g=
=e=
=n=
=x=
=c=
--
++
4 Language Items 39
4.3 Identifiers
Identifiers are the names given to sets, parameters, variables, models, etc. GAMS requires an identifier to start with a letter
followed by more letters or digits. The length of an identifier is currently limited to 63 characters. Identifiers can only contain
alphanumeric characters (letters or numbers). Examples of legal identifiers are:
15 $casg milk&meat
Attention
A name used for one data type cannot be reused for another.
4.4 Labels
Labels are set elements. They may be up to 63 characters long and can be used in quoted or unquoted form.
The unquoted form is simpler to use but places restrictions on characters used, in that any unquoted label must start with a
letter or digit and can only be followed by letters, digits, or the sign characters + and -. Examples of unquoted labels are:
In quoted labels, quotes are used to delimit the label, which may begin with and/or include any legal character. Either single
or double quotes can be used but the closing quote has to match the opening one. A label quoted with double quotes can
contain a single quote (and vice versa). Most experienced users avoid quoted labels because they can be tedious to enter and
confusing to read. There are a couple of special circumstances. If one wants to make a label stand out, then one can, for
instance, put asterisks in it and indent it. A more subtle example is that GAMS keywords can be used as labels if they are
quoted. If one needs to use labels like no, ne or sum then they will have to be quoted. Examples of quoted labels are:
Attention
Labels do not have a value. The label '1986' does not have the numerical value 1986 and the label '01' is different from
the label '1'.
The rules for constructing identifiers and labels are shown in the following table.
Table 2 Rules for constructing identifiers and labels
4.5 Text
Identifiers and simple labels can also be associated with a line of descriptive text. This text is more than a comment: it is
retained by GAMS and is displayed whenever results are written for the identifier.
Text can be quoted or unquoted. Quoted text can contain any character except the quote character used. Single or double
quotes can be used but must match. Text has to fit on one line and cannot exceed 80 characters in length. Text used in
unquoted form must follow a number of mild restrictions. Unquoted text cannot start with a reserved word, '..' or '=' and
must not include semicolon ';', commas ',', or slashes '/'. End of lines terminate a text. These restrictions are a direct
consequence of the GAMS syntax and are usually followed naturally by the user. Some examples are:
this is text
final product shipment (tpy)
"quoted text containing otherwise illegal characters ; /,"
use single quotes to put a "double" quote in text
4.6 Numbers
Numeric values are entered in a style similar to that used in other computer languages
Attention
Blanks can not be used in a number: GAMS treats a blank as a separator.
The common distinction between real and integer data types does not exist in GAMS. If a number is used without
a decimal point it is still stored as a real number.
In addition, GAMS uses an extended range arithmetic that contains special symbols for infinity ( INF), negative infinity
(-INF), undefined (UNDF), epsilon (EPS), and not available ( NA). One cannot enter UNDF; it is only produced by an operation
that does not have a proper result, such as division by zero. All the other special symbols can be entered and used as if they
were ordinary numbers.
The following example shows various legal ways of entering numbers:
The letter e denotes the well-known scientific notation allowing convenient representation of very large or small numbers.
For example:
Attention
GAMS uses a smaller range of numbers than many computers are able to handle. This has been done to ensure
that GAMS programs will behave in the same way on a wide variety of machines, including personal computers.
A good general rule is to avoid using or creating numbers with absolute values greater than 1.0e+20.
A number can be entered with up to ten significant digits on all machines, and more on some.
5 Summary 41
4.7 Delimiters
As mentioned before, statements are separated by a semicolon ';'. However, if the next statement begins with a reserved
word (often called keyword in succeeding chapters), then GAMS does not require that the semicolon be used.
The characters comma ',' and slash '/' are used as delimiters in data lists, to be introduced later. The comma terminates a
data element (as does an end-of-line) and the slash terminates a data list.
4.8 Comments
A comment is an explanatory text that is not processed or retained by the computer. There are three ways to include comments
in a GAMS program.
1. The first, already mentioned above, is to start a line with an asterisk '' in the first character position. The remaining
characters on the line are ignored but printed on the output file.
2. The second is to use special 'block' delimiters that cause GAMS to ignore an entire section of the program. The $
symbol must be in the first character position. The choice between the two ways is a matter of individual taste or utility.
The example below illustrates the use of the block comment.
$ontext
Following a $ontext directive in column 1 all lines are
ignored by GAMS but printed on the output file until the matching $offtext is encountered, also
in column 1. This facility is often used to logically remove parts of programs
that are not used every time, such as statements producing voluminous reports.
Every $ontext must have a matching $offtext in the same file
$offtext
1. The third style of comment allows embedding a comment within a line. It must be enabled with the compiler option
$inlinecom or $eolcom as in the following example.
$eolcom #
$inlinecom {}
x = 1 ; # this is a comment
y = 2 ; { this is also a comment } z = 3 ;
5 Summary
This completes the discussion of the components of the GAMS language. Many unfamiliar terms used in this chapter have
been further explained in the Glossary.
42 GAMS Programs
Chapter 4
Set Definition
1 Introduction
Sets are fundamental building blocks in any GAMS model. They allow the model to be succinctly stated and easily read.
In this chapter we will discuss how sets are declared and initialized. There are some more advanced set concepts, such as
assignments to sets as well as lag and lead operations, but these are not introduced until much later in the book. However the
topics covered in this chapter will be enough to provide a good start on most models.
2 Simple Sets
A set S that contains the elements a, b and c is written, using normal mathematical notation, as:
S = {a, b, c}
In GAMS notation, because of character set limitations, the same set must be written as
set S /a, b, c/
The set statement begins with the keyword set (or sets). S is the name of the set, and its members are a, b, and c. They
are labels, but are often referred to as elements or members.
set name is the internal name of the set (also called an identifier) in GAMS. The accompanying text is used to describe the
set or element immediately preceding it.
25 $currency food&drink
In quoted labels, quotes are used to delimit the label, which may begin with and/or include any legal character. Either single
or double quotes can be used but the closing quote has to match the opening one. A label quoted with double quotes can
contain a single quote (and vice versa). Most experienced users avoid quoted labels because they can be tedious to enter and
confusing to read. There are a couple of special circumstances. If one wants to make a label stand out, then to put asterisks in
it and indent it, as below, is common. A more subtle example is that it is possible to use GAMS keywords as labels if they are
quoted. If one need to use labels like no, ne or sum then they will have to be quoted.
Examples of quoted labels are:
Attention
Labels do not have a value. The label '1986' does not have the numerical value 1986 and the label '01' is different
from the label '1'.
Each element in a set must be separated from other elements by a comma or by an end-of-line. In contrast, each element is
separated from any associated text by a blank.
Consider the following example from the Egyptian fertilizer model [FERTS], where the set of fertilizer nutrients could be
written as
or as
set cq "nutrients" / N
P2O5 / ;
The order in which the set members are listed is normally not important. However, if the members represent, for example,
time periods, then it may be useful to refer to next or previous member. There are special operations to do this, and they will
be discussed in Chapter Sets as Sequences: Ordered Sets. For now, it is enough to remember that the order in which set
elements are specified is not relevant, unless and until some operation implying order is used. At that time, the rules change,
and the set becomes what we will later call an ordered set.
Notice that text may have embedded blanks, and may include special characters such as parentheses. There are, however,
restrictions on special characters in text. Include slashes, commas or semicolons only if the text is enclosed in quotes. A set
definition like
will cause errors since the slash between dollars and ounce will signal the beginning of the set declaration, and the GAMS
compiler will treat ounce as the name of the first element. Further, the slash before gold-price will be treated as the end of the
set definition, and gold-price will be treated as a new set. However, by enclosing the explanatory text in quotes, this problem
is avoided. The following text is valid:
The asterisk '' plays a special role in set definitions. It is used to relieve the tedium of typing a sequence of elements for a
set, and to make intent clearer. For example in a simulation model there might be ten annual time periods from 1991 to 2000.
Instead of typing ten years, the elements of this set can be written as
which means that the set includes the ten elements 1991, 1992,...,2000. GAMS builds up these label lists by looking at the
differences between the two labels. If the only characters that differ are digits, with the number L formed by these digits in
the left and R in the right, then a label is constructed for every integer in the sequence L to R. Any non-numeric differences or
other inconsistencies cause errors.
The following example illustrates the most general form of the 'asterisked' definition:
although the sets, which have 20 members each, have 11 members in common. As a last example, the following are both
illegal because they are not consistent with the rule given above for making lists :
Note one last time that set elements (often referred to as labels) can contain the sign characters '-' and '+' as well as letters
and numbers.
46 Set Definition
sets
s "Sector" / manuf
agri
services
government /
r "regions" / north
eastcoast
midwest
sunbelt / ;
and a second name for the set c is established with either of the following statements
where cp is the new set that can be used instead of the original set c.
Attention
The newly introduced set can be used as an alternative name for the original set, and will always contain only the same
elements as the original set.
The alias statement can be used to introduce more than one new name for the original set.
where the new sets cp, cpp, cppp are all new names for the original set c.
Attention
The order of the sets in the alias statement does not matter. The only restriction set by GAMS is that exactly one of the
sets in the statement be defined earlier. All the other sets are introduced by the alias statement.
We will not demonstrate the use of set aliases until later. Just remember they are used for cases when a set has to be referred
to by more than one name.
4 Subsets and Domain Checking 47
set
i "all sectors" / light-ind, food+agr, heavy-ind, services /
t(i) "traded sectors" / light-ind, food+agr, heavy-ind /
nt "non-traded sectors" / services / ;
Some types of economic activity, for example exporting and importing, may be logically restricted to a subset of all sectors.
In order to model the trade balance, for example, we need to know which sectors are traded, and one obvious way is to
list them explicitly, as in the definition of the set t above. The specification t(i) means that each member of the set t
must also be a member of the set i. GAMS will enforce this relationship, which is called domain checking. Obviously the
order of declaration is important: the membership of i must be known before t is declared for checking to be done. There
will be much more on this topic in succeeding chapters. For now it is important to note that domain checking will find any
spelling errors that might be made in establishing the members of the set t.These would cause errors in the model if they
went undetected.
It is legal but unwise to define a subset without reference to the larger set, as is done above for the set nt. If services were
misspelled no error would be marked, but the model would give incorrect results. So we urge you to use domain checking
whenever possible. It catches errors and allows you to write models that are conceptually cleaner because logical relationships
are made explicit.
This completes the discussion of sets in which the elements are simple. This is sufficient for most GAMS applications;
however, there are a variety of problems for which it is useful to have sets that are defined in terms of two or more other sets.
5 Multi-dimensional Sets
It is often necessary to provide mappings between elements of different sets. For this purpose, GAMS allows the use of
multi-dimensional sets.
Attention
GAMS allows sets with up to 20 dimensions.
The next two sub-sections explain how to express one-to-one and many-to-many mappings between sets.
set c "countries"
/ jamaica
haiti
guyana
brazil / ;
48 Set Definition
set p "ports"
/ kingston
s-domingo
georgetown
belem / ;
Then a set can be created to associate each port with its country, viz.,
The dot between kingston and jamaica is used to create one such pair. Blanks may be used freely around the dot for
readability. The set ptoc has four elements, and each element consists of a port-country pair. The notation (p,c) after the
set name ptoc indicates that the first member of each pair must be a member of the set p of ports, and that the second must
be in the set c of countries. This is a second example of domain checking. GAMS will check the set elements to ensure that
all members belong to the appropriate sets.
set i / a, b /
j / c, d, e /
ij1(i,j) /a.c, a.d/
ij2(i,j) /a.c, b.c/
ij3(i,j) /a.c, b.c, a.d, b.d/ ;
ij1 represents a one-to-many mapping where one element of i maps onto many elements of j.
ij2 represents a many-to-one mapping where many elements of i map onto one element of j.
ij3 is the most general case where many elements of i map on to many elements of j.
These sets can be written compactly as
set i / a, b /
j / c, d, e /
ij1(i,j) /a.(c,d)/
ij2(i,j) /(a,b).c/
ij3(I,j) /(a,b).(c,d)/ ;
The parenthesis provides a list of elements that can be expanded when creating pairs.
Attention
When complex sets like this are created, it is important to check that the desired set has been obtained. The checking
can be done by using a display statement.
The hash sign (#) followed by the set name is a shorthand for referring to all the elements in a set.
The matching operator (:) can be used to map ordered sets. The operator is similar to the product operator (.), however, in
this case elements are matched pairwise by mapping elements with the same order number.
The below example demonstrates the two concepts.
5 Multi-dimensional Sets 49
set i /a, b/
j /c, d, e/
ij4a(i,j) /a.#j/
ij4b(i,j) /a.c, a.d, a.e/
ij5a(i,j) /#i.#j/
ij5b(i,j) /a.c, a.d, a.e, b.c, b.d, b.e/
ij6a(i,j) /#i:#j/
ij6b(i,j) /a.c, b.d/
ij7a(i,j) /#i:(d*e)/
ij7b(i,j) /a.d, b.e/ ;
Sets which name differ only by the last letter map to the same elements. Consider set ij6a(i,j), where the element with
the highest order number in set i is element b, with order number 2. Similarly, the element with the highest order number in
set j is element e, with order number 3. Hence, element e is without a match and, therefore, not mapped.
The concepts may be generalized to sets with more than two labels per set element. Mathematically these are called 3-tuples,
4-tuples, or more generally, n-tuples.
This section ends with some examples to illustrate definitions of multi-label set elements. Some examples of the compact
representation of sets of n-tuples using combinations of dots, parentheses, and commas are shown in Table 1.
Table 1: Examples of the compact representation of sets
Construct Result
(a,b).c.d a.c.d, b.c.d
(a,b).(c,d) .e a.c.e, b.c.e, a.d.e, b.d.e
(a.13).c (a.1, a.2, a.3).c or a.1.c, a.2.c, a.3.c
13. 13. 13 1.1.1, 1.1.2, 1.1.3, ..., 3.3.3
Note that the asterisk can also be used in conjunction with the dot. Recall, that the elements of the list 14 are {1, 2, 3, 4}.
After the OPTION keyword the left and right items are identifiers with conforming domain declarations. The dimensionality
of the left symbol has to be equal or less the dimensionality of the right side. If the left dimensionality is less than the right
one, the operation performed is an aggregation or projection depending on the data type of the left side. In all cases, indices
are permuted according to the domain definitions. This means that if the domain identifier is unique, then the permutation is
performed unambiguously. However, if the domain has identical domain symbol definitions, then they are permuted right to
left ( <) or left to right ( <=). A later example in this section will clarify this. The following example demonstrates the two
ways to do projection and aggregation on sets:
Sets i / i1*i3 /
j / j1*j2 /
k / k1*k4 /
ijk(i,j,k) / #i.#j.#k /
ij1a(i,j)
ij1b(i,j);
50 Set Definition
Attention
The OPTION statement for projection and aggregation operations can also be applied on parameters!
However, in the special case, where a domain has identical domain symbol definitions, e.g., set i1(i,i,i), a permutation of
the domain is ambiguous. The projection can be performed by permuting the indices from right to left ( <) or left to right (
<=). The below example clarifies the difference:
Set i / i1*i3 /
i1(i,i,i) "Set members" / i1.i2.i3, i3.i3.i1/
i2a(i,i) "i2a(i,ii) = sum(i1(iii,ii,i),1)"
i2b(i,i) "Option i2b<i1 (right to left)"
i3a(i,i) "i3a(i,ii) = sum(i1(i,ii,iii),1)"
i3b(i,i) "Option i3b<=i1 (left to right)";
Alias (i,ii,iii);
6 Singleton Sets
A singleton set in GAMS is a special set that has at most one element (zero elements are allowed as well). Like other
sets, singleton sets can have up to 20 dimensions.
Set i / a, b, c /;
Singleton Set j / d /
k(i) / b /
l(i,j) / c.d /;
A data statement for a singleton set with more than one element will create a compilation error:
7 Summary 51
Error Messages
844 Singleton with more than one entry (see $onStrictSingleton)
Attention
Singleton sets can be especially useful in assignment statements since they don't need to be controlled by an
controlling index nor an indexed operator. More information about this can be found in chapter Data Manipulations
with Parameters.
7 Summary
In GAMS, a simple set consists of a set name and the elements of the set. Both the name and the elements may have
associated text that explains the name or the elements in more detail. More complex sets have elements that are pairs or even
n-tuples. These sets with pairs and n-tuples are ideal for establishing relationships between the elements in different sets.
GAMS also uses a domain checking capability to help catch labeling inconsistencies and typographical errors made during
the definition of related sets.
The discussion here has been limited to sets whose members are all specified as the set is being declared. For many models
this is all you need to know about sets. Later we will discuss more complicated concepts, such as sets whose membership
changes in different parts of the model (assignment to sets) and other set operations such as unions, complements and
intersections.
52 Set Definition
Chapter 5
1 Introduction
One of the basic design paradigms of the GAMS language has been to use data in its most basic form, which may be scalar,
list oriented, or tables of two or more dimensions. Based on this criterion, three data types are introduced in this chapter.
Type Description
Scalar Single (scalar) data entry.
Parameter List oriented data.
Table Table oriented data. Must involve two or more dimensions.
Each of these data types will be explained in detail in the following sections.
Attention
Initialization of data can only be done once for parameters; thereafter data must be modified with assignment statements.
2 Scalars
The scalar statement is used to declare and (optionally) initialize a GAMS parameter of dimensionality zero. That means
there are no associated sets, and that there is therefore exactly one number associated with the parameter.
Scalar name is the internal name of the scalar (also called an identifier) in GAMS. The accompanying text is used to describe
the element immediately preceding it. Signed num is a signed number and is assigned to be the value of scalar name.
As with all identifiers, scalar name has to start with a letter followed by more letters or digits. It can only contain
alphanumeric characters, and can be up to 63 characters long. Explanatory text must not exceed 254 characters and must all
be contained on the same line as the identifier or label it describes.
54 Data Entry: Parameters, Scalars and Tables
The statement above initializes rho and life, but not irr. Later on another scalar} statement can be used to initialize irr,
or, (looking ahead to a notion that will be developed later), an assignment statement could be used to provide the value:
irr = 0.07;
3 Parameters
While parameter is a data type that encompasses scalars and tables, the discussion in this chapter will focus on the use
of parameters in data entry. List oriented data can be read into GAMS using the parameter statement.
Param name is the internal name of the parameter (also called an identifier) in GAMS. The accompanying text is used to
describe the parameter immediately preceding it. Signed num is a signed number and is declared to be the value of the entry
associated with the corresponding element.
As with all identifiers, param name has to start with a letter followed by more letters or digits. It can only contain
alphanumeric characters, and can be up to 63 long. Explanatory text must not exceed 254 characters and must all be contained
on the same line as the identifier or label it describes.
A parameter may be indexed over one or more sets (the maximum number being 20). The elements in the data should belong
to the set that the parameter is indexed over.
Attention
The default value of a parameter is 0.
Parameter initialization requires a list of data elements, each consisting of a label and a value. Slashes must be used at the
beginning and end of the list, and commas must separate data elements entered more than one to a line. An equals sign or a
blank may be used to separate the label-tuple from its associated value. A parameter can be defined in a similar syntax to that
used for a set.
The fragment below is adapted from [MEXSS]. We also show the set definitions because they make the example clearer.
4 Tables 55
The domain checking specification for dd means that there will be a vector of data associated with it, one number correspond-
ing to every member of the set j listed. The numbers are specified along with the declaration in a format very reminiscent of
the way we specified sets: in this simple case a label followed by a blank separator and then a value. Any of the legal number
entry formats are allowable for the value. The default data value is zero. Since monterrey has been left out of the data list,
then the value associated with dd('monterrey'), the market share in monterrey, would be zero.
We can also put several data elements on a line, separated by commas:
parameter salaries(employee,manager,department)
/anderson .murphy .toy = 6000
hendry .smith .toy = 9000
hoffman .morgan .cosmetics = 8000 / ;
All the mechanisms using asterisks and parenthesized lists that we introduced in our discussion of sets are available here as
well. Below is an artificial example, in which a very small fraction of the total data points are initialized. GAMS will mark
an error if the same label combination (or label-tuple) appears more than once in a data list.
In this example, the twelve elements row1.col2 to row1.col7 and row4.col2 to row4.col7 are all initialized at 12, the
single element row10.col10 at 17, and the seven elements rows1.col10 to row7.col10 at 33. The other 80 elements (out
of a total of 100) remain at their default value, which is 0. This example shows the ability of GAMS to provide a concise
initialization, or definition, for a sparse data structure.
4 Tables
Tabular data can be declared and initialized in GAMS using a table statement For 2- and higher-dimensional parameters this
provides a more concise and easier method of data entry than the list based approach, since each label appears only once (at
least in small tables).
56 Data Entry: Parameters, Scalars and Tables
Table name is the internal name of the table (also called an identifier) in GAMS. The accompanying text is used to describe
the parameter immediately preceding it. Signed num is a signed number and is declared to be the value of the entry associated
with the corresponding element.
Attention
The table statement is the only statement in the GAMS language that is not free format.
The relative positions of all entries in a table are significant. This is the only statement where end of line (EOL) has
meaning. The character positions of the numeric table entries must overlap the character positions of the column
headings.
The column section has to fit on one line.
The sequence of signed numbers forming a row must be on the same line.
The element definition of a row can span more than one line.
A specific column can appear only once in the entire table.
The rules for forming simple tables are straightforward. The components of the header line are the by now familiar
keyword-identifier-domain list-text sequence, the domain-list and text being optional. Labels are used on the
top and the left to map out a rectangular grid that contains the data values. The order of labels is unimportant, but if domain
checking has been specified each label must match one in the associated set. Labels must not be repeated, but can be left out
if the corresponding numbers are all zero or not needed. At least one blank must separate all labels and data entries. Blank
entries imply that the default value (zero) will be associated with that label combination.
Attention
Notice also that, in contrast to the set, scalar, and parameter statements, only one identifier can be declared and
initialized in a table statement.
sets i "plants"
/ inchon,ulsan,yosu /
m "productive units" /
atmos-dist "atmospheric distillation unit"
steam-cr "steam cracker"
aromatics "aromatics unit"
hydrodeal "hydrodealkylator" / ;
table ka(m,i) "initial cap. of productive units (100 tons per yr)"
4 Tables 57
In the example above, the row labels are drawn from the set m, and those on the column from the set i. Note that the data for
each row is aligned under the corresponding column headings.
Attention
If there is any uncertainty about which data column a number goes with, GAMS will protest with an error message and
mark the ambiguous entry.
table ka(m,i) initial cap. of productive units (100 tons per yr)
inchon ulsan
atmos-dist 3702 12910
steam-cr 517
aromatics 181
hydrodeal 180
+ yosu
atmos-dist 9875
steam-cr 1207
aromatics 148 ;
The crucial item is the plus '+' sign above the row labels and to the left of the column labels in the continued part of the
table. The row labels have been duplicated, except that hydroreal has been left out, not having associated data. Tables can
be continued as many times as necessary.
All the mechanisms using asterisks and parenthesized lists that were introduced in the discussion of sets are available here as
well. The following example shows how repeated columns or rows can be condensed with asterisks and lists in parentheses
follows. The set membership is not shown, but can easily be inferred.
table upgrade(strat,size,tech)
small.tech1 small.tech2 medium.tech1 medium.tech2
strategy-1 .05 .05 .05 .05
strategy-2 .2 .2 .2 .2
strategy-3 .2 .2 .2 .2
strategy-4 .2 .2
Here we encounter the display statement again. It causes the data associated with upgrade and upgradex to be listed on
the output file.
It is possible to continue the row labels in a table on a second, or even third, line in order to accommodate a reasonable
number of columns. The break must come after a dot, and the rest of each line containing an incomplete row label-tuple must
be blank.
The following example, adapted from [INDUS], is used to illustrate. As written, this table actually has nine columns and
many rows: we have just reproduced a small part to show continued row label-tuples.
5 Acronyms 59
5 Acronyms
An acronym is a special data type that allows the use of strings as values.
Acronym name is an identifier and follows the same naming convention as other identifiers like names of sets, parameters, or
tables.
In the example above, data entries are in the form of strings like 'monday' and 'tuesday'. By declaring each of those
character strings as acronyms, this kind of data entry can be used by GAMS. Sections Acronyms in Assignments and Logical
Conditions Involving Acronyms will explain the further use of acronyms once entered in this form.
6 Summary
In this chapter, the declaration and initialization of parameters with the Scalar, Parameter, and Table statement have been
discussed. Chapter Data Manipulations with Parameters will describe how this data can be changed with assignment
statements.
60 Data Entry: Parameters, Scalars and Tables
Chapter 6
1 Introduction
Data once initialized may require manipulation in order to bring it to the form required in the model. The first part of
this chapter will deal explicitly with parameter manipulation. The rest of the chapter will be devoted to explaining the
ramifications: indexed assignment functions, index operations.
scalar x / 1.5/ ;
x = 1.2;
x = x + 2;
The scalar x is initialized to be 1.5. The second statement changes the value to 1.2, and the third changes it to 3.2. The second
and third statement assignments have the effect of replacing the previous value of x, if any, with a new one.
Note that the same symbol can be used on the left and right of the = sign. The new value is not available until the calculation
is complete, and the operation gives the expected result.
Attention
An assignment cannot start with a reserved word. A semicolon is therefore required as a delimiter before all assignments.
This means that for every member of the set d, a value is assigned to DJ. This can be written in GAMS as follows,
dj(d) = 2.75*da(d) ;
This assignment is known technically as an indexed assignment and set d will be referred to as the controlling index or
controlling set.
Attention
The index sets on the left hand side of the assignment are together called the controlling domain of the assignment
The extension to two or more controlling indices should be obvious. There will be an assignment made for each label
combination that can be constructed using the indices inside the parenthesis. Consider the following example of an assignment
to all 100 data elements of a.
The calculation in the last statement is carried out for each of the 100 unique two-label combinations that can be formed from
the elements of row and col. The first of these is, explicitly,
In the sparse assignments, the parameters p2(i) and p3(i) are replaced with values from parameter d2(i) only if the entry in
d2(i) is nonzero. Hence, the nonzero entry d2('a') replaces entry p2('a') and p3('a').
a(r-7,c-4) = -2.36 ;
This statement assigns a constant value to one element of a. All other elements of a remain unchanged. Either single or
double quotes can be used around the labels.
In general, wherever a set name can occur in an indexed assignment, a subset (or even alabel) can be used instead if you need
to make the assignment over a subset instead of the whole domain.
Consider the following example,
a(row,col-2) = 22 - c(col) ;
GAMS will flag this statement as an error since col is an index on the right hand side of the equation but not on the left.
There would be no error here if col would be a singleton set. Since there is not more than one element in a singleton
set it is not required that this index gets controlled by an controlling index on the left or an indexed operator.
Attention
Each set is counted only once to determine the number of controlling indices. If the same set appears more than once
within the controlling domain, the second and higher occurrences of the set should be aliases of the original set in
order for the number of controlling indices to be equal to the number of indices.
This statement has only one controlling index (row). If one steps through the elements of row one at a time assignments will
be made only to the diagonal entries in b. This will assign exactly 10 values! None of the off-diagonal elements of b will be
filled.
If an additional name is provided for row and used in the second index position, then there will be two controlling indices
and GAMS will make assignments over the full Cartesian product, all 100 values. Consider the following example,
alias(row,rowp) ;
b(row,rowp) = 7.7 - r(row) + r(rowp) ;
64 Data Manipulations with Parameters
Extended range arithmetic will be discussed later in this Section. The values most often used are NA in incomplete tables, and
INF for variable bounds.
Attention
Acronyms contain no numeric value, and are treated as character strings only.
3 Expressions
An expression is an arbitrarily complicated specification for a calculation, with parentheses nested as needed for clarity and
intent. In this section, the discussion of parameter assignments will continue by showing in more detail the expressions that
can be used on the right of the = sign. All numerical facilities available in both standard and extended arithmetic will be
covered.
x = 5 + 4*3**2 :
x = 5 + (4*(3**2)) ;
Attention
It is better to use parentheses than to rely on the precedence of operators, since it prevents errors and clarifies
intentions.
Expressions may be freely continued over many lines: an end-of-line is permissible at any point where a blank
may be used. Blanks may be used for readability around identifiers, parentheses and operator symbols. Blanks are
not allowed within identifiers or numbers, and are significant inside the quote marks used to delimit labels.
3 Expressions 65
xn is equivalent to the function call rPower(x,y) and is calculated inside GAMS as exp[nlog(x)]. This
operation is not defined if x has a negative value, and an error will result. If the possibility of negative values for x
is to be admitted and the exponent is known to be an integer, then a function call, power(x,n), is available.
Three additional capabilities are available to add power and flexibility of expression calculations. They are indexed operations,
functions and extended range arithmetic.
If there is only one controlling index, the parentheses around it can be removed. The most common of these is sum, which
is used to calculate totals over the domain of a set. Consider the following simple example adapted from [ANDEAN] for
illustration.
The smin and smax operations are used to find the largest and smallest values over the domain of the index set or sets. The
index for the smin and smax operators is specified in the same manner as in the index for the sum operator. Consider the
following example to find the largest capacity,
lrgunit = smax((i,m),capacity(i,m));
66 Data Manipulations with Parameters
3.3 Functions
Functions play an important part in the GAMS language, especially for non-linear models. Similar to other programming
languages, GAMS provides a number of built-in (intrinsic) functions. However, GAMS is used in an extremely diverse
set of application areas and this creates frequent requests for the addition of new and often sophisticated and specialized
functions. There is a trade-off between satisfying these requests and avoiding complexity not needed by most users. The
GAMS Function Library Facility (Section Functions) provides the means for managing that trade-off.
Intrinsic Functions
GAMS provides commonly used standard functions such as exponentiation, and logarithmic, and trigonometric functions.
The complete list of available functions is given in the following sections: Mathematical functions, Logical functions, Time
and Calendar functions, and GAMS utility and performance functions. There are cautions to be taken when functions appear
in equations; these are dealt with in Section Expressions in Equation Definitions, Chapter Equations.
In the following sections, the Endogenous Classification (third column) specifies in which models the function can legally
appear. In order of least to most restrictive, the choices are DNLP, NLP, any, none (see Section Classification of Models for
details). Functions classified as any are only permitted with exogenous (constant) arguments.
The following conventions are used for the function arguments. Lower case indicates that an endogenous variable is allowed.
Upper case indicates that a constant argument is required. The arguments in square brackets can be omitted and default
values will be used. Those default values are specified in the function description provided in the second column.
Mathematical functions
execSeed reads or writes the seed for the random number generator none
exp(x) returns the exponential function ex of an expression or term x, see NLP
MathWorld
fact(N) returns the factorial of N where N is an integer any
floor(x) returns the greatest integer number less than or equal to x DNLP
frac(x) returns the fractional part of x DNLP
R
gamma(x) gamma function: (x) = t x1 et dt, see MathWorld DNLP
0
gammaReg(x,a) regularized gamma function, see MathWorld NLP
log(x) returns the natural logarithm, logarithm base e, see MathWorld NLP
logBeta(x,y) log beta function: log(B(x, y)) NLP
logGamma(x) log gamma function as discussed in MathWorld NLP
log10(x) returns the common logarithm, logarithm base 10, see MathWorld NLP
log2(x) returns the binary logarithm, logarithm base 2, see MathWorld NLP
mapVal(x) Function that returns an integer value associated with a numerical any
result that can contain special values. Possible values are:
0 for all regular numbers
4 for UNDF which means undefined
5 for NA which means not available
6 for INF which means plus infinity
7 for -INF which means minus infinity
8 for EPS which means very close to zero but different from zero
max(x1,x2,x3,...) returns the maximum of a set of expressions or terms, the number DNLP
of arguments is not limited
min(x1,x2,x3,...) returns the minimum of a set of expressions or terms, the number DNLP
of arguments is not limited
mod(x,y) returns the remainder of x divided by y DNLP
ncpCM(x,y,Z) function that computes a Chen-Mangasarian smoothing equaling: NLP
xy
x Z ln(1 + e Z )
ncpF(x,y[,Z]) function
p that computes a Fisher smoothing equaling: NLP
(x2 + y2 + 2 Z) x y, Z 0, default setting: Z=0
normal(MEAN,STDDEV) generates a random number with normal distribution with mean none
MEAN and standard deviation STDDEV, see MathWorld
pi value of = 3.141593... any
68 Data Manipulations with Parameters
Logical functions
x(j) = log(y(j)) ;
which replaces the current value of x with the natural logarithm of y over the domain of the index set j.
72 Data Manipulations with Parameters
Extrinsic Functions
Using the GAMS Function Library Facility, functions can be imported from an external library into a GAMS model. Apart
from the import syntax, the imported functions can be used in the same way as intrinsic functions. In particular, they can be
used in equation definitions. Some function libraries are included with the standard GAMS software distribution (see Chapter
Extrinsic Functions) but GAMS users can also create their own libraries using an open programming interface. The GAMS
Test Library instances trilib01, trilib02, trilib03, and cpplib00 are simple examples in the programming languages
C, Delphi, Fortran, and C++ that come with every GAMS system.
Note that the Function Library Facility gives you complete control over naming so that potential name conflicts between
libraries can be avoided. The <InternalLibName> is a sort of handle and will be used to refer to the library inside your
model source code. The <ExternalLibName> is the file name for the shared library that implements the extrinsic functions.
To access libraries included with your GAMS distribution you use the library's name with no path prefix. GAMS will look for
the library in a standard place within the GAMS installation. To access a library that does not reside in this standard place, the
external name should include a relative or absolute path to the library's location. GAMS will search for the shared library you
specify using the mechanisms specific to the host operating system. When processing the $FuncLibIn directive, GAMS will
validate the library, make the included functions available for use, and add a table of the included functions to the listing file.
Before using individual functions you must declare them:
Note that the syntax is similar to that used for declaring Sets, Parameters, Variables and so forth and that the control over
potential naming conflicts extends to the names of the individual functions. The <InternalFuncName> is the one that
you will use in the rest of your model code. The <InternalLibName> is the one that you created with the $FuncLibIn
directive and <FuncName> is the name given the function when the library was created. Once functions have been declared
with the Function statement they may be used exactly like intrinsic functions in the remainder of your model code.
Example
$eolcom //
variable x;
equation e;
The following lines from the listing file describe the library loaded.
A description of the libraries included in the GAMS system can be found in Chapter Extrinsic Functions.
Stateful Libraries
While GAMS intrinsic function are stateless, a user can implement stateful extrinsic functions, meaning that the extrinsic
libraries can have some memory. This can be done in two ways:
Library initialization (see Section Piecewise Polynomial Librarty): At initialization time, the function library reads
some data to provide the necessary functions
Previous function calls (see Section Build Your Own: Trigonometric Library Example, function setMode): Function
calls that alter the execution of successive function calls
The latter type of memory is problematic, since different parts of the GAMS system potentially use different instances
of the function library. For example, if one sets SetMode(1) before the solve statement and one uses GAMS option
solvelink<>5 (see SolveLink), the solver runs in a separate process with a new instance of the function library and
therefore uses the default mode, which is 0. Even worse, if solvelink=0 is set, the GAMS process terminates in order to
execute the solve statement and restarts a new GAMSprocess after the solve which again starts up with a fresh function library
instance, so the function library's memory is lost also in this case. The GAMS Test Library model trilib04 demonstrates
this problem.
GAMS has defined the results of all arithmetic operations and all function values using these special values.
The results can be inspected by running the model library problem [CRAZY]. As one would expect, 1+INF evaluates to
INF, and 1-EPS to 1.
Attention
The mapval function should be used in comparisons involving extended range arithmetic. Only the extended range
arithmetic shown in the table above give non-zero values for mapval. For example, mapval(a) takes a value of 6 if a
is inf. All regular numbers result in a mapval of 0.
The following table shows a selection of results for exponentiation and division for a variety of input parameters.
Table 2: Exponentiation and Division
a b ab power(a,b) a/b
2 2 4 4 1
-2 2 undf 4 -1
2 2.1 4.28 undf .952
na 2.5 na na na
3 0 1 1 undf
inf 2 inf inf inf
2 inf undf undf 0
Attention
One should avoid creating or using numbers with absolute values larger than 1.0E20. If a number is too large, it may
be treated by GAMS as undefined (UNDF), and all values derived from it in a model may be unusable. Always use INF
(or -INF) explicitly for arbitrarily large numbers
When an attempted arithmetic operation is illegal or has undefined results because of the value of arguments (division by zero
is the normal example), an error is reported and the result is set to undefined (UNDF).
From there on, UNDF is treated as a proper data value and does not trigger additional error messages.
Attention
GAMS will not solve a model if an error has been detected, but will terminate with an error condition.
It is thus always necessary to anticipate conditions that will cause errors, such as divide by zero. This is most easily done
with the dollar control, and will be discussed in the next section.
4 Summary
GAMS provides powerful facilities for data manipulation with parallel assignment statements, built-in functions and extended
range arithmetic.
Chapter 7
Variables
1 Introduction
This chapter covers the declaration and manipulation of GAMS variables. Many of the concepts covered in the previous
Chapters are directly applicable here.
A variable is the GAMS name for what are called endogenous variables by economists, columns or activities by linear
programming experts, and decision variables by industrial Operations Research practitioners. They are the entities whose
values are generally unknown until after a model has been solved. A crucial difference between GAMSvariables and columns
in traditional mathematical programming terminology is that one GAMSvariable is likely to be associated with many columns
in the traditional formulation.
2 Variable Declarations
A GAMS variable, like all other identifiers, must be declared before it is referenced.
The declaration of a variable is similar to a set or parameter declaration, in that domain lists and explanatory text are
allowed and recommended, and several variables can be declared in one statement.
Var type is the optional variable type that is explained in detail later. Var name is the internal name of the variable (also
called an identifier) in GAMS. An identifier has to start with a letter followed by more letters or digits. It can only contain
alphanumeric characters, and can be up to 63 characters long. The accompanying text is used to describe the set or element
immediately preceding it. This must not exceed 254 characters and must all be contained on the same line as the identifier it
describes.
One important difference between variable and parameter declarations is that values cannot be initialized in a variable
declaration.
A typical variable statement, adapted from [RAMSEY], is shown below for illustration:
The declaration of k above implies, as usual, that references to k are restricted to the domain of the set t. A model that
includes k will probably have several corresponding variables in the associated mathematical programming problem: most
likely one for each member of t. In this way, very large models can be constructed using a small number of variables. (It is
quite unusual for a model to have as many as 50 distinct variables.) It is still unclear from the declaration whether utility
is not domain checked or whether it is a scalar variable, i.e., one without associated sets. Later references will be used to
settle the issue.
It is important that variable declarations include explanatory text and that this be as descriptive as possible, since the text is
used to annotate the solution output. Note the use of 'per' instead of '/' in the text above: slashes are illegal in all unquoted
text.
The default type is free, which means that if the type of the variable is not specified, it will not be bounded at all. The most
frequently used types are free and positive, for descriptions of variables for which negative values are meaningless, such
as capacities, quantities or prices.
Four additional, although more exotic, variable types - sos1, sos2, semicont and semiint are available in GAMS. These
are explained in Section Types of Discrete Variables .
variables
u(c,i) "purchase of domestic materials (mill units per yr)"
v(c.j) "imports (mill tpy)"
e(c,i) "exports (mill tpy)"
phi "total cost (mill us$)"
phipsi "raw material cost (mill us$)" ;
positive variables u, v, e ;
Attention
It is possible to declare an identifier more than once, but that the second and any subsequent declarations should only
add new information that does not contradict what has already been entered.
The second popular way of declaring variables is to list them in groups by type. We rewrite the example above using this
second method:
free variables
phi "total cost (mill us$)"
phipsi "raw material cost (mill us$)"
positive variables
u(c,i) "purchase of domestic materials (mill units per yr)"
v(c,j) "imports (mill typ)"
e(c,i) "exports (mill typ)" ;
3 Variable Attributes
Another important difference between parameters and variables is that an additional set of keywords can be used to specify
various attributes of variables. A GAMS parameter has one number associated with each unique label combination. A
variable, on the other hand, has seven. They represent:
Attributes Description
.lo The lower bound for the variable. Set by the user either explicitly or through default values.
.up The upper bound for the variable. Set by the user either explicitly or through default values.
.fx The fixed value for the variable.
.l The activity level for the variable. This is also equivalent to the current value of the variable. Receives new
values when a model is solved.
.m The marginal value (also called dual value) for the variable. Receives new values when a model is solved.
.scale This is the scaling factor on the variable. This is normally an issue with nonlinear programming problems
and is discussed in detail in Section Model Scaling - The Scale Option .
.prior This is the branching priority value of a variable. This parameter is used in mixed integer programming
models only, and is discussed in detail later.
The user distinguishes between these suffix numbers when necessary by appending a suffix to the variable name.
All default bounds set at declaration time can be changed using assignment statements.
Attention
For binary and integer variable types, the consequences of the type declaration cannot be completely undone.
Bounds on variables are the responsibility of the user. After variables have been declared, default bounds have already been
assigned: for many purposes, especially in linear models, the default bounds are sufficient. In nonlinear models, on the other
hand, bounds play a far more important role. It may be necessary to provide bounds to prevent undefined operations, such as
division by zero.
78 Variables
It is also often necessary to define a 'reasonable' solution space that will help to make the nonlinear programming problem be
solved more efficiently.
Attention
The lower bound cannot be greater than the upper: if you happen to impose such a condition, GAMS will exit with an
error condition.
GAMS allows the user to set variables through the .fx variable suffix. This is equivalent to the lower bound and upper bound
being equal to the fixed value. Fixed variables can subsequently be freed by changing the lower and upper bounds.
GAMS allows the user to fix the activity levels of variables through the .l variable suffix. These activity levels of the variables
prior to the solve statement serve as initial value for the solver. This is particularly important for nonlinear programming
problems.
Assignment statements operate on one variableattribute at a time, and require the suffix to specify which attribute is being
used. Any index list comes after the suffix.
The following example illustrates the use of assignment statements to set upper bounds for variables.
Note that, in the first statement, the index set covering the domain of x appears after the suffix. The first assignment puts an
upper bound on all variables associated with the identifier x. The statement on the second line bounds one particular entry.
The statement on the last line sets the level values of the variables in c to four times the values in the parameter cinit.
Remember that the order is important in assignments, and notice that the two pairs of statements below produce very different
results. In the first case, the lower bound for c('1985') will be 0.01, but in the second, the lower bound is 1.
Everything works as described in the previous chapter, including the various mechanisms described there of indexed
operations, dollar operations, subset assignments and so on.
4 Variables in Display and Assignment Statements 79
As with parameters, a variable must have some non-default data values associated with it before one can use it in a display
statement or on the right hand side of an assignment statement. After a solve statement (to be discussed later) has been
processed or if non-default values have been set with an assignment statement, this condition is satisfied.
Attention
The .fx suffix is really just a shorthand for .lo and .up and can therefore only be used only on the left-hand side of
an assignment statement.
The output looks similar, except that (of course) the listing shows which of the values is being displayed. Because zeroes,
and especially all zero rows or columns, are suppressed, the patterns seen in the level and marginal displays will be quite
different, since non-zero marginal values are often associated with activity levels of zero.
We should mention here a clarification of our previous discussion of displays. It is actually the default values that are
suppressed on display output. For parameters and variable levels, the default is zero, and so zero entries are not shown. For
bounds, however, the defaults can be non-zero. The default value for the upper bound of a positive variable is +INF, and if
above you also would display v.up, for example, you will see:
80 Variables
If any of the bounds have been changed from the default value, then only the entries for the changed elements will be shown.
This sounds confusing, but since few users display bounds it has not proved troublesome in practice.
5 Summary
Remember that wherever a parameter can appear in a display or an assignment statement, a variable can also appear - provided
that it is qualified with one of the four suffixes. The only places where a variable name can appear without a suffix is in a
variable declaration, as shown here, or in an equation definition, which is discussed in Chapter Equations.
Chapter 8
Equations
1 Introduction
Equations are the GAMS names for the symbolic algebraic relationships that will be used to generate the constraints in the
model. As with variables, one GAMS equation will map into arbitrarily many individual constraints, depending on the
membership of the defining sets.
2 Equation Declarations
A GAMS equation, like all identifiers, must be declared before it can be used.
Eqn name is the internal name of the equation (an identifier) in GAMS. An identifier has to start with a letter followed by
more letters or digits. It can only contain alphanumeric characters, and can be up to 63 characters long. The accompanying
text is used to describe the set or element immediately preceding it. This must not exceed 254 characters and must all be
contained on the same line as the identifier it describes.
There are no modifying keywords as there are with variables, and no initializing data list as there may be with parameters or
sets.
equations
cost total cost definition
invb(q) inventory balance
sbal(q,s) shift employment balance ;
82 Equations
The declaration of the first equation follows the keyword equations. This declaration begins with the name of the equation,
in this case cost, and is followed by the text, namely 'Total cost definition'. The equation cost above is a scalar
equation, which will produce at most one equation in the associated optimization problem.
By contrast, the equation sbal is declared over the sets q (4 members) and s (2 members), and is thus likely to produce
eight individual equations, one for each unique combination of labels. The circumstances under which less than eight
equations might be produced will be discussed in later chapters. It is certainly true, however, that no more than eight equations
will be produced.
3 Equation Definitions
The definitions are the mathematical specification of the equations in the GAMS language. The next sub-section explain
the syntax for an equation definition and this is followed by an illustrative example. The rest of this section is devoted to
discussions about some of the key components of equation definitions.
Eqn name is the name of the equation as in the equation declaration. The two dots '..' are always required between the
equation name and start of the algebra. The expressions in the equation definition can be of the forms discussed in the
Chapters before, but can involve variables as well. Eqn type refers to the symbol between the two expressions that form the
equation, and can be of the following types,
Type Description
=e= Equality: rhs must equal lhs
=g= Greater than: lhs must be greater than or equal to rhs
=l= Less than: lhs must be less than or equal to rhs
=n= No relationships enforced between lhs and rhs. This equation type is rarely used.
=x= External equation. Only supported by selected solvers.
=c= Conic constraint. Only supported by selected solvers.
Attention
As with the assignment statement, equation definitions can be carried over as many lines of input as needed.
Blanks can be inserted to improve readability, and expressions can be arbitrarily complicated.
An equation, once defined, can not be altered or re-defined. If one needs to change the logic, a new equation with
a new name will have to be defined. It is possible, however, to change the meaning of an equation by changing the
data it uses, or by using exception handling mechanisms (dollar operations) built into the definition
Consider the following example, adapted from [MEXSS]. The associated declarations are also included.
Obj is the name of the equation being defined. The =e= symbol means that this is an equality. Any of the following forms of
the equation are mathematically equivalent,
Attention
The arrangement of the terms in the equation is a matter of choice, but often a particular one is chosen because it makes
the model easier to understand.
A scalar equation will produce at most one equation in the associated optimization problem. The equation defined in the last
Section is an example of a scalar equation, which contains only scalar variables. Note that in general, scalar equations may
contain indexed variables operated on by index operators. Consider the following example from [CHENERY].
All the set references in scalar equations are within the scope of index operations - many references can therefore be
included in one equation. However, GAMS allows for equations to be defined over a domain, thereby developing a compact
representation for constraints. The index sets to the left of the '..' are called the domain of definition of the equation.
Attention
Domain checking ensures that the domain over which an equation is defined must be the set or a subset of the set over
which the equation is declared.
Consider the following example of a singly indexed equation, meaning one that produces a separate constraint for each
member of the driving (or controlling) set.
As t has three members, three constraints will be generated , each one specifying separately for each member of t, the
dependence of g on m. Mew and xsi are parameters: the data associated with them are used in building up the individual
constraints. These data do not have to be known when the equation is defined, but do have to be when a model containing the
equation is solved.
The extension to two or more index positions on the left of the '..' should be obvious. There will be one constraint generated
for each label combination that can constructed using the indices inside the parenthesis. Here are two examples from
[AIRCRAFT], a scheduling model.
The domain of definition of both equations is the Cartesian product of j and h: constraints will be generated for every label
pair that can be constructed from the membership of the two sets.
84 Equations
Consider the following example adapted from [CHENERY] showing parentheses and exponentiation,
1. Exogenous arguments: The arguments(s) are known. Parameters and variable attributes (for example, .l and .m
attributes) are used as arguments. The expression is evaluated once when the model is being set up, and all functions
except the random distribution functions uniform and normal are allowed.
2. Endogenous arguments: The arguments are variables and therefore unknown. The function will be evaluated many
times at intermediate points while the model is being solved.
Attention
The occurrence of any function with endogenous arguments implies that the model is not linear.
It is forbidden to use the uniform and normal functions in an equation definition.
Functions with endogenous arguments can be further classified into types listed in Table 1 .
Table 1: Classification of functions with endogenous arguments
Smooth functions can be used routinely in nonlinear models, but non-smooth ones may cause numerical problems and
should be used only if unavoidable, and only in a special model type called dnlp. However, the use of the dnlp model type
is strongly discouraged and the use of binary variables is recommended to model non-smooth functions. Discontinuous
functions are not allowed at all with variable arguments.
5 Data Handling Aspects of Equations 85
A fuller discussion is given in Chapter Model and Solve Statements . For convenience, all the available functions are classified
in Section Functions.
c.lo(t) = 0.01 ;
util .. utility =e= sum(t, beta(t)*log(c(t))) ;
The bounding on c(t) away from 0 prevents the log function from being undefined.
The meaning of the marginal value (.m) in terms of the objective value is discussed in detail in most texts on mathematical
programming. The crude but useful definition is that it is the amount by which the objective function would change if the
equation level were moved one unit.
86 Equations
Chapter 9
1 Introduction
This chapter brings together all the concepts discussed in previous chapters by explaining how to specify a model and solve it.
Model name is the internal name of the model (also called an identifier) in GAMS . The accompanying text is used to
describe the set or element immediately preceding it. Eqn name is the name of an equation that has been declared prior to the
model statement.
As with all identifiers, model name has to start with a letter followed by more letters or digits. It can only contain
alphanumeric characters, and can be up to 63 characters long. Explanatory text must not exceed 80 characters and must all be
contained on the same line as the identifier or label it describes.
An example of a model definition in GAMS is shown below.
The model is called transport and the keyword all is a shorthand for all known (declared) equations.
Several models can be declared (and defined) in one model statement. This is useful when experimenting with different ways
of writing a model, or if one has different models that draw on the same data. Consider the following example, adapted from
[PROLOG], in which different groups of the equations are used in alternative versions of the problem. Three versions are
solved the linear, nonlinear, and 'expenditure' versions. The model statement to define all three is
where cb, rc, etc. are the names of the equations. We will describe below how to obtain the solution to each of the three
models.
find x
F(x) = 0 (9.1)
subject to L x U
G(x) b
where F and x are of equal dimension and the variables x are continuous. The (possibly empty) constraints L x U are
not intended to be binding at the solution, but instead are included to constrain the solution to a particular domain or to
avoid regions where F(x) is undefined. The (possibly empty) constraints G(x) b are intended for the same purpose and are
silently converted to equations with bounded slacks.
The CNS model is a generalization of the square system of equations F(x) = 0. There are a number of advantages to using
the CNS model type (compared to solving as an NLP with a dummy objective, say), including:
A check by GAMS that the model is really square,
solution/model diagnostics by the solver (e.g. singular at solution, locally unique solution),
and potential improvement in solution times, by taking better advantage of the model properties.
The CNS model class is solved with a solve statement of the form:
without the usual objective term. The CNS solver can be selected during installation or with the usual OPTION CNS =
Solver;statement.
For information on CNS solvers that can be used through GAMS see the Solver/Model type Matrix.
Solve Status values
A CNS solver will return one of the following solver status values:
where the definitions are the same as for other model classes. The CNS solver will return one of the following model status
values:
Additional comments
Some special comments relating to CNS models apply:
There is no objective and therefore no marginal values, either for variables or for equations. The solution
listing will therefore not have the MARGINAL column. Any marginal values already stored in the GAMS
database will remain untouched.
A singular model flags a set of linearly dependent rows and columns with DEPND in the solution listing.
The number of dependencies reported is made available by GAMS via the <model>.numdepnd model
attribute. This can be tested in the usual way. Note that a row/column pair for a linear dependence
contributes one to numdepnd. Also note that there may be more linear dependencies than the ones reported.
An infeasible or locally infeasible model, or a singular model with infeasibilities, flags the infeasible
constraints and variables with the usual INFES flag. The number of infeasibilities is available via the usual
<model>.numinfes model attribute.
Mathematically, the Nonlinear Programming with Discontinuous Derivatives (DNLP) Problem looks like:
Minimize f (x)
st g(x) 0
L x U
where x is a vector of variables that are continuous real numbers. f (x) is the objective function, and g(x) represents the
set of constraints. L and U are vectors of lower and upper bounds on the variables. This is the same as NLP , except that
non-smooth functions (abs, min,max) can appear in f (x) and g(x).
For information on DNLP solvers that can be used through GAMS see the Solver/Model type Matrix.
Linear Programming
where x is a vector of variables that are continuous real numbers. cx is the objective function, and Ax b represents the set of
constraints. L and U are vectors of lower and upper bounds on the variables.
GAMS supports both free variables (unrestricted), positive variables, and negative variables. In addition user specified lower
and upper bounds can be provided.
In a GAMS model equations are specified as a combination of less-than-or-equal-to or greater-than-or-equal-to inequalities
and equalities (equal-to constraints).
For information on LP solvers that can be used through GAMS see the Solver/Model type Matrix.
Find z, w, v
such that F(z) = w v
l z u, w 0, v 0
w0 (z l) = 0, v0 (u z) = 0
2 The Model Statement 91
MCP's are a class of mathematical programs which can be formulated in GAMS and solved by one of the MCP solvers that
are hooked up to GAMS: see the Solver/Model type Matrix.
MCP's arise in many application areas including applied economics, game theory, structural engineering and chemical
engineering.
Complementarity problems are easily formulated in the GAMS language. The only additional requirement beyond general
NLP's is the definition of complementarity pairs.
MCP's constitute a fairly general problem class. It encompasses systems of nonlinear equations, non-linear complementarity
problems and finite dimensional variational inequalities. Also inequality-constrained linear, quadratic and nonlinear programs
are MCP's (although for these problems you may expect specialized solvers to do better). For instance, when we set the lower
bounds l to minus infinity and u to plus infinity, both w and v have to be zero. This results in the problem
Find z
such that F(z) = 0
which is a system of non-linear equations.
Mathematically, the Mixed Integer Nonlinear Programming (MINLP) Problem looks like:
Minimize f (x) + Dy
st g(x) + Hy 0
L x U
y = {0, 1, 2, }
where x is a vector of variables that are continuous real numbers. f (x) + Dy is the objective function, and g(x) + Hy represents
the set of constraints. L and U are vectors of lower and upper bounds on the variables.
For information on MINLP solvers that can be used through GAMS see the Solver/Model type Matrix.
Mathematically, the Mixed Integer Linear Programming (MIP) Problem looks like:
Minimize cx + dy
st Ax + By b
L x U
y = {0, 1, 2, }
where x is a vector of variables that are continuous real numbers, and y is a vector in variables that can only take integer
values. cx + dy is the objective function, and Ax + By b represents the set of constraints. L and U are vectors of lower and
upper bounds on the continuous variables, and y = {0, 1, 2, } is the integrality requirement on the integer variables y.
For information on MIP solvers that can be used through GAMS see the Solver/Model type Matrix.
Mathematically, the Mathematical Program with Equilibrium Constraints (MPEC) Problem looks like:
Maximize or Minimize f (x, y)
subject to g(x, y) 0
Lx x Ux
F(x, y) perp to Ly y Uy
where x and y are vectors of continuous real variables. The variables x are often called the control or upper-level variables,
while the variables y are called the state or lower-level variables. f (x, y) is the objective function. g(x, y) represents the set of
92 Model and Solve Statements
traditional (i.e. NLP-type) contraints; in some cases, they can only involve the control variables x. The function F(x, y) and
the bounds Ly and Uy define the equilibrium constraints. If x is fixed, then F(x, y) and the bounds Ly and Uy define an MCP;
the perp-to indicates that such a complementary relationship holds. From this definition, we see that the MPEC model type
contains NLP and MCP models as special cases of MPEC.
While the MPEC model formulation is very general, it also results in problems that are very difficult to solve. Work on
MPEC algorithms is not nearly so advanced as that for the other model types. As a result, the MPEC solvers included in the
GAMS distribution are experimental or beta versions.
For information on MPEC solvers that can be used through GAMS see the Solver/Model type Matrix.
Nonlinear Programming
Minimize f (x)
st g(x) 0
L x U
where x is a vector of variables that are continuous real numbers. f (x) is the objective function, and g(x) represents the set of
constraints. L and U are vectors of lower and upper bounds on the variables.
For information on NLP solvers that can be used through GAMS see the Solver/Model type Matrix.
A Quadratically Constrained Program (QCP) is a special case of the NLP in which all the nonlinearities are required to be
quadratic. As such, any QCP model can also be solved as an NLP. However, most LP vendors provide routines to solve LP
models with a quadratic objective. Some allow quadratic constraints as well. Solving a model using the QCP model type
allows these LP solvers to be used to solve quadratic models as well as linear ones. Some NLP solvers may also take
advantage of the special (quadratic) form when solving QCP models. In case a model with quadratic constraints is passed to
a QCP solver that only allows a quadratic objective, a capability error (solver status 6 CAPABILITY PROBLEMS) will be
returned.
For information on QCP solvers that can be used through GAMS see the Solver/Model type Matrix.
A Mixed Integer Quadratically Constrained Program (MIQCP) is a special case of the MINLP in which all the nonlinearities
are required to be quadratic. For details see the description of the QCP, a special case of the NLP.
For information on MIQCP solvers that can be used through GAMS see the Solver/Model type Matrix.
model_name.attribute
Some of the attributes are mainly used before the solve statement to provide information to GAMS or the solver link. Others
are set by GAMS or the solver link and hence are mainly used after a solve statement.
Moreover, some of the input attributes can also be set globally via an option statement or the command line, e.g.
option reslim = 10
gamsmodel.gms reslim = 10
2 The Model Statement 93
Note that a model specific option takes precedence over the global setting and that a setting via an option statement takes
precedence over one via the command line parameter.
The complete list of model attributes is shown below. The third and fourth column indicate whether there is also a global
option and/or a command line parameter.
integer1 Integer communication cell that can contain any integer number. x x
integer2 Integer communication cell that can contain any integer number. x x
integer3 Integer communication cell that can contain any integer number. x x
integer4 Integer communication cell that can contain any integer number. x x
integer5 Integer communication cell that can contain any integer number. x x
iterLim Iteration limit. The solvers will interrupt the solution process when the iteration x x
count reaches that limit. The default value is 2 billion.
limCol Maximum number of cases written to the LST file for each named variable in a x x
model. The default value is 3.
limRow Maximum number of cases written to the LST file for each named equation in a x x
model. The default value is 3.
MCPRHoldfx This attribute can be set to print a list of rows that are perpendicular to variables x x
removed due to the holdfixed setting when solvin an MCP. Allowable values are:
0: do not print the list (default)
1: print the list
nodLim Node limit. This attribute specifies the maximum number of nodes to process x
in the branch and bound tree for a MIP problem. The default value is 0 and is
interpreted as 'not set'.
optCA Absolute optimality criterion. This attribute specifies an absolute termination x x
tolerance for use in solving all mixed-integer models. The default value is 0.
optCR Relative optimality criterion. This attribute specifies a relative termination toler- x x
ance for use in solving all mixed-integer models. The default value is 0.1.
94 Model and Solve Statements
Priority option. Variables in mixed integer programs can have a priority attribute.
priorOpt
One can use this parameter to specify an order for picking variables to branch on
during a branch and bound search for MIP model solutions. The default value is
0 in which case priorities will not be used.
real1 Real communication cell that can contain any real number. x
real2 Real communication cell that can contain any real number. x
real3 Real communication cell that can contain any real number. x
real4 Real communication cell that can contain any real number. x
real5 Real communication cell that can contain any real number. x
reform Reformulation level. x
resLim Maximum time available in wall clock seconds to solve in seconds. The default x x
value is 1000.
savePoint This parameter tells GAMS to save a point format GDX file that contains the x x
information on the current solution point. One can save the solution information
from the last solve or from every solve. Numeric input with the following values
is expected:
0: no point gdx file is to be saved
1: a point gdx file called model name p.gdxis to be saved from the
last solve in the GAMS model
2: a point gdx file called model name pnn.gdx is to be saved from
every solve in the GAMS model, where nnis the solve number as
determined internally by GAMS
scaleOpt This attribute tells GAMS whether to employ user specified variable and equation
scaling factors. It must be set to a nonzero value if the scaling factors are to be
used.
solPrint This attribute controls the printing of the model solution to the LST x x
file. Note that the corresponding option expects a text, while the use of
model name.solPrintand the command line expect a numeric value. Allowed
are:
0/Off: remove solution listings following solves
1/On: include solution listings following solves
2/Silent: suppress all solution information
The default value is 1 respectively 'On'.
2 The Model Statement 95
solveOpt This attribute tells GAMS how to manage the model solution when only part of the x
variables and equations are in the particular problem being solved. Note that the
corresponding option expects a text, while the use of model name.solveOptand
the command line expect a numeric value. Allowed are:
0/replace: the solution information for all equations appearing in the
model is completely replaced by the new model results; variables are
only replaced if they appear in the final model
1/merge: the solution information for all equations and variables is
merged into the existing solution information; (default)
2/clear: the solution information for all equations appearing in the
model is completely replaced; in addition, variables appearing in the
symbolic equations but removed by conditionals will be removed
There is an example called 'solveopt' in the model library.
sysOut This attribute controls the incorporation of additional solver generated output x x
(that in the solver status file) to the LST file. Note that the corresponding option
expects a text, while the use of model name.solPrintand the command line
expect a numeric value. Allowed are:
0/Off: suppress additional solver generated output (default)
1/On: include additional solver generated output
threads This attribute controls the number of threads or CPU cores to be used by a solver. x x
Allowable values are:
-n: number of cores to leave free for other tasks
0: use all available cores
n: use n cores (will be reduced to the available number of cores if n
is too large)
tolInfeas Infeasibility tolerance for an empty row of the form a.. 0x =e= 0.0001;.
If not set, a tolerance of 10 times the machine precision is used. Empty rows
failing this infeasibility check are flagged with the listing file message 'Equation
infeasible due to rhs value'.
tolInfRep This attribute sets the tolerance for marking infeasible in the equation listing. The
default value is 1.0e-6.
96 Model and Solve Statements
Attribute Description
domUsd Number of domain violations.
etAlg This attribute returns the elapsed time it took to execute the solve algorithm. The time does not include
the time to generate the model, reading and writing of files etc. The time is expressed in seconds of
wall-clock time.
etSolve This attribute returns the elapsed time it took to execute a solve statement in total. This time includes the
model generation time, time to read and write files, time to create the solution report and the time taken
by the actual solve. The time is expressed in seconds of wall-clock time.
etSolver This attribute returns the elapsed time taken by the solver only. This does not include the GAMS model
generation time and time taken to report and load the solution back into the GAMS database. The time is
expressed in seconds of wall-clock time.
handle Every solve gets unique handle number that may be used by handlecollect, handlestatus or handledelete.
See Chapter The Grid and Multi-Threading Solve Facility .
iterUsd Number of iterations used.
line Line number of last solve of the corresponding model
linkUsed Integer number that indicates the value of solveLink used for the last solve
maxInfes Max of infeasibilities
meanInfes Mean of infeasibilities
modelStat Model status. Range from 1 to 19. For details check Section Model Status.
nodUsd The number of nodes used by the MIP solver.
number Model instance serial number. The first model solved gets number 1, the second number 2 etc. The user
can also set a value and the next model solved will get value+1 as number.
numDepnd Number of dependencies in a CNS model.
numDVar Number of discrete variables.
numEqu Number of equations.
numInfes Number of infeasibilities.
numNLIns Number of nonlinear instructions.
numNLNZ Number of nonlinear nonzeros.
numNOpt Number of nonoptimalities.
numNZ Number of nonzero entries in the model coefficient matrix.
numRedef Number of MCP redefinitions.
3 The Solve Statement 97
Attribute Description
numVar Number of variables.
numVarProj Number of bound projections during model generation.
objEst The estimate of the best possible solution for a mixed-integer model.
objVal The objective function value.
procUsed Integer number that indicates the used model type. Possible values are:
1: LP
2: MIP
3: RMIP
4: NLP
5: MCP
6: MPEC
7: RMPEC
8: CNS
9: DNLP
10: RMINLP
11: MINLP
12: QCP
13: MIQCP
14: RMIQCP
15: EMP
Attention
It is important to remember that GAMS itself does not solve your problem, but passes the problem definition to one of
a number of separate solver programs.
Model name is the name of the model as defined by a model statement. Var name is the name of the objective variable that
is being optimized. Model type is one of the model types described before. An example of a solve statement in GAMS is
shown below.
98 Model and Solve Statements
Solve and using are reserved words.Transport is the name of the model, lp is the model type, minimizing is the
direction of optimization, and cost is the objective variable. The opposite of minimizing is maximizing , both reserved
words. Note that an objective variable is used instead of an objective row or function
Attention
The objective variable must be scalar and of type free, and must appear in at least one of the equations in the model.
The next two sub-sections will describe briefly below what happens when a solve statement is processed, and more details on
how the resulting output is to be interpreted will be given in the next chapter. After that sequences of solve statements will be
discussed. The final section will describe options that are important in controlling solve statements.
1. All symbolic equations have been defined and the objective variable is used in at least one of the equations
2. The objective variable is scalar and of type free
3. Each equation fits into the specified problem class (linearity for lp, continuous derivatives for nlp, as we outlined
above)
4. All sets and parameters in the equations have values assigned.
1. The model is translated into the representation required by the solution system to be used.
2. Debugging and comprehension aids are produced and written to the output file (EQUATION LISTING, etc).
3. GAMS verifies that there are no inconsistent bounds or unacceptable values (for example NA or UNDF) in the problem.
4. Any errors detected at this stage cause termination with as much explanation as possible, using the GAMS names for
the identifiers causing the trouble.
5. GAMS passes control to the solution subsystem and waits while the problem is solved.
6. GAMS reports on the status of the solution process and loads solution values back into the GAMS database. This
causes new values to be assigned to the .l and .m fields for all individual equations and variables in the model. A row
by row and column by column listing of the solution is provided by default. Any apparent difficulty with the solution
process will cause explanatory messages to be displayed. Errors caused by forbidden nonlinear operations are reported
at this stage.
The outputs from these steps, including any possible error messages, are discussed in detail in Chapter GAMS Output.
When there is more than one solve statement in your program, GAMS uses as much information as possible from the
previous solution to provide a starting point in the search for the next solution.
qs(upper,fuel-oil,sulfur) = 3.5 ;
solve oil using lp maximizing phi;
report(cr,p,base) = z.l(cr,p) ;
report(sulfur,limit,base) = qs(upper,fuel-oil,sulfur);
qs (upper,fuel-oil,sulfur) = 3.4 ;
solve oil using lp maximizing phi ;
report(cr,p,one) = z.l(cr,p) ;
report(sulfur,limit,one) = qs (upper,fuel-oil,sulfur);
qs(upper,fuel-oil,sulfur) = 5.0 ;
solve oil using lp maximizing phi ;
report(cr,p,two) = z.l(cr,p) ;
report(sulfur,limit,two) = qs(upper,fuel-oil,sulfur);
display report ;
This example shows not only how simply sensitivity analysis can be done, but also how the associated multi-case reporting
can be handled. The parameter qs is used to set the upper bound on the sulfur content in the fuel oil, and the value is
retrieved for the report.
The output from the display is shown below. Notice that there is no production at all if the permissible sulfur content is
lowered. The case attributes have been listed in the row SULFUR.LIMIT. The wild card domain is useful when generating
reports: otherwise it would be necessary to provide special sets containing the labels used in the report. Any mistakes made
100 Model and Solve Statements
in spelling labels used only in the report should be immediately apparent, and their effects should be limited to the report.
Section Global Display Controls , contains more detail on how to arrange reports in a variety of ways.
Another use of multiple solve statements is to permit iterative solution of different blocks of equations, solution values from
the first are used as data in the next. These decomposition methods are useful for certain classes of problems because the
sub-problems being solved are smaller, and therefore more tractable. One of the most common examples of such a method is
the Generalized Bender's Decomposition method.
An example of a problem that is solved in this way is an input-output system with endogenous prices, described in Henaff
(1980) 1 . The model consists of two groups of equations. The first group uses a given final demand vector to determine
the output level in each sector. The second group uses some exogenous process and input-output data to compute sectoral
price levels. Then the resulting prices are used to compute a new vector of final demands, and the two block of equations
are solved again. This iterative procedure is repeated until satisfactory convergence is obtained. Henaff has used GAMS
statements to perform this kind of calculation. The statements that solve the system for the first time and the next iteration are
shown below:
pbar(ta) = (sum(ipd.l(i,ta))/4.);
d(i,t) = (db(i)*g(t))/(pd.l(i,t)/pbar(t)) ;
Mb is a set of material balance (input-output) equations, and output is a total output equation. Dual is a group of price
equations, and totp is an equation that sums all the sectoral prices. The domestic prices pd used in the calculation of the
average price pbar are divided by four because there are four sectors in this example. Also the .l is appended to pd to
indicate that this is the level of the variable in the solution of the model namely in dualmodel. Thus the iterative procedure
uses solution values from one iteration to obtain parameter values for the next one. In particular, both pbar and pd are used
to compute the demand d for the i-th product in time period t, d(i,t). Also, the base year demand db and the growth
factor g are used in that calculation. Then when the new final demand vector d is calculated, the two blocks of equations are
solved again.
1 Henaff, Patrick (1980). emAn Input-Output Model of the French Economy/em, Masters Thesis, Department of Economics, University of Maryland.
5 Making New Solvers Available with GAMS 101
The guarantee that a user has not somehow provided an illegal input specification.
Elaborate documentation, particularly of input formats, is not needed.
Access to the existing community of GAMS users, for marketing or testing.
This completes the discussion of the model and solve statements. In Chapter GAMS Output the various components of
GAMS output are described in some detail.
102 Model and Solve Statements
Chapter 10
GAMS Output
1 Introduction
The output from GAMS contains many aids for checking and comprehending a model. In this chapter the contents of the
output file are discussed. Ways by which the amount of diagnostic output produced can be controlled will also be discussed,
although complete lists of all these controls are not given until later. A small nonlinear model, [ALAN] by Alan S. Manne,
is used to illustrate the output file, and list it piece by piece as we discuss the various components. The possibilities for
extension to large models with voluminous output (which is when the diagnostics are really useful) should be apparent.
The output from a GAMS run is produced on one file, which can be read using any text editor. The default name of this
output file depends on the operating system, but Chapter The GAMS Call describes how this default can be changed. The
display statement, described in detail in Chapter The Display Statement , can be used to export information from the GAMS
program to the listing file.
$Offtext
* This model has been modified for use in the documentation
t-bills 7 /
Positive Variable x;
3 Compilation Output
This is the output produced during the initial check of the program, often referred to as compilation. It contains two or three
parts: the echo print of the program, an explanation of any errors detected, and the maps. The next four sub-sections will
discuss each of these in detail.
Note that the first line number shown is 9. If the lines on the input are counted, it can be seen that this comment line shown
above appears after 8 lines of dollar directives and comments.
The line starting $title has caused text of the users choice to be put on the page header, replacing the default tile, which just
announces GAMS. The following $- directives are used to display more information in the output file and we be discussed.
3 Compilation Output 105
The text within the $ontext-$offtext pair is listed without line numbers, whereas comments starting with asterisks have line
numbers shown. Line numbers always refer to the physical line number in your input file.
Attention
Dollar control directives are only listed if a directive to list them is enabled, or if they contain errors.
10
11 Set i securities /hardware,software,show-biz,t-bills/; alias (i,j);
12
13 Scalar target target mean annual return on portfolio % /10/,
14 lowyield yield of lowest yielding security,
15 highrisk variance of highest security risk ;
16
17 Parameters mean(i) mean annual returns on individual securities (%)
18
19 / hardware 8
20 software 9
21 show-biz 12
22 t-bills 7 /
23
24 Table v(i,j) variance-covariance array (%-squared annual return)
25
26 hardware software show-biz t-bills
27
28 hardware 4 3 -1 0
29 software 3 6 1 0
30 show-biz -1 1 10 0
31 t-bills 0 0 0 0 ;
32
33 lowyield = smin(i, mean(i)) ;
34 highrisk = smax(i, v(i,i)) ;
35 display lowyield, highrisk ;
36
37 Variables x(i) fraction of portfolio invested in asset i
38 variance variance of portfolio
39
40 Positive Variable x;
41
42 Equations fsum fractions must add to 1.0
43 dmean definition of mean return on portfolio
44 dvar definition of variance;
45
46 fsum.. sum(i, x(i)) =e= 1.0 ;
47 dmean.. sum(i, mean(i)*x(i)) =e= target;
48 dvar.. sum(i, x(i)*sum(j,v(i,j)*x(j))) =e= variance;
49
50 Model portfolio / fsum, dmean, dvar / ;
51
52 Solve portfolio using nlp minimizing variance;
That is the end of the echo of the input file. If errors had been detected, the explanatory messages would be found in this
section of the listing file. All discussion of error messages have been grouped in the section Error Reporting .
106 GAMS Output
Symbol Listing
For each symbol, the name and type of the symbol are first provided. For example, the last symbol listed is X which is defined
to be of type VAR. The complete list of data types are given in table Table 1 .
Table 1: List of GAMS data types
Then comes a list of references to the symbol, grouped by reference type and identified by the line number in the output file.
The actual reference can then be found by referring to the echo print of the program, which has line numbers on it. In the
3 Compilation Output 107
case of the symbol X in the example above, the list of references as shown in the symbol reference map are as follows,
DECLARED 37
IMPL-ASN 52
REF 40 46 47 2*48
This means that X is declared on line 37, implicitly assigned through a solve statement on line 52, and referenced on lines
40, 46, and 47. The entry 248 means that there are two references to X on line 48 of the input file .
The complete list of reference types is given below.
Symbol Listing
SETS
I securities
J Aliased with I
PARAMETERS
VARIABLES
EQUATIONS
MODELS
PORTFOLIO
The following map is called the Unique Element Listing. All unique elements are first grouped in entry order and then in
sorted order with their explanatory texts. The unique element listing map can be turned on by entering a line containing
$onuelxref at the beginning of the program.
ELEMENT REFERENCES
This sub-section reviews the most useful of the Dollar Control Directives. These must not be confused with the dollar
exception-handling operators that will be introduced later: the similarity of terminology is unfortunate. These dollar control
directives are compiler directives that can be put in the input file to control the appearance and amount of detail in the output
produced by the GAMS compiler. Directives that do not have following text can be entered many to a line, as shown below
for the map controls.
$offlisting, $onlisting
This directive stops the echo print of the input file. $onlisting restores the default.
$offsymxref, $offsymlist, $onsymxref, $onsymlist
These four directives are used to control the production of symbol maps. Maps are most often turned on or
off at the beginning of the program and left as initially set, but it is possible to produce maps of part of the
program by using a on-map directive followed later by an off-map. The symlist lists all the symbols in the model.
The symxref shows a complete cross-reference list of symbols by number. Both these maps are suppressed by
default.
$offuelxref, $offuellist, $onuelxref, $onuellist
These four directives are used to control the production of Unique Element maps which show set membership
labels. Maps are most often turned on or off at the beginning of the program and left as initially set, but it is
possible to produce maps of part of the program by using a on-map directive followed later by an off-map. The
uellist lists all labels in both GAMS entry and alphabetical order. The uelxref shows a complete cross-reference
list by number. These label maps are suppressed by default.
$offupper, $onupper
4 Execution Output 109
This directive causes the echo print of the portion of the GAMS program following the directive to appear on the
output file in the case that it has been entered in. This is the default on newer GAMS systems. It is necessary if
case conventions have been used in the program, for example to distinguish between variables and equations.
$onupper, will cause all echo print to be in upper case.
$ontext, $offtext
$ontext-$offtext pairs are used to create block comments that are ignored by GAMS . Every $ontext must
have a matching $offtext in the same file. The $offtext must be on a line by itself.
$title 'text'
The text can have up to 80 characters. This causes every page of the output to have the title specified.
Attention
In all dollar control directives, the $ symbol must be in the first character position on the line.
Dollar control directives are dynamic: they affect only what happens after they are encountered, and they can be
set and reset wherever appropriate. They are remembered in continued compilations started from work files.
4 Execution Output
The only output to the listing file while GAMS is executing (performing data manipulations) is from the display statement.
All the user controls available to change the format will be discussed in detail later. The output from the display statement on
line 41 of the example is shown below. Note the wrap of the explanatory text.
If errors are detected because of illegal data operations, a brief message indicating the cause and the line number of the
offending statement will appear.
(LHS = 0)
Attention
The equation listing is an extremely useful debugging aid. It shows the variables that appear in each constraint, and
what the individual coefficients and right-hand-side value evaluate to after the data manipulations have been done.
Most of the listing is self-explanatory. The name, text, and type of constraints are shown. The four dashes are useful for
mechanical searching.
Attention
All the terms that depend on variables are collected on the left, and all the constant terms are combined into one number
on the right, any necessary sign changes being made.
Four places of decimals are shown if necessary, but trailing zeroes following the decimal point are suppressed. E-format is
used to prevent small numbers being displayed as zero.
Attention
The nonlinear equations are treated differently. If the coefficient of a variable in the equation listing is enclosed in
parentheses, then the corresponding constraint is nonlinear, and the value of the coefficient depends on the activity
levels of one or more of the variables. The listing is not algebraic, but shows the partial derivative of each variable
evaluated at their current level values.
Note that, in the equation listing from our example, the equation dvar is nonlinear. A simpler example will help to clarify
the point. Consider the following equation and associated level values.
The coefficient of x is determined by first differentiating the equation above with respect to x. This results in
2(2x.l)power(y.l,3)+ 5, which evaluates to 221. Similarly the coefficient of y is obtained by differentiating
the equation above with respect to y which results in 2(sqr(x.l)3sqr(y.l) + 1.5/sqr(y.l), giving 216.1667.
Notice that the coefficient of y could not have been determined if its level had been left at zero. The attempted division by
zero would have produced an error and premature termination.
The result of evaluating the left-hand-side of the equation at the initial point is shown at the end of each individual equation
listing. In the example above it is 225.5, and the three asterisks() are a warning that the constraint is infeasible at the
starting point.
5 Output Produced by a Solve Statement 111
Attention
The order in which the equations are listed depends on how the model was defined. If it was defined with a list of
equation names, then the listing will be in the order in that list. If it was defined as /all/, then the list will be in the
order of declaration of the equations. The order of the entries for the individual constraints is determined by the label
entry order.
X(hardware)
(.LO, .L, .UP = 0, 0, +INF)
1 FSUM
8 DMEAN
(0) DVAR
X(software)
(.LO, .L, .UP = 0, 0, +INF)
1 FSUM
9 DMEAN
(0) DVAR
X(show-biz)
(.LO, .L, .UP = 0, 0, +INF)
1 FSUM
12 DMEAN
(0) DVAR
VARIANCE
(.LO, .L, .UP = -INF, 0, +INF)
-1 DVAR
Attention
The order in which the variables appear is the order in which they were declared.
MODEL STATISTICS
The BLOCK counts refer to GAMS equations and variables, the SINGLE counts to individual rows and columns in the
problem generated. The NON ZERO ELEMENTS entry refers to the number of non-zero coefficients in the problem matrix.
There are four entries that provide additional information about nonlinear models. The NON LINEAR N-Z entry refers to the
number of nonlinear matrix entries in the model.
All forms of nonlinearity do not have the same level of complexity. For example, xy is a simpler form of nonlinearity than
exp(xy). So, even though both these terms count as 1 nonlinear entry in the matrix, additional information is required
to provide the user with a feel for the complexity of the nonlinearity. GAMS provides the CODE LENGTH entry as a good
yardstick for this purpose. There are two other entries - DERIVATIVE POOL and CONSTANT POOL that provide some more
information about the nonlinearity. In general, the more nonlinear a problem is, the more difficult it is to solve.
The times that follow statistics are also useful. The GENERATION TIME is the time used since the syntax check finished. This
includes the time spent in generating the model. The measurement units are given, and represent ordinary clock time on
personal computers, or central processor usage (CPU) time on other machines.
S O L V E S U M M A R Y
The common part of the solve summary is shown above. It can be found mechanically by searching for four asterisks. The
explanation for the information provided in this section follows.
MODEL PORTFOLIO
5 Output Produced by a Solve Statement 113
TYPE NLP
SOLVER MINOS5
This provides the name of the solver used to solve the model.
OBJECTIVE VARIANCE
DIRECTION MINIMIZE
These provide the solver status and model status for the problem, and are discussed in greater detail at the end of this
subsection.
This provides the value of the objective function at the termination of the solve. If the Solver and Model have the right status,
this value is the optimum value for the problem.
These two entries provide the amount of wall clock time (in seconds) taken by the solver, as well as the upper limit allowed
for the solver. The solver will stop as soon as the limit on time usage has been reached. The default limit on time usage is
1000 seconds. This limit can be changed by entering a line containing the statement option reslim = xx ; in the program
before the solve statement, where xx is the required limit in wall clock seconds.
These two entries provide the number of iterations used by the solver, as well as the upper limit allowed for the solver. The
solver will stop as soon as this limit is reached. The default limit on iterations used is pratically infinity. This limit can be
changed by entering a line containing the statement option iterlim = nn; in the program before the solve statement,
where nn is the required limit on the iterations used.
EVALUATION ERRORS 0 0
These two entries provide the number of numerical errors encountered by the solver, as well as the upper limit allowed
for the solver. These errors result due to numerical problems like division by0. This is suppressed for LP, RMIP, and MIP
models since evaluation errors are not applicable for these model types. The default limit on evaluation errors used is 0. This
limit can be changed by entering a line containing the statement option domlim = nn; in the program before the solve
statement, where nn is the required limit on the evaluation errors allowed.
The SOLVER STATUS and MODEL STATUS require special explanation. The status for the solver (the state of the program)
and the model (what the solution looks like) are characterized, and a complete list of possible MODEL STATUS and SOLVER
STATUS messages is given below.
114 GAMS Output
Model Status
This is used when a CNS model is solved and the solver somehow can be certain that there is only one solution.
The simplest examples are a linear model with a non-singular Jacobian, a triangular model with constant
non-zero elements on the diagonal, and a triangular model where the functions are monotone in the variable on
the diagonal.
16 SOLVED
Locally feasible in a CNS models - this is used when the model is feasible and the Jacobian is non-singular and
we do not know anything about uniqueness.
17 SOLVED SINGULAR
Singular in a CNS models - this is used when the model is feasible (all constraints are satisfied), but the Jacobian
/ Basis is singular. In this case there could be other solutions as well, in the linear case a linear ray and in the
nonlinear case some curve.
18 UNBOUNDED - NO SOLUTION
The model is unbounded and no solution can be provided.
19 INFEASIBLE - NO SOLUTION
The model is infeasible and no solution can be provided.
Solver Status
The next section in the listing file is the part of the solve summary that is particular to the solver program that has been used.
This section normally begins with a message identifying the solver and its authors: MINOS was used in the example here.
There will also be diagnostic messages in plain language if anything unusual was detected, and specific performance details
as well, some of them probably technical. The Solver Manual will help explain these. In case of serious trouble, the GAMS
listing file will contain additional messages printed by the solver. This may help identify the cause of the difficulty. If the
solver messages do not help, a perusal of the solver documentation or help from a more experienced user is recommended.
The solver report from our example follows.
GAMS/MINOS
B. A. Murtagh, University of New South Wales
and
P. E. Gill, W. Murray, M. A. Saunders and M. H. Wright
Systems Optimization Laboratory, Stanford University.
The line 'work space allocated -- 0.04 MB' provides the amount of memory used by the solver for the problem. If the
amount of memory the solver estimates that it needs is not available, GAMS will return a message saying that not enough
memory was allocated. GAMS will also return the maximum amount of memory available on the machine. The user can
direct the solver to use less memory by entering a line containing the statement mymodel.workspace = xx; were mymodel
is the name of the model being solved as specified by the model statement, and xx is the amount of memory in Megabytes.
Note that the solver will attempt to solve the problem with xx MB of memory, however it is not guaranteed to succeed since
the problem may require more memory.
More information can be obtained for a successful run by entering a line containing the statement option sysout = on ;
in the program above the solve statement.
The next section of the listing file is a row-by-row then column-by-column listing of the solutions returned to GAMS by the
solver program. Each individual equation and variable is listed with four pieces of information.
5 Output Produced by a Solve Statement 117
This section of the listing file can be turned off by entering a line containing the statement option solprint = off ; in
the program above the solve statement.
The solution listing section from our example is shown below.
The order of the equations and variables are the same as in the symbol listing described before and will be described later
The four columns associated with each entry have the following meaning,
LOWER lower bound (.lo)
LEVEL level value (.l)
UPPER upper bound (.up)
MARGINAL marginal (.m)
For variables the values in the LOWER and UPPERM columns refer to the lower and upper bounds. For equations they are
obtained from the (constant) right-hand-side value and from the relational type of the equation. These relationships were
described in Chapter Equations .
Attention
The LEVEL and MARGINAL values have been determined by the solver, and the values shown are used to update the
GAMS values. In the list they are shown with fixed precision, but the values are returned to GAMS with full machine
accuracy. The single dots '.' on the list represent zero.
EPS is the GAMS extended value that means very close to but different from zero. It is common to see a marginal value
given as EPS, since GAMS uses the convention that marginal are zero for basic variables, and not zero for others.
118 GAMS Output
Attention
EPS is used with non-basic variables whose marginal values are very close to, or actually, zero, or in nonlinear problems
with superbasic variables whose marginals are zero or very close to it. A superbasic variable is one between its bounds
at the final point but not in the basis.
There are brief explanations of technical terms used in this section in the Glossary. For models that are not solved to
optimality, some constraints may additionally be marked with certain flags. The list of these flags and their description is
given below.
INFES The row or column is infeasible. This mark is made for any entry whose level value is not between the
upper and lower bounds.
NOPT The row or column is non-optimal. This mark is made for any non-basic entries for which the marginal
sign is incorrect, or superbasic ones for which the marginal value is too large.
UNBND The row or column that appears to cause the problem to be unbounded.
If our example had display output for reporting, it would come here.
6 Error Reporting
All the comments and description about errors have been collected into this section for easy reference when disaster strikes.
Effective error detection and recovery are important parts of any modeling system.GAMS is designed around the assumption
that the error State is the normal state of modeling. Experience shows that most compilations during the early stages of
development will produce errors. Not to Worry! The computer is much better at checking details that the human mind and
should be able to provide positive feedback and suggestions about how to correct errors or avoid ambiguities. Developing a
model is like writing a paper or an essay ; many drafts and rewrites are required until the arguments are presented in the
most effective way for the reader and meet all the requirements of proper English.GAMS acts like a personal assistant with
knowledge of mathematical modeling and of the syntactic and semantic details of the language.
6 Error Reporting 119
Errors are detected at various stages in the modeling process. Most of them are caught at the compilation stage, which
behaves like the proofreading stage of the modeling process. Once a problem has passed through the rigorous test of this
stage, the error rate drops almost to zero. Most of the execution runs, which are much more expensive than compilation,
proceed without difficulties because GAMS knows about modeling and has anticipated problems. Many of the typical errors
made with conventional programming languages are associated with concepts that do not exist in GAMS Those error sources
such as address calculations, storage assignment, subroutine linkages, input-output and flow control create problems at
execution time, are difficult to locate, often lead to long and frustrating searches, and leave the computer user intimidated.
GAMS takes a radically different approach. Errors are spotted as early as possible, are reported in a way understandable to
the user, including clear suggestions for how to correct the problem, and a presentation of the source of the error in terms of
the user's problem.
Attention
All errors are marked with four asterisks' 'at the beginning of a line in the output listing.
As soon as an error is detected, processing will be stopped at the next convenient opportunity. A model will never be solved
after an error has been detected. The only remedy is to fix the error and repeat the run.
Errors are grouped into the three phases of GAMS modeling! compilation, execution and model generation (which includes
the solution that follows). The following three sub-sections discuss these types of errors.
Attention
When a compilation error is discovered, a $-symbol and error number are printed below the offending symbol (usually
to the right) on a separate line that begins with the four asterisks.
If more than one error is encountered on a line (possibly because the first error caused a series of other spurious errors) the
$-signs may be suppressed and error number squeezed. GAMS will not list more than 10 errors on any one line.
Attention
At the end of the echo print of the program, a list of all error numbers encountered, together with a description of the
probable cause of each error, will be printed. The error messages are self-explanatory and will not be listed here.
It is worth noting that it is easy to produce a model that does not do what you want it to do, but does not contain errors in the
sense that the term is being used in this section. The best precaution is to check your work carefully and build in as many
automatic consistency checks as possible.
One mistake that may cause confusion is if a GAMS reserved word is used for a label or an identifier. In this case, it is
impossible to provide helpful messages for technical reasons.
Attention
In some cases, an error may not be detected until the statement following its occurrence, where it may produce a number
of error conditions whose explanations seem quite silly. Always check carefully for the cause of the first error is such a
group, and look at the previous statement (and especially for missing semicolons) if nothing seems obvious.
The following example illustrates the general reporting format for compiler errors.
120 GAMS Output
Attention
Solve error messages are reported in two places and in two formats.
1. they are shown immediately below the solve statement with a short text including the name of any offending
identifier and the type of model involved. This will be sufficient in most cases.
2. a longer message with some hints appears with the rest of the error messages at the end of the compilation.
The example below illustrates how the general reporting format for compiler errors associated with a solve statement.
1 variables x,y, z ;
2 equations eq1 , eq2;
3
4 eq1.. x**2 - y =e= z ;
5 eq2.. min(x,y) =l= 20 ;
6
7 model silly / all / ;
8 solve silly using lp maximizing z ;
**** $54,51,256
**** THE FOLLOWING LP ERRORS WERE DETECTED IN MODEL SILLY:
**** 54 IN EQUATION EQ1 .. ENDOG OPERANDS FOR **
**** 51 IN EQUATION EQ2 .. ENDOG ARGUMENT(S) IN FUNCTION
9
Error Messages
1 variable x;
2 equation eq1;
3
4 eq1.. x =l= 10 ;
5 x.lo = 10 ;
6 x.up = 5 ;
7 model wrong /eq1/;
8 solve wrong using lp maximizing x ;
9
Some solve statement require the evaluation of nonlinear functions and the computation of derivatives. Since these
calculations are not carried out by GAMS but by other subsystems not under its direct control, errors associated with these
calculations are reported in the solution report. Unless reset with the domlim option the subsystems will interrupt the solution
process if arithmetic exceptions are encountered. They are then reported on the listing as shown in the following example:
1 variable x, y;
2 equation one;
3
4 one.. y =e= sqrt(10/x);
5 x.l = 10;
6 x.lo = 0;
7
8 model divide / all / ;
9 solve divide maximizing y using nlp;
S O L V E S U M M A R Y
Note that the solver status returned with a value of 5, meaning that the solver has been interrupted because more than domlim
evaluation errors have been encountered. The type of evaluation error and the equation causing the error are also reported.
If the solver returns an intermediate feasible solution because of evaluation errors, the following solve will still be attempted.
The only fatal GAMS error that can be caused by a solver program is the failure to return any solution at all. If this happens,
as mentioned above, all possible information is listed on the GAMS output file and any solves following will not be attempted.
7 Summary
This is the end of the sequential discussion of the basic features of the GAMS language. All further chapters are geared
towards more advanced use of GAMS .
Chapter 11
1 Introduction
This chapter deals with the way in which conditional assignments, expressions and equations are made in GAMS. The index
operations already described are very powerful, but it is necessary to allow for exceptions of one sort or another. For example,
heavy trucks may not be able use a particular route because of a weak bridge, or some sectors in an economy may not produce
exportable product. The use of a subset in an indexed expression has already been shown to provide some ability to handle
exceptions.
2 Logical Conditions
Logical conditions are special expressions that evaluate to a value of True or False. Numerical Expressions can also serve
as logical conditions. Additionally, GAMS provides for numerical relationship and logical operators that can be used to
generate logical conditions. The next four sub-sections discuss these various building blocks that can be used to develop
complex logical conditions.
2*a - 4
This expression results in a logical value of False when a is 2 because the expression numerically evaluates to 0. For all other
values of a, the expression results in a non-zero value, and therefore is equivalent to a logical value of True.
Operator Meaning
strictly less than
lt, <
less than-or-equal to
le, <=
eq, = equal to
not equal to
ne, <>
greater than or equal to
ge, >=
strictly greater than
ge, gt, >
The following example of a numerical relationship illustrates its use as a logical condition.
(sqr(a) > a)
This condition evaluates to False if 1 a 1. For all other values of a, this condition evaluates to True. Note that the same
expression can also be written as (sqr(a) gt a).
Operator Meaning
not
not
and
and
or inclusive or
xor exclusive or
The truth table generated by these logical operators is given in the following table.
Table 1:Truth table of logical operators
Set membership can also be used as a logical condition. The label results in a logical value of True if it is a member of the set
in question, and False if it is not. This is used with subsets and dynamic sets.
Consider the following example for illustration.
set i /1*10/
subi(i) /1*3/ ;
The set subi(i) results in a logical value of True for all elements that belong to subi and False for all elements of i that do
not belong to subi.
2 Logical Conditions 125
The use of set membership as a logical condition is an extremely powerful feature of GAMS and while its use will be
illustrated later on in this chapter, its full power becomes clear when considered with the description of dynamic sets later.
dayofweek = wednesday
dayofweek <> thursday
Attention
GAMS follows the convention that the result of a relational operation is zero if the assertion is False, and one if True.
x = (1 < 2) + (2 < 3)
The expression to the right of the assignment evaluates to 2 since both logical conditions within parenthesis are true and
therefore assume a value of 1. Note that this is different from the assignment below,
x = (1 < 2) or (2 < 3)
Operation Operator
Exponentiation
Numerical Operators
- Multiplication, Division , /
- Unary operators - Plus, Minus +, -
- Binary operators - addition, subtraction +, -
Numerical Relationship operators <, <=, =, <>, >=, >
Logical Operators
- not not
- and and
- or, xor or, xor
126 Conditional Expressions, Assignments and Equations
Note that in the case of operators with the same precedence, the order in which the operator appears in the expression is used
as the precedence criterion, with the order reducing from left to right.
Attention
It is always advisable to use parentheses rather than relying on the precedence order of operators. It prevents errors and
makes the intention clear.
x - 5*y and z - 5
is treated equivalent to (x - (5y)) and (z-5). However, note that the use of parenthesis does make the expression
clearer to understand.
Attention
The dollar logical conditions cannot contain variables. Variable attributes (like .l and .m) are permitted however.
The dollar operator is used to model conditional assignments, expressions, and equations. The following subsection provides
an example that will clarify its use. The next section will deal individually with the topic of using dollar conditions to model
conditional assignments, expressions, and equations respectively.
3.1 An Example
Consider the following simple condition,
If the condition is not satisfied, no assignment is made. Note that one can read the $ as 'such that' to clarify the meaning: 'a,
such that b is greater than 1.5, equals 2'.
Attention
For nested dollar conditions, all succeeding expressions after the dollar must be enclosed in parentheses.
u(k)$(s(k)$t(k)) = a(k) ;
where k, s(k), and t(k) are sets and u(k) and a(k) are parameters. The assignment will be made only for those members
of k that are also members of both s and t. Note the position of the parenthesis in the dollar condition. The statement above
can be rewritten as
Attention
To assist with the readability of statements, it is strongly recommended to use the logical and operator instead of nesting
dollar operators.
4 Conditional Assignments
The statement comprising the example in the Section before was a conditional assignment. In this example, the dollar
condition was on the left-hand-side of the assignment.
Attention
The effect of the dollar condition is significantly different depending on which side of the assignment it is in.
In many cases, it may be possible to use either of the two forms of the dollar condition to describe an assignment.
In such a case, clarity of logic should be used as the criterion for choice.
The next two subsections describe the use of the dollar condition on each side of the assignment.
Attention
For an assignment statement with a dollar condition on the left-hand side, no assignment is made unless the logical
condition is satisfied. This means that the previous contents of the parameter on the left will remain unchanged
for labels that do not satisfy the condition.
If the parameter on the left-hand side of the assignment has not previously been initialized or assigned any values,
zeroes will be used for any label for which the assignment was suppressed.
rho(i)$(sig(i) ne 0) = (1./sig(i)) - 1. ;
The parameter sig(i) has been previously defined in the model and the statement above is used to calculate rho(i). The
dollar condition on the statement protects against dividing by zero. If any of the values associated with sig(i) turn out
to be zero, no assignment is made and the previous values of rho(i) remain. As it happens, rho(i) was previously not
initialized, and therefore all the labels for which sig(i) is 0 will result in a value of 0.
Now recall the convention, explained in Section Numerical Expressions as Logical Conditions that non zero implies True and
zero implies False. The assignment above could therefore be written as
rho(i)$sig(i) = (1./sig(i)) - 1. ;
Consider the following example, which is a slight modification to the one described in Section An Example,
Therefore an if-then-else type of construct is implied, but the else operation is predefined and never made explicit. Notice
that the statement in the illustrative example above can be re-written with an explicit if-then-else and equivalent meaning as
This use of this feature is more apparent for instances when an else condition needs to be made explicit. Consider the next
example adapted from [FERTD] . The set i is the set of plants, and are calculating mur(i), the cost of transporting imported
raw materials. In some cases a barge trip must be followed by a road trip because the plant is not alongside the river and we
must combine the separate costs. The assignment is:
This means that if the entry in the distance table is not zero, then the cost of shipping using that link, which has a fixed and a
variable components, is added to the total cost,. If there is no distance entry, there is no contribution to the cost, presumably
because that mode is not used.
u(k)$s(k) = a(k) ;
where k and s(k) are sets, while u and a are parameters. This can be rewritten as
u(s) = a(s) ;
4 Conditional Assignments 129
Note that the assignment has been filtered through the conditionality without the use of the dollar operator. This is a cleaner
and more understandable representation of the assignment. This feature gets more useful when dealing with tuples (sets with
multiple indices).
Consider the following example for calculating the travel cost for a fictional parcel delivery service between collection sites
(i) and regional transportation hubs (j),
set i /miami,boston,chicago,houston,sandiego,phoenix,baltimore/
j /newyork,detroit,losangeles,atlanta/ ;
set ij(i,j) /
boston.newyork
baltimore.newyork
miami.atlanta
houston.atlanta
chicago.detroit
sandiego.losangeles
phoenix.losangeles / ;
The set ij denotes the regional transportation hub for each collection site. Factor is the cost estimate per unit mile. The
cost of transporting parcels (shipcost) from a local collection site (i) to a regional hub(j) is then provided by the following
assignment,
shipcost(i,j)$ij(i,j) = factor*distance(i,j) ;
Note that i and j do not appear separately in the assignment for shipcost. The assignment can then be simply written as,
shipcost(ij) = factor*distance(ij) ;
If i or j appear separately in any assignment, the above simplification cannot be made. For example, consider the case where
the shipping cost depends not only on factor and the distance between collection sites and regional hubs but also on the
congestion at the regional hub.
Parameter congestfac(j) /
newyork 1.5
detroit 0.7
losangeles 1.2
atlanta 0.9/ ;
Congestfac is a parameter used to model the congestion at each regional hub. The unit cost of shipment is then computed
as follows:
shipcost(i,j)$ij(i,j) = factor*congestfac(j)*distance(i,j) ;
shipcost(ij) = factor*congestfac(j)*distance(ij) ;
The above representation has the index j on the right hand side, but not on the left hand side. As explained before, GAMS
will flag this assignment as an error. However, the following representation will work:
shipcost(ij(i,j)) = factor*congestfac(j)*distance(ij) ;
In the above assignment ij is specifically denoted as a tuple of i and j which then appear on the left hand side.
Attention
A common use of dollar controlled index operations is where the control is itself a set. The importance of this concept
will become apparent with the discussion of dynamic sets.
A set was used to define the mapping between mines and ports in Chapter Set Definition. Another typical example is a
set-to-set mapping defining the relationship between states and regions, useful for aggregating data from the state to the
regional level.
sets r / north,south /
s / florida,texas,vermont,maine /
corr(r,s) / north.(vermont,maine)
south.(florida,texas) /
parameter y(r)
income (s) "income of each state"
/ florida 4.5, vermont 4.2
texas 6.4, maine 4.1 / ;
The set corr provides a correspondence to show which states belong to which regions. The parameter income is the income
of each state. Y(r) can be calculated with this assignment statement:
For each region r, the summation over s is only over those pairs of (r,s) for which corr(r,s) exists. Conceptually, set
existence is analogous to the Boolean value True or the arithmetic value 'not zero'. The effect is that only the contributions
for 'vermont' and 'maine' are included in the total for 'north', and 'south' includes only 'texas' and 'florida'.
Note that the summation above can also be written as sum(s,income(s)$corr(r,s)), but this form is not as easy to read
as controlling the index of summation.
6 Conditional Equations 131
The controlling indices can, in certain cases, be filtered through the conditional set without the use of the dollar operator.
Consider the shipping cost example described previously in this section. The total cost of shipment is obtained through the
following equation:
where shipped is the amount of material shipped from i to j, and totcost is the total cost of all shipment. The equation
above can be written as
However, if the original equation includes a term dependent only on index j, as follows
Note that the presence of a parameter indexed solely by j in the indexed expression above necessitated the use of ij(i,j)
rather than ij.
6 Conditional Equations
The dollar operator is also used for exception handling in equations. The next two subsections discuss the two main uses of
dollar operators within equations - within the body of an equation, and over the domain of definition.
A dollar operator within an equation is analogous to the dollar control on the right of assignments as discussed in Section
Dollar on the Right , and if one thinks of 'on the right' as meaning on the right of the '..' then the analogy is even closer. An
if-else operation is implied as it was with assignments. It is used to exclude parts of the definition from some of the generated
constraints.
Consider the following example adapted from [CHENERY],
The term is added to the right hand side of the equation only for those elements of i that belong to t(i).
Controlling indexing operations using the dollar condition can also be done as with any assignment. Consider the following
supply balance (sb) equation from [GTM],
Attention
The purpose of the dollar control over the domain of definition of equations is to restrict the number of constraints
generated to less than that implied by the domain of the defining sets.
cc(m,i)$mpos(m,i)..
sum(p$ppos(p,i), b(m,p)*z(p,i)) =l= util*k(m,i);
Cc is a capacity constraint defined for all units (m) and locations (i).
Not all types of units exist at all locations, however, and the mapping set mpos(m,i) is used to restrict the number of
constraints actually generated. The control of the summation over p with ppos(p,i) is an additional one, and is required
because not all processes (p) are possible at all locations (i).
parameter bigM(i,j) ;
variable shipped(i,j) ;
binary variable bin(i,j) ;
equation logical(i,j) ;
logical(i,j)$ij(i,j).. shipped(i,j) =l= bigM(i,j)*bin(i,j) ;
The equation logical relates the continuous variable shipped(i,j) to the binary variable bin(i,j). This can be
simplified as follows:
Note that if the right hand side of the equation contained any term that was indexed over i or j separately, then the equation
logical(i,j)$ij(i,j) would have to be simplified as logical(ij(i,j)).
Chapter 12
Dynamic Sets
1 Introduction
All the sets that have been discussed so far had their membership declared as the set itself was declared, and the membership
was never changed. In this chapter we will discuss changing the membership of sets. A set whose membership can change
is called a dynamic set to contrast it with a static set whose membership will never change. The distinction is important and
will be discussed in detail in this chapter. This is a topic that has been avoided until now because of a potential confusion for
new users. Advanced Users will, however, find it useful.
Set name is the internal name of the set (also called an identifier) in GAMS. Yes and no are keywords used in GAMS to
denote membership or absence respectively from the assigned set.
Attention
The most important principle to follow is that a dynamic set should always be domain checked at declaration time
to be a subset of a static set (or sets).
It is of course possible to use dynamic sets that are not domain checked, and this provides additional power,
flexibility, lack of intelligibility, and danger. Any label is legal as long as the set dimension, once established, is
preserved.
Note that the sets subitem1 and subitem2 are declared like any other set. The two sets become dynamic because of
assignments. They are also domain checked: the only members they will ever be able to have must also be members of item.
And item is a static set and henceforth its membership is frozen. The first two assignments each add one new element to
subitem1. The third is an example of the familiar indexed assignment: subitem2 is assigned all the members of item. The
output caused by the display statement, that will reveal the membership of the sets, is shown below for verification.
Attention
The elements are displayed in the order specified in the declaration of item.
supply(pencil,bic) = yes ;
supply(pen,sup) = yes ;
All the mechanisms using asterisks and parenthesized lists that we introduced in the discussion on static sets in Chapter Set
Definition are available for dynamic sets as well.
subitem1(item) = no
subitem1(subitem2) = yes;
The first assignment ensures that subitem1 is empty. Note that this can also be done with parameters. For example,
parameter inventory(item) ;
inventory(subitem1) = 25 ;
2 Assigning Membership to Dynamic Sets 135
Attention
The trick is to declare the equation over the entire domain but define it over the dynamic set.
To repeat the important point: the equation is declared over allr but referenced over r. Then arbitrary assignments can be
made to r within the membership of allr.
ii(c) = yes;
si(c) = yes;
Here is the output from the display statement in the listing file:
b, c
Attention
That an assignment to a singleton set first clears the set always, means that it is even cleared if there would be no
change at all for a regular set:
136 Dynamic Sets
Singleton Set s / 1 /;
s(s)$0 = yes;
display s;
Here is the output from the display statement in the listing file:
---- 3 SET s
( EMPTY )
The assignment behavior can be changed with strictSingleton, and option strictSingleton.
3.1 Assignments
Dynamic sets can be used inside dollar conditions within assignments defining other dynamic sets or parameters.
As an illustration of its use in defining other dynamic sets, the two statements in the example from Section Assignments over
the Domain of Dynamic Sets can be written with equivalent effect as
subitem1(item) = yes$subitem2(item) ;
Attention
The value used in the implied else that goes with dollar on the right is no in a set assignment, rather than zero
which is used with normal data.
The second example from Section Assignments over the Domain of Dynamic Sets can be rewritten as follows to illustrate the
use of dynamic sets in defining parameters,
inventory(item)$subitem1(item) = 25 ;
This example has been shown only for illustration. Note that the second statement above can also be rewritten tersely as
totinv = sum(subitem1,inventory(subitem1)) ;
This is not always possible. Consider the following artificially created example,
parameter totsales(dep) ;
totsales(dep) = sum(item$supply(item,bic), sales(dep,item)) ;
The assignment above is used to find the total sales of all departments that sell items supplied by bic. Note that the dynamic
set is used to limit the domain of summation to those for which supply(item,'bic') is true.
3.3 Equations
Dynamic sets can be used inside dollar conditions in equations both as part of the equation algebra, or while defining the
domain of the equation. The first case is similar to the case of assignments discussed in Section Assignments . The latter
case is used to restrict the equation over the domain of a dynamic set. The equation defined in the example from Section
Equations Defined over the Domain of Dynamic Sets can be rewritten with equivalent effect as follows,
The domain of definition of equation prodbal is restricted to those elements that belong to the dynamic set r.
inventory(item)$subitem1(item) = 25 ;
prodbal(allr)$r(allr).. activity(allr)*price =e= revenue(allr) ;
inventory(subitem1) = 25 ;
prodbal(r).. activity(r)*price =e= revenue(r) ;
4 Set Operations
This section describes how various symbolic set operations can be performed in GAMS using dynamic sets. The Union,
Intersection, Complement, and Difference set operations are described individually in the following subsections. Once again
the example from Section Illustrative Example is used to illustrate each operation.
The membership of subitem3 is set equal to all the elements of subitem1 and all the elements of subitem2. The operation
above is equivalent to the following longer way of representation,
The membership of subitem3 is set equal to only those present in both subitem1 and subitem2. The operation above is
equivalent to the following longer way of representation,
The membership of subitem3 is set equal to all those in item but not in subitem1. The operation above is equivalent to the
following longer way of representation,
subitem3(item)=yes; subitem3(subitem1)=no;
The membership of subitem3 is set equal to all elements that are members of subitem1 but subitem2. The operation
above is equivalent to the following longer way of representation,
subitem3(item)=yes$(subitem1(item)); subitem3(subitem2)=no;
5 Summary
The purpose of set assignments is to make calculations based on given data (the static sets) for use in exception handling. It
is one more example of the principle of entering a small amount of data and building a model up from the most elemental
information.
Chapter 13
1 Introduction
In our original discussion of sets in Chapter Set Definition , we said that unless there is a special need to do things differently,
a one-dimensional set should be regarded as an unordered collection of labels. In this chapter we will discuss special features
that can be used when you need to be able to deal with a set as if it were a sequence.
For example, in economic models that explicitly represent conditions in different time periods, it is necessary to refer to the
next or previous time period, because there must be links between the periods. As another example, stocks of capital are
normally tracked through such models by equations of the form 'stocks at the end of period n are equal to stocks at the end
of period n 1 plus net gains during period n'. Location problems, where the formulation may require a representation of
contiguous areas, as in a grid representation of a city, and scheduling problems are other classes of problems in which sets
must also have the properties of sequences.
Attention
Models involving sequences of time periods are often called dynamic models, because they describe how conditions
change over time. This use of the word dynamic unfortunately has a different meaning from that used in connection
with sets, but this is unavoidable.
Attention
Ordered sets must be static sets. In other words, no order is possible for dynamic sets.
GAMS maintains one list of unique elements - the labels that are used as elements in one or more sets. The order
of the elements in any one set is the same as the order of those elements in that unique element list. This means
that the order of a set may not be what it appears to be if some of the labels were used in an earlier definition.
The map of your labels in the GAMS order can be seen by putting the compiler directive $onuellist somewhere
before the first set declaration.
A good rule of thumb is that if the labels in a set one wants to be ordered have not been used already, then they
will be ordered.
The map is shown with the other compiler maps after the listing of your program. In the example below we show ordered and
unordered sets and the map showing the order. The input is:
140 Sets as Sequences: Ordered Sets
$onuellist
set t1 / 1987, 1988, 1989, 1990, 1991 /
t2 / 1983, 1984, 1985, 1986, 1987 /
t3 / 1987, 1989, 1991, 1983, 1985 / ;
The map below shows the entry order (the important one) and the sorted order, obtained by sorting the labels into dictionary
order. The single digits on the left are the sequence numbers of the first label on that line.
G e n e r a l A l g e b r a i c M o d e l i n g S y s t e m
Unique Element Listing
A set can always be made ordered by moving its declaration closer to the beginning of the program. With these restrictions in
mind, we move on the operations that are used in dealing with sets as sequences.
Attention
Ord can be used only with a one-dimensional, static, ordered set.
As a result of the statements above, the value of val('1985') will be 1, val('1986') will be 2 and so on.
A common use of ord is in setting up vectors that represent quantities growing in some analytically specified way. For
example, suppose a country has 56 million people in the base period and population is growing at the rate of 1.5 percent per
year. Then the population in succeeding years can be calculated by using:
It is often useful to simulate general matrix operations in GAMS. The first index on a two dimensional parameter can
conveniently represent the rows, and the second the columns, and order is necessary. The example below shows how to set
the upper triangle of a matrix equal to the row index plus the column index, and the diagonal and lower triangle to zero.
4 Lag and Lead Operators 141
which fixes the variable for the last member only: no assignment is made for other members of t. The advantage of this way
of fixing c is that the membership of t can be changed safely and this statement will always fix c for the last one.
The difference between these two types of operators involves the handling of endpoints in the sequence. GAMS provides
some built in facilities to deal with this issue, but in any work involving sequences the user must think carefully about the
treatment of endpoints, and all models will need special exception handling logic to deal with them.
In the linear case, the members of the set that are endpoints are left hanging. In other words, there are no members preceding
the first member or following the last one. This may cause the use of non-existent elements. The next section will describe
how this is handled in GAMS . This form of the lag and lead operators is useful for modeling time periods that do not repeat.
A set of years (say 1990 to 1997) is an example. The operators are + and --.
Attention
GAMS is able to distinguish linear lag and lead operators (+,-) from arithmetic operators by context. To avoid
ambiguity, GAMS does not allow to mix lag and lead operators with arithmetic operators. For example, i + 1 + 1 is
not allowed, but writing i + (1 + 1) would work.
In the circular case, the first and last members of the set are assumed to be adjacent, so as to form a circular sequence of
members. The notion is that 'first - 1' is a reference to 'last' and 'last + 2' is the same as 'first + 1' and so on. All
references and assignments are defined. This is useful for modeling time periods that repeat, such as months of the year or
hours in the day. It is quite natural to think of January as the month following December. Agricultural farm budget models
and workforce scheduling models are examples of applications where circular leads occur naturally. The operators are ++ and
--.
The next two sections will describe the use of these lag and lead operators in assignment statements and in equations
respectively.
142 Sets as Sequences: Ordered Sets
Attention
A reference to a non-existent element causes the default value (zero in this case) to be used, whereas an attempt to
assign to a non-existent element results in no assignment being made.
The next two sub-sections provide examples illustrating the use of the linear form of the lag and lead operators for reference
and assignment. Section Circular Lag and Lead Operators will illustrate the use of the circular form of the lag and lead
operator.
The option statement suppresses the decimal places from the display. The results are shown below.
---- 6 PARAMETER A
Y-1987 1987, Y-1988 1988, Y-1989 1989, Y-1990 1990, Y-1991 1991
---- 6 PARAMETER B
Y-1988 1987, Y-1989 1988, Y-1990 1989, Y-1991 1990
For a, as expected, the values 1987, 1988 up to 1991 are obtained corresponding to the labels y-1987, y-1988 and so on. b
is initialized to 1.
For b, the assignment is done over all members of t, and for each, the value of a from the previous period is assigned to the
current member of b. If no previous period, as with y-1987, zero is used, and b('y-1987') becomes zero, replacing the
previous value of 1.
---- 6 PARAMETER A
Y-1987 1987, Y-1988 1988, Y-1989 1989, Y-1990 1990, Y-1991 1991
---- 6 PARAMETER C
Y-1987 -1, Y-1988 -1, Y-1989 1987, Y-1990 1988, Y-1991 1989
The assignment to ais explained in Section Linear Lag and Lead Operators - Reference . The assignment to c is different. It is
best to spell it out in words. For each member of t in sequence, find the member of c associated with t+2. If it exists, replace
its value with that of a(t). If not (as with y-1990 and y-1991) make no assignment. The first member of t is y+1987, and
therefore the first assignment is made to c('y-1989') which takes the value of a('y-1987'), viz., 1987. No assignments
at all are made to c('y-1987') or c('y-1988'): these two retain their previous values of 1.
The lag (or lead) value does not have to be an explicit constant: it can be arbitrary expression, provided that it evaluates to
an integer. If it does not, error messages will be produced. A negative result causes a switch in sense (from lag to lead, for
example). The following is guaranteed to set d(t) to all zero:
The parameter lagval2 is used for reference while lagval1if used for assignment. Notice that the case of circular lag and
lead operators does not lead to any non-existent elements. The difference between reference and assignment is therefore not
important. Note that the following two statements from the example above,
lagval2(s) = val(s--2) ;
leadval(s++1) = val(s) ;
are equivalent to
lagval2(s++2) = val(s) ;
leadval(s) = val(s--1) ;
The use of reference and assignment have been reversed with no difference in effect.
144 Sets as Sequences: Ordered Sets
Attention
All lag and lead operands must be exogenous.
The next two sub-sections provide examples illustrating the use of the linear form of the lag and lead operators in equations
for reference and to modify the domain of its definition. Section Circular Lag and Lead Operators will illustrate the use of the
circular form of the lag and lead operator in equations.
The declaration of t is included, as are a couple of dynamic sets that are used to handle the first and last periods (terminal
conditions) in a clean way.
The interesting equation is kk, the capital balance. The set t contains members 1990 to 2000, and so there will be a capital
stock constraint for 1991 to 2000. Spelling out the constraint for 1991,
The lead operator on the domain of definition has restricted the number of constraints generated so that there are no references
to non-existent variables: the generated problem will have 10 kk constraints defining the relationship between the 11 k capital
values.
The other interesting point in the [RAMSEY] excerpt is that the constraint tc is explicitly defined only for the final period
because of the assignment to the set tlast. Notice the use of dynamic sets to control the domain of the two equations. The
set tfirst is also used in other parts of the model to set initial conditions, particularly the capital stock in the first period,
k('1990').
The dollar condition will cause one of the individual equations to be suppressed.
However, note that using lags and leads in the equation domain will always cause one or more individual equations to
be suppressed, and this may not be desirable in every case. Consider the following modified set of constraints to the one
discussed in the previous example. It is expressed with the lag and lead operators being used to control the domain of the
equation definition.
Here, the important boundary is the one at the beginning of the set rather than at the end. This can be expressed more
compactly as
In general, the choice between using lag and lead operators as reference or in domain control is often a matter of taste.
equation matbal(s) ;
In this example, four individual examples are generated. They are listed below.
7 Summary
This chapter introduced the concept of ordering in sets. All the features in GAMS that dealt with this issue including the ord
and card functions, as well as the linear and circular forms of the lag and lead operators were described in detail.
146 Sets as Sequences: Ordered Sets
Chapter 14
1 Introduction
In this chapter we will provide more detail about display statements, including the controls that a user has over the layout
and appearance of the output. These controls are a compromise to provide some flexibility. The display statement will
not provide a publication quality reporting function, but is instead aimed for functionality that is easy to use, and provides
graceful defaults. The execution of the display statement allows the data to be written into the listing file only.
2 The Syntax
In general, the syntax in GAMS for the display statement is:
Ident-ref means the name without domain lists or driving indices of a set or parameter, or a sub-field of an equation
or variable. The identifier references and the text can be mixed and matched in any order, and the whole statement can be
continued over several lines.
The output produced by a display consists of labels and data. For sets, the character string yes (indicating existence) is used
instead of values.
Attention
Only the non-default values are displayed for all data types.
The default value is generally zero, except for the .lo and .up subtypes of variables and equations. The default values
for these are shown in the following table.
Table 1: Default values for .lo and .up subtypes
3 An Example
An example of a display statement is given below.
The resulting listing file will contain the following section that corresponds to the display statement.
S1 0.330, S3 0.670
T5 T7
S1 0.109 0.221
S3 0.221 0.449
Note that only the non-zero values are displayed. In the case of multi-dimensional identifiers, the data is reported in a tabular
form that is easy to read.
For 7 to 10 indices, the natural progression is followed. The labels vary slowest for the first index position, and quickest for
the highest. Within each index position the order is the GAMS entry order of the labels.
The order of the indices is always as in the declaration statement for the symbol. One can declare them in the order that is
found appealing, or make an assignment to a new identifier with a different order.
Attention
The only way to change the order in which the labels for each index position appear on display output is to change
the order of appearance of the labels in the GAMS program. This is most easily done by declaring a set whose only
purpose is to list all the labels in the order that is needed. Make this set the very first declaration in the GAMS program.
4.1 Example
Consider the following example. X has four dimensions or index positions. It is initialized using parameter format and then
displayed as shown below:
INDEX 1 = first
i ii
one .b 5.636
two .a -2.939 0.029
two .b 10.346
three.b -6.316
INDEX 1 = second
i ii
150 The Display Statement
Notice that there are two sub-tables, one for each label in the first index position. Note that the zero in the list for
x('first','one','a','ii') has vanished, since zero values are suppressed in each sub-table separately. The order of
the labels is not the same as in the input data list.
5 Display Controls
GAMS allows the user to modify the number of row and column labels in the display listing, as well as the accuracy of the
data being displayed. The global display controls allows the user to affect more than one display statement. If specific data
need to be listed in a particular format, the local display controls can be used to over-ride the global controls. The next two
sub-sections will deal with each of these display controls in turn.
The simplest of these options is the one controlling the number of digits shown after the decimal point. It affects numbers
appearing in all display output following the option statement, unless changed for a specific identifier as shown below. The
general form of the statement is: 'option decimals = value;' where value is an integer between 0 and 8. If you use 0,
the decimal point is suppressed as well. The width of the number field does not change, just the number of decimals, but this
may cause numbers which would normally be displayed in fixed to appear in E-format, i.e., with the exponent represented
explicitly.
Consider the following extension to the example discussed in the previous section.
GAMS has rounded or converted numbers to E-format where necessary and the output is as follows:
INDEX 1 = first
i ii
one .b 5.6
two .a -2.9 2.873000E-2
two .b 10.3
three.b -6.3
INDEX 1 = second
i ii
It is often more useful to control the number of decimals for specific identifiers separately. Using a statement whose general
form can do this:
option ident:d-value:
Ident represent the name of a parameter, variable or equation, and d-value must be (as before) in the range 0 and
8 . Exactly d-value places of decimals will be shown on all displays of ident that follow. This form can be extended to
control layout of the data. The general form is:
option ident:d-value:r-value:c-value ;
Here r-value means the number of index positions that are combined to form the row label and c-value means the number
on the column headers.
The example discussed in the previous section is further extended in order to illustrate the local display control.
i ii
first .one .b 5.63559
first .two .a -2.93930 0.02873
first .two .b 10.34570
first .three.b -6.31610
second.one .a +INF 1.00370
second.one .b -17.29948
second.two .a +INF
second.two .b 19.83500
Five places of decimals are shown, and three labels are used to mark the rows and one on the column. Since this is a
four-dimensional structure, there are no remaining indices to be used as sub-table labels (on the plane), and we now have the
results in one piece. The option statement is checked for consistency against the dimensionality of the identifier, and error
messages issued if necessary. Here is an example that puts two indices on each of the row and column labels, and retains five
decimal places:
The output is :
This output nicely illustrates the label order used. The first index varies the slowest, the last the fastest, and each one runs
from beginning to end before the next one to the left advances. This ordering scheme is also used on equation and column
lists and on the solution report, all produced by the solve statement.
Chapter 15
1 Introduction
In this chapter, the put writing facility of the GAMS language is introduced. The purpose of this writing facility is to
output individual items under format control onto different files. Unlike the display statement, the entire set of values for
indexed identifiers cannot be output using a single put statement (identifiers are the names given to data entities such as
the names for parameters, sets, variables, equations, models, etc). While its structure is more complex and requires
more programming than is required for the display statement, there is much greater flexibility and control over the output of
individual items.
In this chapter, the working of the put writing facility is described as well as the syntax for accessing files and globally
formatting documents using file suffixes for various attributes of a file. The put writing facility enables one to generate
structured documents using information that is stored by the GAMS system. This information is available using numerous
suffixes connected with identifiers, models, and the system. Formatting of the document can be facilitated by the use of file
suffixes and control characters.
The put writing facility generates documents automatically when GAMS is executed. A document is written to an external
file sequentially, a single page at a time. The current page is stored in a buffer, which is automatically written to an external
file whenever the page length attribute is exceeded. Consequently, the put writing facility only has control of the current
page and does not have the ability to go back into the file to alter former pages of the document. However, while a particular
page is current, information placed on it can be overwritten or removed at will.
2 The Syntax
The basic structure of the put writing facility in its simplest form is:
file fname(s);
put fname;
put item(s);
where fname represents the name used inside the GAMS model to refer to an external file. Items are any type of output such
as explanatory text, labels, parameters, variable or equation values. In the basic structure shown above, the first line defines
the one or more files which you intend to write to. The second line assigns one of these defined files as the current file, that is
the file to be written to. Lastly, the third line represents the actual writing of output items to the current file.
3 An Example
It is instructive to use a small example to introduce the basics of the put writing facility. The example will be based on the
transportation model [TRNSPORT]. The following program segment could be placed at the end of the transportation model
154 The Put Writing Facility
to create a report:
put results;
put Transportation Model Results// ;
loop((i,j), put i.tl, @12, j.tl, @24, x.l(i,j):8:4 /);
In the first line, the internal file names factors and results are defined and connected to the external file names factors.dat
and results.dat. These internal file names are used inside the model to reference files, which are external to the model.
The second line of this example assigns the file factors.dat as the current file, that is the file which is currently available
to be written to.
In the third line of the example, writing to the document begins using a put statement with the textual item 'Transportation
Model Factors'. Notice that the text is quoted. The slashes following the quoted text represent carriage returns. The
example continues with another textual item followed by the scalar f. Notice that these output items are separated with
commas. Blanks, commas, and slashes serve as delimiters for separating different output items. As mentioned above, the
slash is used as a carriage return. Commas and blank spaces serve as item delimiters. These delimiters leave the cursor at the
next column position in the document following the last item written. In most cases, the blank and the comma can be used
interchangeably; however, the comma is the stronger form and will eliminate any ambiguities.
In the fifth line of the program above, the cursor is repositioned to the first column of the sixth row of the output file where
another textual item is written. The cursor control characters # and @ serve to reposition the cursor to a specific row or column
as designated by the row or column number following the cursor control character. Lastly, the put statement is terminated
with a semicolon.
Next, the parameters a and b are written along with their corresponding set labels. Only one element of the index set can be
written using a put. To write the entire contents of the parameters a and b, the put statement is embedded inside a loop
which iterates over the index set. In the example above, the set element labels are identified using their set identifier and the
suffix .tl. As can be seen, the set element labels are located starting in the third column and the parameter a at column 15.
The example continues with the display of another quoted textual item followed by the parameter b. When executed, the
factors.dat file will look like:
Plant capacity
seattle 350.00
san-diego 600.00
Market demand
new-york 325.00
chicago 300.00
topeka 275.00
This output has been formatted using the default file format values. The methods to change these defaults will be described
later in this chapter.
In the last two lines of the example, the file results.dat is made current and the values associated with the variable x along
with their corresponding set element index labels are written line by line. The output results of the variable x are formatted
4 Output Files 155
by specifying a field width of eight spaces with four of these spaces reserved for the decimal. Notice that the local formatting
options are delimited with colons. The results.dat file will look like:
With just this brief introduction to the put writing facility, it is easy to envision its many uses such as report writing, providing
output to a file for use by another computer program, or simply the display of intermediate calculations. But, the surface of
the put writing facility has just barely been scratched. In the sections that follow, the many features and structure of the put
writing facility are described in more detail, along with examples.
4 Output Files
As noted earlier, the put statement allows the user to write to external files. This section describes the various features related
to the use of external files.
where file is the keyword used to define files. Fname is the internal file name and is used inside the GAMS model to refer to
an external file. External files are the actual files that output is written to. During file declaration, the external file name and
explanatory text are optional. When the external file name is omitted, GAMS will provide a system specific default external
file name, often fname.put. Note that multiple files can be defined using a single file statement. Consider the following
example:
file class1
class2 this defines a specific external file /report.txt/
con this defines access to the console (screen) for PC systems;
The first output file is recognized in the model by the name class1 and corresponds to the default file class1.put for a PC
system. The second output file is recognized in the model by the name class2 and it corresponds to the defined external file
report.txt. Lastly, the special internal file name con is defined to write output to the console (screen) for a PC systems.
Writing to the screen can be useful to advise the user of various aspects of the model during the model's execution.
As indicated by this syntax, multiple files can be sequentially written using a single put statement. Note that only one file is
current at a time. After the output items following an internal file name are written, the current file is reassigned based on the
next internal file name in the statement. The last internal file name used in a put statement remains as the current file until a
subsequent put statement uses an internal file name.
156 The Put Writing Facility
where myfile is the internal name of the file to be closed, and item(s) are the final entries into the file before it is closed.
If the internal file name is omitted from the putclose statement, the current put file is closed. Note that after using the
putclose command, the file does not have to be redefined in order to use it again. Simply make the file current and use put
statements as would be done normally. Of course, the existing file will either be overwritten or appended to depending on the
value of the append file suffix.
Attention
One application where this is useful is to write the solver option file from within the GAMS model. Option file
statements can be written using put and the file closed with a putclose prior to the solve statement. This makes the
option file available for use by the solver.
The following example shows the creation and closing of an option file for the MINOS solver:
This program segment would be placed inside the GAMS model prior to the solve statement.
class2.ap = 1;
Any items put into report.txt will from that point on be added to the end of the existing file contents. If the file had not
existed, the file would be created.
5 Page Format
The pages within files can also be structured using file suffixes to specify many attributes such as the printing format, page
size, page width, margins, and the case which text is displayed in. The following file suffixes can be used for formatting:
print control (.pc) Used to specify the format of the external file. The options 4,5,6, and 8 create delimited
files, which are especially useful when preparing output for the direct importation into other computer programs
such as spreadsheets.
0 Standard paging based on the current page size. Partial pages are padded with blank lines. Note
that the .bm file suffix is only functional when used with this print control option.
1 FORTRAN page format. This option places the numeral one in the first column of the first row of
each page in the standard FORTRAN convention.
6 Page Sections 157
2 Continuous page (default). This option is similar to .pc option zero, with the exception that
partial pages in the file are not padded with blank lines to fill out the page.
3 ASCII page control characters inserted.
4 Formatted output; Non-numeric output is quoted, and each item is delimited with a blank space.
5 Formatted output; Non-numeric output is quoted, and each item is delimited with commas.
6 Formatted output; Non-numeric output is quoted, and each item is delimited with tabs.
7 Fixed width; Fills up line with trailing blanks.
8 Formatted output; Each item is delimited with a blank space.
page size (.ps) Used to specify the number of rows (lines) which can be placed on a page of the document.
Can be reset by the user at any place in the program. However, an error will result if set to a value less than the
number of rows which have already been written to the current page. Maximum value is 130. The default value
is 60
page width (.pw) Used to specify the number of columns (characters) which can be placed on a single row of
the page. Can be reset by the user at any place in the program. However, an error will result if set to a value less
than the number of rows or columns which have already been written to the current page. The default value is
255.
top margin (.tm) Number of blank lines to be placed at the top margin of the page. These lines are in addition
to the number of lines specified in the .ps file suffix. Default value is 0.
bottom margin (.bm) Number of blank lines to be placed in the bottom margin of the page. These lines are in
addition to the number of lines specified in the .ps file suffix. This is functional with .pc option 0 only. Default
value is 0.
alphabetic case (.case) Used to specify the case in which alphabetic characters are displayed in the output file.
0 (default) Causes mixed case to be displayed.
1 Causes the output to be displayed in upper case regardless of the case used for the input.
To illustrate the use of these file suffixes, the following example involves formatting report.txt so that the pages are 72
spaces wide with 58 lines of output, an additional top margin of 6 lines, using ASCII page control characters (inserted every
64 lines), and with the output displayed in upper case.
Attention
Using a value of 4, 5, or 6 for the print control suffix (.pc) will cause data to be squeezed and therefore will ignore
spacing information provided by the user through the @ character. However, these values can be used to pass data on to
be read by spreadsheets.
6 Page Sections
There are three independent writing areas on each page of a document. These areas are the title block, the header block, and
the window. This is quite useful when there are sections of a page which remain relatively constant throughout a document.
Title and header blocks are often used to provide organizational information in a document with the window being used for
specific reporting.
These writing areas are always sequentially located on the page in the order shown on the following diagram.
+-----------------+
| Title Block |
158 The Put Writing Facility
+-----------------+
| Header Block |
+-----------------+
| |
| Window |
| |
+-----------------+
It is important to note that the title and header blocks are essentially the same as the window and use exactly the same syntax
rules. However, the window is required in each page of your document, while the title and headers are optional. Also note
that once the window is written to, any further modifications of the title or header blocks will be shown on subsequent pages
and not the current page. Writing to the window is what ultimately forces a page to be written.
In the illustrative example described in Section An Example , all the data was written to the window. A title block might
have been included, if more elaboration were needed, to provide the model name along with the page number. In addition, a
header block might have been used to display a disclaimer or an instruction, which we wanted consistently, repeated on every
page. Once this information is placed in the title or header blocks, it is displayed on each page thereafter unless modified.
This could be especially useful for a long document covering many pages.
Keyword Description
puttl write to title block
puthd write to header block
put write to window
The size of any area within a given page is based entirely on the number of lines put into it. Note that the total number of
lines for all areas must fit within the specified page size. If the total number of lines written to the title and header block
equals or exceeds the page size, an overflow error will be displayed in the program listing. When this occurs, this means
there is no room remaining on the page to write to the window.
As mentioned above, the syntax for writing an output item to any of the three possible writing areas of the page is basically the
same, the only difference being the choice of put keyword. This is illustrated by writing to the title block of our report.dat
file:
In this case, the text 'GAMS Put Example' has been placed in the first column of the first row of the title block. Any
subsequent pages in the report.dat file will now start with this information.
Attention
If the title block was modified or the header block was started after the window of the current page has been written to,
these modifications would appear in the next page and not the current page.
6.2 Paging
Paging occurs automatically whenever a page is full. However, note that the window must be used in order for the page to be
written to the output file. When a page has no output in its window, the page is not written to file regardless of whether there
are output items in the title or header blocks. To force a page that has an empty window out to file, simply write something
innocuous to the window such as:
8 System Suffixes 159
put ;
Now the window of the page has been initiated and it will be written.
Keyword Description
Move cursor position to row n of current page
#
Move cursor position to column n of current line
@n
Move cursor to first column of next line. Also acts as a delimiter between output items
/
In addition to numerals, any expression or symbol with a numeric value can be used to follow the # and @ characters. The
following example illustrates the use of these position controls to write out the value of a parameter a(i,j) in a tabular form:
8 System Suffixes
The complete list of system suffixes that can be used to recover information about the GAMS run are:
Suffix Description
.date program execution date
.ifile input file name
.ofile output file name
.page current file page
.rdate restart file date
.rfile restart file name
.rtime restart file time
.sfile save file name
.time program execution time
.title title of the model as specified by $title
As an illustration, consider the example discussed in the previous section. One can add page numbers to the title of the report
file by modifying the puttl statement to read
This causes the word page followed by the page number to appear on the title of every page starting at column 65.
9 Output Items
Output items for the put statement are of the following forms:
Item Description
text Any quoted text, set element label or text, any identifier symbol text or contents of the system
suffixes.
numeric Values associated with parameters, variables, equations, or any of the model suffixes.
set values Represent existence of set elements and carry the values yes or no only.
The methods for identifying and using each of these different types of output items are described in the following sub-sections.
Output items, which are quoted text, are any combination of characters or numbers set apart by a pair of single or double
quotes. However, the length of quoted text, as well as any output item, has a limit. No portion of the output item can be
placed outside of the page margin. When the page width is exceeded, several asterisks are placed at the end of the line and a
put error is recorded in the program listing.
In addition to quoted text, the output of other text items is possible through the use of system and identifier suffixes. The
identifier suffixes are:
identifier symbol text (.ts) Displays the text associated with any identifier
set element labels (.tl) Displays the individual element labels of a set
set element text (.te(index)) Displays the text associated with an element of a set. Notice that the .te suffix
requires a driving index. This driving index controls the set, which will be displayed and does not necessarily
have to be the same as the controlled set. Often a subset of indices of the controlled set is used.
text fill (.tf) Used to control the display of missing text for set elements.
0 suppresses the fill of missing explanatory text with element names leaving blanks
1 results in blank entries when an element is referenced which does not exist and does the default
fill otherwise
2 (default) always fills empty explanatory text with the element name
3 always fills the .te output with the element names not using the defined explanatory text
4 puts out the .te as when 3 in quotes with comma separators
5 same as 4 with periods as separators
6 same as 4 with blanks as separators
The following example illustrates these ideas:
subset of sites
i3 San Francisco
i4 Los Angeles
i5 i5
In this example, the symbol text for the identifier of the subset j is written first. This is followed with the labels for the subset
j and the associated element text found in its domain, that is, the set i. Notice the driving set j is used for the element text
specification of the set i. Since there was no set element text associated with the i5 element of set i, the set element label
was displayed again. By placing the following before the last line:
out.tf = 0;
The missing element text is now no longer replaced with the label text. The resulting file out.put file would now look like:
subset of sites
i3 San Francisco
i4 Los Angeles
i5
Suffix Description
.l level or marginal value
.lo lower bound
.m marginal or dual value
.prior priority
.scale scaling
.up upper bound
subset of sites
i1 NO Seattle
i2 NO Portland
i3 YES San Francisco
162 The Put Writing Facility
The second columns represents whether the element belongs to set jor not.
Suffix Description
.lj label justification (default 2)
.nj numeric justification (default 1)
.sj set value justification (default 1)
.tj text justification (default 2)
Suffix Description
.lw label field width (default 12)
.nw numeric field width (default 12)
.sw set value field width (default 12), (maximum 20)
.tw text field width (default 0)
The field width is specified with the number of spaces to be allocated to the field. Variable length field widths are possible by
using a suffix value of 0. This forces the field width to match the exact size of the item being displayed. If a textual output
item does not fit within the specified field, truncation occurs to the right. For numeric output items, the decimal portion of a
number is rounded or scientific notation used to fit the number within the given field. If a number is still too large, asterisks
replace the value in the output file.
As an example, to set the global numeric field width to four spaces from its default of 12 in the file out.put, we would use
the following statement:
out.nw = 4;
12 Additional Numeric Display Control 163
item:{<>}width:decimals;
The item is followed by a justification symbol, the field width, and the number of decimals to be displayed. The
specification of the number of decimals is only valid for numeric output. The following local justification symbols are
applicable:
Symbol Description
> right justified
< left justified
<> center justified
Omitting any of the components causes their corresponding global format settings to be used. As with global formatting, when
the field width is given a value of 0, the field width is variable in size. The item, width, and decimals are delimited with
colons as shown above. The use of the local format feature as well as the inclusion any of the components for justification,
field width, or the number of decimals is entirely optional.
The following example shows some examples of the local formatting feature:
numeric zero tolerance (.nz) Sets the tolerance level for which a number will be rounded to zero for display
purposes. When it is set equal to zero, rounding is determined by the field width. Default value is 1.0e-5.
The maximum size of a displayed number must fit within 20 spaces using at most 10 significant digits. The remaining 10
spaces are used for the sign, exponential notation, or padding with zeros.
The following illustrative example shows the results of different combinations of these numeric file suffixes. The example
uses five combinations of the numeric file suffixes .nd, .nz, .nr, and .nw. Four number values, each of which is shifted by
three decimal places from its predecessor, are used with these suffix combinations. The combinations are chosen to show
various format results when these suffix values are used together in put statements:
For readability, the numeric values have purposely been made left justified using the .nj suffix since the numeric field width
is changed as the model goes through the suffix combinations. The following is the resulting file out.put, which shows the
value/suffix combinations:
Notice that in comb1, the display of values switch to exponential notation when a value becomes smaller than the number of
decimal places allowed. This is triggered by the suffix .nr being set to zero. Of particular interest is value3 for comb2 and
comb3. Value3 is greater than the zero tolerance level in .nz, but smaller than the number of decimals allowed by .nd. In
comb2, since .nr is set to zero, the value is displayed in exponential format. In comb3, .nr is set to 1, so this small value is
rounded to 0. In comb6, all values are rounded to integers because .nd is set to 0.
13 Cursor Control
Having described the display of various output items using the put statement, this section describes features available to
position these items in the output file. GAMS has several file suffixes which determine the location of the cursor and the last
line of the file. These suffixes can also be used to reposition the cursor or reset the last line. As such, they are instrumental in
formatting output items in documents. These suffixes are grouped by the title, header, or window writing area for which they
are valid.
Suffix Description
.cc current cursor column in window
.hdcc header current column
.tlcc title current column
The convention for updating the values stored for the .cc, .hdcc, and .tlcc suffixes is that they are updated at the conclusion
of a put statement. Consequently, these values remain constant for the duration of a single put statement, even if multiple
items or lines are displayed.
The following example illustrates the updating of the cursor control suffixes and the use of cursor control characters. The
example is trivial but instructive:
out.cc = 1 x
y
z out.cc = 23
Initially, the scalar lmarg is set to a specific value to use as an alignment tab. Symbols which hold common alignment values
such as margins or tabs are often useful for large structured documents. The first put statement uses the current column
cursor control character to relocate the cursor. In this example, the cursor is moved to column 8 where out.cc and its value
are displayed.
The second put statement illustrates the updating of the cursor control suffixes by writing the letters x, y , and z on three
different lines. Each is preceded by the cursor being moved to the out.cc value. Initially, the value for the cursor control
suffix is 20. Since a single put statement is used for these three items, the out.cc value remains constant and consequently
166 The Put Writing Facility
the letters end up in the same column. Following this put statement, the out.cc value is updated to 23, which is the location
of the cursor at the end of the second put statement (note the additional blank spaces displayed with the letter z).
Suffix Description
.cr current cursor row in window
.hdcr header current row
.tlcr title current row
The convention for updating the values stored for the .cr, .hdcr, and .tlcr suffixes is that they are updated at the conclusion
of a put statement. Consequently, these values remain constant for the duration of a single put statement, even if multiple
items or lines are displayed. Their behavior is similar to that of .cc.
Suffix Description
.ll last line used in window
.hdll header last line
.tlll title last line
Unlike the row and column control, the last line suffix is updated continuously. Last line suffixes are especially useful for
modifying the various writing areas of a page.
Attention
The .tlll and .hdll suffixes may not hold values applicable to the current page because when the title or header
blocks are modified, they correspond to the title or header blocks of the next page whenever the window has been
written to on the current page.
Not only can this suffix be used to determine the last line used in a writing area, but it can also be used to delete
lines within this area.
In the following example, the header section will be completely deleted by resetting the .hdll suffix to 0.
file out;
puthd out This header statement will be eliminated;
out.hdll = 0;
In this example, a header is initially written. By changing the .hdll suffix to 0, the cursor is reset to the top of the header
block. Consequently the header will not be written unless something new is added to the header block.
14 Paging Control 167
14 Paging Control
In addition to the automatic paging, which occurs when the bottom of the page is reached, a page can also be written to file
early. The keyword putpage is used to do this. Putpage forces the current page to immediately be written to file, making a
new page available for put statements. In its simplest form, the keyword putpage is used by itself to eject the current page.
Additionally, it can be used with output items. When it is used with output items, the page is written to file including the
output items contained in the putpage statement. The putpage statement is in fact another variation of the put statement.
In the following statement, the quoted text is placed in the current page, which is then written to the file out.put:
putpage out This text is placed in window and the page ends;
Two additional file suffixes that can help the user in determining when to page a file are:
last page (.lp) Indicates the number of pages that are already in the document. Note that setting this to 0 does
not erase the pages that have previously been written to the file.
window size (.ws) Shows the number of rows, which can be placed in the window, considering the number of
lines that are in the title and header blocks of the current page and the existing page size. The .ws file suffix
value is calculated by GAMS and is not changeable by the user. This suffix is useful for manual pagination when
used in conjunction with the .ll file suffix.
15 Exception Handling
In this section, the topic of exception handling is dealt with. As with other GAMS statements, dollar control exception
handling can be used with put statements to control whether particular output items are displayed. In the following example,
the put statement is only displayed if the dollar condition is true. If it is not, the put statement is ignored:
Syntax errors are caused by the incorrect usage of the GAMS language. These errors are the same or are similar to what one
finds elsewhere with GAMS such as unmatched parentheses, undefined identifiers, uncontrolled sets, or the incorrect use of a
keyword or suffix. These errors are detected during program compilation and are always fatal to program execution. Errors
of this kind are identified in the program listing at the location of the error with a $ symbol and corresponding error numbers.
The program listing includes a brief description of the probable cause of the error.
Put errors are unique to the put writing facility. This type of error occurs during program execution and is caused when
one or more of the file or page attributes are violated. These errors are non-fatal and are listed at the end of the program
listing. They typically occur when a put statement attempts to write outside of a page, such as moving the cursor with the @
character to a location beyond the page width. Other typical errors are the inability to open a specified file, the overflow of a
page, or an inappropriate value being assigned to a suffix. For many of these errors, an additional set of asterisks will be
placed at the location of the error in the output file.
168 The Put Writing Facility
Since put errors are non-fatal and are not overemphasized in the output file, their presence is sometimes overlooked. Without
reviewing the program listing, these put errors might go undetected, especially in large output files. Consequently, GAMS
has included the following file suffix to help one detect errors:
.errors Allows one to display the number of put errors occurring in a file.
To illustrate its use, the following statement could be inserted at any point of a program to detect the number of errors, which
have occurred up to its location. The choice of output file could be the same file, a different file, or the console as appropriate:
In this example it is assumed that the files out.put and error.put have previously been defined with a file statement. With
this statement, the number of put errors that occur in the file out.put are displayed in the file error.put. Using putpage
would allow the immediate display to the screen of a PC system at the location of this statement if the console had been the
output device.
Attention
Avoid horizontal cursor relocations in a program, which creates a delimited file. Horizontally relocating the cursor in a
delimited file is potentially damaging since a delimiter could be overwritten.
While the comma is the most common delimiting character for spreadsheets, other delimiters like blank space and tab
characters can also be used.
17.1 An Example
In the following example, the capacity sub-table of the [MEXSS] report program is prepared as a delimited file. The
following program segment demonstrates .pc suffix value 5. The program segment could be placed at the end of the original
[MEXSS] model:
The first line of this program segment creates the file out.put as the delimited file. Notice that in the remainder of this
program, field widths, justifications, and horizontal cursor relocations are completely avoided. All text items are quoted. The
following is the resulting output file:
"CAPACITY (tons)","AHMSA","FUNDIDORA","SICARTSA","HYLSA","HYLSAP"
"BLAST FURNACES",3.25,1.40,1.10,0.00,0.00
17 Simple Spreadsheet/Database Application 169
Notice that each item is delimited with a comma and that textual output is quoted.
170 The Put Writing Facility
Chapter 16
1 Introduction
The previous chapters have focused on the ability of GAMS to describe models. This chapter will describe the various
programming features available in GAMS to help the advanced user. The various programming flow control features
discussed in this chapter are
loop(controlling_domain[$(condition)],
statement {; statement}
) ;
If the controlling domain consists of more than one set, then parentheses are required around it.
The loop statement causes GAMS to execute the statements within the scope of the loop for each member of the driving
set(s) in turn. The order of evaluation is the entry order of the labels. A loop is thus another, more general, type of indexed
operation. The loop set may be dollar-controlled and does not need to be static or nested. Loops may be controlled by
more than one set.
172 Programming Flow Control Features
Attention
One cannot make declarations or define equations inside a loop statement.
It is illegal to modify any controlling set inside the body of the loop.
2.2 Examples
Consider a hypothetical case when a growth rate is empirical:
set t / 1985*1990 /
parameter pop(t) / 1985 3456 /
growth(t) / 1985 25.3, 1986 27.3, 1987 26.2
1988 27.1, 1989 26.6, 1990 26.6 /;
in an iterative rather than a parallel way. In this example there is one statement in the scope of the loop, and one driving, or
controlling, set.
A loop is often used to perform iterative calculations. Consider the following example, which finds square roots by Newton's
method. This example is purely for illustration - in practice, the function sqrt should be used. Newton's method is the
assertion that if x is an approximation to the square root of v, then (x + v/x)/2 is a better one
scalars
target "number whose square root is needed" /23.456 /
sqrtval "final approximation to sqrt(target)"
curacc "accuracy of current approximation"
reltol "required relative accuracy" / 1.0e-06 / ;
if (condition,
statements;
{elseif condition, statements; }
[else statements;]
);
Attention
One cannot make declarations or define equations inside an if statement.
3.2 Examples
Consider the following set of statements
p(i)$(f <= 0) = -1 ;
p(i)$((f > 0) and (f < 1)) = p(i)**2 ;
p(i)$(f > 1) = p(i)**3 ;
q(j)$(f <= 0) = -1 ;
q(j)$((f > 0) and (f < 1)) = q(j)**2 ;
q(j)$(f > 1) = q(j)**3 ;
if (f <= 0,
p(i) = -1 ;
q(j) = -1 ;
elseif ((f > 0) and (f < 1)),
p(i) = p(i)**2 ;
q(j) = q(j)**2 ;
else
p(i) = p(i)**3 ;
q(j) = q(j)**3 ;
) ;
The body of the if statement can contain solve statements. For instance, consider the following bit of GAMS code:
if ((ml.modelstat eq 4),
* model ml was infeasible
* relax bounds on x and solve again
x.up(j) = 2*x.up(j) ;
solve ml using lp minimizing lp ;
174 Programming Flow Control Features
else
if ((ml.modelstat ne 1),
abort "error solving model ml ;
);
);
The following GAMS code is illegal since one cannot define equations inside an if statement.
if (s gt 0,
eq.. sum(i,x(i)) =g= 2 ;
);
The following GAMS code is illegal since one cannot make declarations inside an if statement.
if (s gt 0,
scalar y ; y = 5 ;
);
while(condition,
statements;
);
Attention
One cannot make declarations or define equations inside a while statement.
4.2 Examples
One can use while statements to control the solve statement. For instance, consider the following bit of GAMS code that
randomly searches for a global optimum of a non-convex model:
In this example, a non-convex model is solved from 1000 random starting points, and the global solution is tracked. The
model [PRIME] from the model library illustrates the use of the while statement through an example where the set of
prime numbers less than 200 are generated
The following GAMS code is illegal since one cannot define equations inside a while statement.
while (s gt 0,
eq.. sum(i,x(i)) =g= 2 ;
);
The following GAMS code is illegal since one cannot make declarations inside a while statement.
while(s gt 0,
scalar y ; y = 5 ;
);
Note that i is not a set but a parameter. Start and end are the start and end, and incr is the increment by which i is
changed after every pass of the loop.
Attention
One cannot make declarations or define equations inside a for statement.
The values of start, end and incr need not be integer. The start and end values can be positive or negative
real numbers. The value of incr has to be a positive real number.
5.2 Examples
One can use forstatements to control the solve statement. For instance, consider the following bit of GAMS code that
randomly searches for a global optimum of a non-convex model:
scalar i ;
scalar globmin ; globmin = inf ;
option bratio = 1 ;
for (i = 1 to 1000,
x.l(j) = uniform(0,1) ;
solve ml using nlp minimizing obj ;
if (obj.l le globmin,
globmin = obj.l ;
globinit(j) = x.l(j) ;
);) ;
176 Programming Flow Control Features
In this example, a non-convex model is solved from 1000 random starting points, and the global solution is tracked.
The use of real numbers as start, end and incr can be understood from the following example,
Notice that the value of s was incremented by 1.4 with each pass of the loop as long as it did not exceed 0.3.
The following GAMS code is illegal since one cannot define equations inside a for statement.
for (s = 1 to 5 by 1,
eq.. sum(i,x(i)) =g= 2 ;
);
The following GAMS code is illegal since one cannot make declarations inside a for statement.
for (s=1 to 5 by 1,
scalar y ; y = 5 ;
);
Chapter 17
1 Introduction
This chapter introduces special features in GAMS that do not translate across solvers, or are specific to certain model types.
These features can be extremely useful for relevant models, and are among the most widely used.
The following types of discrete variables have been discussed so far in the book,
integer variables These can take on integer values between the defined bounds. The default lower and upper
bounds are 0 and 100 respectively.
In addition to these two, two new types of discrete variables that are introduced in this section. Both these variables exploit
special structures in MIP models during the solution phase. These are the following
Special Ordered Sets (SOS) The precise definition of special ordered sets differ from one solver to another and the
development of these features has been driven more by internal algorithmic consideration than by broader modeling
concepts. GAMS offers sos1 and sos2 variables as two types of compromise features that model special ordered sets.
Sections Special Order Sets of Type 1 (SOS1) and Special Order Sets of Type 2 (SOS2) discuss these two types of
variables in greater detail.
Semi-continuous variables GAMS offers semicont and semiint variables to model this class of variables. These
are explained in Sections Special Order Sets of Type 2 (SOS2) and Semi-Continuous Variables .
The presence of any of the above types of discrete variables requires a mixed integer model and all the discreteness is handled
by the branch and bound algorithm in the same way as binary and general integer variables are handled.
178 Special Language Features
At most one variable within a SOS1 set can have a non-zero value. This variable can take any positive value. Special ordered
sets of type 1 are defined as follows,
The members of the innermost (the right-most) index belongs to the same set. For example, in the sets defined above, s1
represents one special ordered set of type 1 with i elements, t1 defines k sets of j elements each, and w1 defines (i,j) sets
with k elements each.
Attention
The default bounds for SOS1 variables are 0 to +. As with any other variable, the user may set these bounds to
whatever is required.
The user can, in addition, explicitly provide whatever convexity row that the problem may need through an
equation that requires the members of the SOS set to be less than a certain value. Any such convexity row would
implicitly define bounds on each of the variables.
The equation defsoss1 implicitly defines the non-zero values that one of the elements of the SOS1 variable s1 can take.
A special case of SOS1 variables is when exactly one of the elements of the set have to be non-zero. In this case, the defsoss1
equation will be
A common use of the use of this set is for the case where the non-zero value is 1. In such cases, the SOS1 variable behaves
like a binary variable. It is only treated differently by the solver at the level of the branch and bound algorithm. For example,
consider the following example to model the case where at most one out of n options can be selected. This is expressed as
The variable x can be made binary without any change in meaning and the solution provided by the solver will be
indistinguishable from the SOS1 case.
The use of special ordered sets may not always improve the performance of the branch and bound algorithm. If there is no
natural order the use of binary variables may be a better choice. A good example of this is the assignment problem.
Attention
Not all MIP solvers allow SOS1 variables. Furthermore, among the solvers that allow their use, the precise definition can
vary from solver to solver. Any model that contains these variables may not be transferable among solvers. Please verify
how the solver you are interested in handles SOS1 variables by checking the relevant section of the Solver Manual.
2 Special MIP Features 179
Attention
The default bounds for SOS2 variables are 0 to +. As with any other variable, the user may set these bounds to
whatever is required.
The members of the innermost (the right-most) index belongs to the same set. For example, in the sets defined above, s2
represents one special ordered set of type 2 with i elements, t2 defines k sets of j elements each, and w2 defines (i,j) sets
with k elements each.
[PRODSCHX] shows SOS type formulations with binary, SOS1 and SOS2 sets. The default bounds for SOS variables are 0
to +. As with any other variable, the user may set these bounds to whatever is required.
Attention
Not all MIP solvers allow SOS2 variables. Furthermore, among the solvers that allow their use, the precise definition can
vary from solver to solver. Any model that contains these variables may not be transferable among solvers. Please verify
how the solver you are interested in handles SOS2 variables by checking the relevant section of the Solver Manual.
semicont variable x ;
x.lo = 1.5 ; x.up = 23.1 ;
The above slice of code declares the variable x to be semi-continuous variable that can either be 0, or can behave as a
continuous variable between 1.5 and 23.1.
Attention
Not all MIP solvers allow semi-continuous variables. Please verify that the solver you are interested in can handle
semi-continuous variables by checking the relevant section of the Solver Manual.
The lower bound has to be less than the upper bound, and both bounds have to be greater than 0. GAMS will flag
an error if it finds that this is not the case.
semiint variable x ;
x.lo = 2 ; x.up = 25 ;
The above slice of code declares the variable x to be semi-continuous variable that can either be 0, or can take any integer
value between 2 and 25.
Attention
Not all MIP solvers allow semi-integer variables. Please verify that the solver you are interested in can handle
semi-integer variables by checking the relevant section of the Solver Manual.
The lower bound ( L) has to be less than the upper bound ( U), and both bounds have to be greater than 0. GAMS
will flag an error during model generation if it finds that this is not the case.
The bounds for semiint variables have to take integer values. GAMS will flag an error during model generation
if it finds that this is not the case.
The user can specify an order for picking variables to branch on during a branch and bound search for MIP models through
the use of priorities. Without priorities, the MIP algorithm will determine which variable is the most suitable to branch on.
The GAMS statement to use priorities for branching during the branch and bound search is:
mymodel.prioropt = 1 ;
where mymodel is the name of the model specified in the model statement. The default value is 0 in which case priorities
will not be used.
Using the .prior suffix sets the priorities of the individual variables. Note that there is one prior value for each individual
component of a multidimensional variable. Priorities can be set to any real value. The default value is 1. As a general rule of
thumb, the most important variables should be given the highest priority.
The following example illustrates its use,
z.prior(i,small) = 3 ;
z.prior(i,medium) = 2 ;
z.prior(i,large) = 1 ;
In the above example, z(i,'large') variables are branched on before z(i, 'small') variables.
Attention
The lower the value given to the .prior suffix, the higher the priority for branching.
All members of any SOS1 or SOS2 set should be given the same priority value since it is the set itself which is
branched upon rather than the individual members of the set.
The statement should be inserted somewhere after the model statement and before the solve statement. In order to turn
scaling off again, set the model.scaleopt parameter to 0 before the next solve.
The scale factor of a variable or an equation is referenced with the suffix .scale, i.e. the scale factor of variable x(i) is
referenced as x.scale(i). Note that there is one scale value for each individual component of a multidimensional variable
or equation. Scale factors can be defined using assignment statements. The default scale factor is always 1.
GAMS scaling is in most respects hidden from the user. The solution values reported back from a solution algorithm are
always reported in the user's notation. The algorithm's versions of the equations and variables are only reflected in the
derivatives in the equation and column listings in the GAMS output if the options limrow and limcol are positive, and the
debugging output from the solution algorithm generated with sysout option set to on.
By setting x1.scale to 0.01 and x2.scale to 10, the model seen by the solver is,
Note that the solver does not see the variables x1 or x2, but rather the scaled (and better-behaved) variables xprime1 and
xprime2.
Attention
Upper and lower bounds on variables are automatically scaled in the same way as the variable itself.
Integer and binary variables cannot be scaled.
Attention
The user may have to perform a combination of equation and variable scaling until a well-scaled model is obtained.
x1.scale = 0.1 ;
eq1.scale = 5 ;
eq2.scale = 5 ;
will result in the solver seeing the following well scaled model,
Portfolio Optimization
Quadratic Programming
Co