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
Conic programs can be thought of as generalized linear programs with the additional nonlinear constraint x C, where C is
required to be a convex cone. The resulting class of problems is known as conic optimization and has the following form:
minimize cT x
subject to Ax rc ,
x [l x , ux ]
x C
where A Rmn is the constraint matrix, x Rn the decision variable, and c Rn the objective function cost coefficients.
The vector rc Rm represents the right hand side and the vectors l x , ux Rn are lower and upper bounds on the decision
variable x.
Now partition the set of decision variables x into sets St ,t = 1, ..., k, such that each decision variables x is a member of at
most one set St . For example, we could have
C := {x Rn : xSt Ct ,t = 1, ..., k} ,
These two types of cones allow the formulation of quadratic, quadratically constrained, and many other classes of nonlinear
convex optimization problems.
184 Special Language Features
Quadratic cone:
Note that the resulting nonlinear conic constraints result in linear constraints in GAMS. Thus the original nonlinear
formulation is in fact a linear model in GAMS. We remark that we could formulate conic problems as regular NLP using
constraints:
Quadratic cone:
The following example illustrates the different formulations for conic programming problems. Note that a conic optimizer
usually outperforms a general NLP method for the reformulated (NLP) cone problems.
4.3 Examples
Consider the following example, which illustrates the use of rotated conic constraints. We will give reformulations of the
original problem in regular NLP form using conic constraints and in conic form.
The original problem is:
n
di
minimize xi (17.1)
i=1
0
subject to a x b (17.2)
xi [li , ui ], i = 1, . . . , n (17.3)
where x Rn is the decision variable, d, a, l, u Rn parameters with li > 0 and di 0, and b R a scalar parameter. The
original model can be written in GAMS using the equations:
We can write an equivalent QCP formulation, by using the substitution ti = 1/xi in the objective function and adding a
constraint. As we are dealing with a minimization problem, di 0 and xi li > 0, we can relax the equality ti xi = 1 into an
inequality ti xi 1, which results in an equivalent problem with convex feasible set:
4 Conic Programming in GAMS 185
n
minimize diti (17.4)
i=1
0
subject to a x b (17.5)
ti xi 1, i = 1, . . . , n (17.6)
x [l, u], (17.7)
t 0, (17.8)
(17.9)
where t Rn is a new decision variable. The GAMS formulation of this QCP (model cqcp) is:
Note that the constraints ti xi 1 are almost in rotated conic form. If we introduce a variable z Rn with zi = 2, then we
can reformulate the problem using conic constraints as:
n
minimize diti (17.10)
i=1
0
subject to a x b (17.11)
zi = 2, i = 1, . . . , n (17.12)
2ti xi z2i , i = 1, . . . , n (17.13)
x [l, u], (17.14)
t 0, (17.15)
(17.16)
Note that this formulation is a linear program in GAMS, although the constraints cone(n) represent the nonlinear rotated
quadratic cone constraints.
The complete model is listed below:
Set n / n1*n10 /;
Parameter d(n), a(n), l(n), u(n);
Scalar b;
d(n) = uniform(1,2);
a(n) = uniform (10,50);
l(n) = uniform(0.1,10);
u(n) = l(n) + uniform(0,12-l(n));
Variables x(n);
x.l(n) = uniform(l(n), u(n));
b = sum(n, x.l(n)*a(n));
t.lo(n) = 0;
x.lo(n) = l(n);
x.up(n) = u(n);
Option qcp=cplexd;
Option lp=mosek;
Solve cqcp min obj using qcp;
Solve clp min obj using lp;
Solve orig min obj using nlp;
qp7.gms: Portfolio investment model using rotated quadratic cones (quadratic program using a Markowitz model)
Pataki, G, and Schmieta, S, The DIMACS library of semidefinite-quadratic-linear programs. Tech. rep., Computational
Optimization Research Center, Columbia University, 2002.
5 Indicator Constraints
An indicator constraint is a way of expressing relationships among variables by specifying a binary variable to control
whether or not a constraint takes effect. For example, indicator constraints are useful in problems where there are fixed
charges to express only if a given variable comes into play.
So-called Big M formulations often exhibit trickle flow, and at times, they behave unstably. The main purpose of indicator
constraints is to avoid the unwanted side-effects of Big M formulations. Generally, the use of indicator constraints is not
warranted when the unwanted side-effects of Big M formulations are not present.
For example, instead of the following Big M formulation, which relies on the x values summing to less than one billion (a
formulation that can cause numeric instability or undesirable solutions in some situations):
5 Indicator Constraints 187
a natural way of entering an indicator constraint, where y is a binary variable, would look like this:
In the following, we will describe how to specify indicator constraints when using GAMS/CPLEX. For other solver interfaces
that support this construct, the syntax is similar. Please consult the corresponding solver manual for information on whether
indicator constraints are supported and possible differences in their specification.
The example from above would be implemented in the following way:
constr01.. x1 + x2 + x3 =l= 0;
indic constr01$y 0
This has the following effect: Equation constr01 will become an indicator constraint and becomes effective in a solution
where the binary variable takes the value 0. If the value of y in a solution is 1, the constraint is not active.
Note, that this way of entering an indicator constraint is dangerous since the option files changes the model (usually an
option file has some effect on the performance of the algorithm). Therefore, GAMS/CPLEX will abort if there is a problem
processing the indicator options in the Cplex option file. Moreover, if the model is given to a different solver or to CPLEX
without the option file containing the indicator mapping, a very different model is solved. The current implementation of
indicator constraints requires a significant amount of caution from the user.
There are two ways of entering the equation/binary variable mapping in a Cplex option file:
The indexed format is a convenient short hand notation which borrows its syntax from the GAMS syntax. It requires that the
indexes for the binary variable are already present in the index set of the equation. For example, the following invalid GAMS
syntax with an endogenous variable in the $-condition
indic equ1(i,j,k)$bin1(i,k) 1
In cases where the binary variable indexes are not present in the equation indexes (or is adjusted using lags or leads), one
needs to specify the mapping of all individual equations and variables of the indicator constraints. For example,
This would be specified using the label format of indicator constraint as follows. The GAMS file
indic equ1(i1,j1)$bin1(j2) 0
indic equ1(i1,j2)$bin1(j1) 0
indic equ1(i2,j1)$bin1(j2) 0
indic equ1(i2,j2)$bin1(j1) 0
indic equ1(i3,j1)$bin1(j2) 0
indic equ1(i3,j2)$bin1(j1) 0
Such option files can be easily generated using The Put Writing Facility :
There are situation where the binary variable shows up the in indicator constraints only and hence will not be generated by
GAMS to be passed on to Cplex. In such cases Cplex will issue an error message:
In such cases the binary variable has to be added artificially to the model, e.g. but adding them with cost EPS to the objective:
The GAMS model libraries contain a few examples that use indicator constraints. For example, check out the model
[BILINEAR] in the GAMS Model Library.
Finally, we want to present a fixed-charge network example based on the [TRNSPORT] model from the GAMS Model
library that used indicator constraints, big M forumulations and a formulation that makes it easy to switch between these
two.
Sets
i canning plants / seattle, san-diego /
j markets / new-york, chicago, topeka / ;
Parameters
Variables
x(i,j) shipment quantities in cases
use(i,j) is 1 if arc is used in solution
z total transportation costs in thousands of dollars ;
Equations
cost define objective function
supply(i) observe supply limit at plant i
demand(j) satisfy demand at market j
minship(i,j) ensure minimum shipping
maxship(i,j) ensure zero shipping if use variable is 0;
* Now lets build a model for the same problem using indicator constraints
Equations
iminship(i,j) ensure minimum shipping using indicator constraints
imaxship(i,j) ensure zero shipping if use variable is 0 using indicator constraints;
* Now lets build a model for the same problem that can be used with
* and without indicator constraints. This can become handy when
* debugging a model with indicator constraints
Equations
xminship(i,j) ensure minimum shipping using indicator constraints and bigM
xmaxship(i,j) ensure zero shipping ig use variable is 0 using indicator constraints and bigM
bndminslack(i,j) ensure minslack is zero if use variable is 1
bndmaxslack(i,j) ensure maxslack is zero if use variable is 0;
* Now we will use indicators and therefore we dont need the slacks
minslack.fx(i,j) = 0; maxslack.fx(i,j) = 0;
indicatorbigMModel.optfile = 1; Solve indicatorbigMModel using mip minimizing z ;
Advanced Topics
Chapter 18
Glossary
acronym A GAMS data type used to give logical classifications to data points.
An inequality constraint is binding when the value of the associated slack is zero.
binding
Upper and lower limits on the possible values that a column may assume in a feasible
bounds
solution. May be infinite, meaning that no limit is imposed.
An individual decision variable in the model seen by a solver program. Many may be
column
associated with one GAMS variable
The initial phase of GAMS processing, when the program is being checked for syntax
compilation
and consistency.
A relationship between columns that must hold in a feasible solution. There may be
constraint
many constraints associated with one GAMS equation.
There are two contexts. First a classification of a function. A plot of the function values
continuous
will be a line without breaks in it. Second, a classification of variables. A continuous
variable may assume any value within its bounds.
Each symbol or identifier has to be declared to be one of the seven data types, which are
data types
set, parameter, variable, equation, model, file and acronym. The keywords scalar
and table do not introduce separate data types but rather comprise a shorthand way to
declare a symbol to be a parameter that will use a particular format for specifying initial
values.
The entry of a symbol and the specification of its data type. A declaration may include
declaration
the specification of initial values, and then it is more properly called a definition.
The value used, or the action taken, if the user provides no information.
default
The definitions of the algebraic relationships in an equation are the assignment of
definition
initial values to parameters or of elements to sets as part of the initial declaration of the
identifier.
Units that describe symbols, assign initial values to them, and describe symbolic rela-
definition statements
tionships. Some examples of the set, parameter, table, and model statements, and
the equation definition statement.
A classification of a function. A plot of the function values will be a line with breaks in
discontinuous
it.
A discrete variable (type binary or integer) may not assume any value between the
discrete
bounds, but must assume integer values.
Directives or options used to control input or output detail associated with the GAMS
dollar control option
compiler.
The check that ensures that only legal label combination are used on every assignment
domain checking
to, or reference of, an identifier.
The label combinations whose data will be updated in an assignment statement, or that
domain definition
will generate an individual constraint in an equation definition.
The alteration to the domain of definition caused when a dollar operator is used on the
domain restriction condition
left (of the '= in an assignment or of the '..' in an equation definition).
The set that determine the domain of definition, or that control and index operation such
driving set
as sum.
A set is dynamic if it has been changed with an assignment statement. Dynamic sets
dynamic set
cannot be used with lag operations or in domain definitions.
Data values that change when a solve statement is processed. In GAMS most often
endogenous
associated with variables.
The GAMS data type used to specify required relationships between activity levels of
equation
variables.
The second phase of GAMS processing, when GAMS is actually carrying out data
execution
transformations or generating a model.
195
Instructions to carry out actions such as data transformations, model solutions, and
execution statements
report generation. Some examples are the assignment and the option, display, loop
and solve statements.
exogenous Data values known before a solve statement is processed, and not changed by the solve.
In GAMS most often parameters.
See text.
explanatory text
A scale factor used to conveniently represent very large or small numbers.
exponent
The usual computer arithmetic is extended to include plus and minus infinity (+inf
extended arithmetic
and -inf) and a special value for an arbitrarily a small number (i.e. one which is
close to zero) known as epsilon (eps). Also, not available (na) can be used to indicate
missing data, and undefined (undf) is the result of illegal operation. GAMS allows
extended arithmetic for all operations and functions. The library problem [CRAZY]
demonstrates extended arithmetic by showing the results for all operations and functions.
Often used to describe a model that has at least one feasible solution. See also infeasible.
feasible
A solution to a model in which all column activity levels are within the bounds and all
feasible solution
the constraints are satisfied.
The person who looks after the administration of a GAMS system, and who will know
GAMS coordinator
what solvers are available and can tell you who to approach for help with GAMS
problems. Unlikely to apply to personal computer versions.
A constraint in which the imposed relationship between the columns is not fixed, but
inequality constraint
must be either greater than or equal to, or less than or equal to, a constant. The GAMS
symbols =g= and =l= are used in equation definitions to specify these relationships.
Used to describe either a model that has no feasible solution, or an intermediate solution
infeasible
that is not feasible (although feasible solutions may exist). See also feasible.
Associating initial values with sets or parameters using lists as part of the declaration or
initialization
definition, or (for parameters only) using table statements.
One of the ways of specifying initial values. Used with sets or parameters, most often
list
for one-dimensional but also for two and higher dimensional data structures.
One of the ways in which sets and parameters, can be initialized and all symbol classes
list format
having data can be displayed. Each unique label combination is specified in full, with
the associated non-default value alongside.
Often called reduced costs or dual values. The values, which are meaningful only for
marginal
non-basic rows or columns in optimal solutions, contain information about the rate at
which the objective value will change of if the associated bound or right hand side is
changed.
The initial phase of processing a solve statement: preparing a problem description for
model generation
the solver.
There are two contexts. First, describing a variable: a non-basic variable that would
nonoptimal
improve the objective value if made basic. The sign of the marginal value is normally
used to test for non-optimality. Second, for a solution: other solutions exists with better
objective values.
A classification of function that does not have continuous first derivatives, but has
nonsmooth
continuous function values. A plot of the function values will be a line with kinks in it.
The coefficient of a particular column in a particular row if it is not zero. Most math-
nonzero element
ematical programming problems are sparse meaning that only a small proportion of
the entries in the full tableau of dimensions number of rows by number of columns is
different from zero.
Solver system require the specification of a row on (for nonlinear systems) a function
objective row (or function)
whose value will be maximized or minimized. GAMS users, in contrast, must specify a
scalar variable.
A set is ordered if its content has been initialized with a set definition statement
ordered set
and the entry order of the individual elements of the set has the same partial order as
the chronological order of the labels. A set name alone on the left-hand side of an
assignment statement destroys the ordered property. Lag and Ord operations rely on the
relative position of the individual elements and therefore require ordered sets. Ordered
sets are by definition constant.
A model class that is dependent on functional form and specification. Examples are
problem type
linear, nonlinear, and mixed integer programs.
program A GAMS input file that provides a representation of the model or models.
197
This term may be used in two ways. First, in an equation definition it describes the type
relational operator
of relationships the equation specifies, for example equality, as specified with the =e=
symbol. Second, in a logical expression, the symbols eq, ne, lt and so on are also
called relational operators, and are used to specify a required relationship between two
values.
Sometimes called units. The fundamental building block of GAMS programs. State-
statements
ments or sentences that define data structures, initial values, data modifications, and
symbolic relationships. Examples are table, parameter, variable, model, assign-
ment and display statements.
An identifier.
symbol
One of the ways of initializing parameters. Used for two and higher dimensional data
table
structures.
Professor Paul Samuelson is fond of saying that he hopes each generation economists will be able to "stand on the
shoulders" of the previous generation. The library of models included with the GAMS system is a reflection of this desire.
We believe that the quality of modeling will be greatly improved and the productivity of modelers enhanced if each generation
can stand on the shoulders of the previous generation by beginning with the previous models and enhancing and improving
them. Thus the GAMS systems includes a large library, collectively called GAMSlib.
The models included have been selected not only because they collectively provide strong shoulders for new users to stand on,
but also because they represent interesting and sometimes classic problems. For example the trade-off between consumption
and investment is richly illustrated in the Ramsey problem, which can be solved using nonlinear programming methods.
Examples of other problems included in the library are production and shipment by firms, investment planning in time and
space, cropping patterns in agriculture, operation of oil refineries and petrochemical plants, macroeconomics stabilization,
applied general equilibrium, international trade in aluminum and in copper, water distribution networks, and relational
databases.
Another criterion for including models in the library is that they illustrate the modeling capabilities GAMS offers. For
example, the mathematical specification of cropping patterns can be represented handily in GAMS. Another example of
the system's capability is the style for specifying initial solutions as staring points in the search for the optimal solution of
dynamic nonlinear optimization problems.
Finally, some models have been selected for inclusion because they have been used in other modeling systems. Examples are
network problems and production planning models. These models permit the user to compare how problems are set up and
solved in different modeling systems.
Most of the models have been contributed by GAMS users. The submission of new models is encouraged. If you would like
to see your model in a future release of the library, please send the model and associated documents and reports to GAMS
Development Corporation.
The most convenient way (Windows only) to access the model library is from within the GAMS IDE by going through: File
Model Library Open GAMS Model Library. A window will pop up and give you access to all models.
Another way to access the library is through the gamslib command. This command copies a model from the library directory
into the current directory. If you enter gamslib without any parameters, the command syntax will be displayed as shown
below:
or
where modelname is the modelname, modelnum is the model sequence number, and target is the target file name. If the
target file name is not provided, the default is modelname.gms. For example, the [TRNSPORT] model could be copied in
any of the following ways
200 The GAMS Model Library
The full and annotated list of the models of the GAMS Model Library is available at: GAMS Model library.
Chapter 20
The entire GAMS system appears to the user as a single call that reads the input files and produces output files. Several
options are available at this level to customize the GAMS run and define the output desired. Although details will vary with
the type of computer and operating system used, the general operating principles are the same on all machines.
from the system prompt and GAMS will compile and execute the GAMS statements in the file myfile. If a file with this
name cannot be found, GAMS will look for a file with the extended name myfile.gms. The output will be written by default
on the file myfile.lst. For example, the following statement compiles and executes the example problem [TRNSPORT]
from the GAMS model library,
where key1 is the name of the option that is being set on the command line, and value1 is the value to which the option is
set. Depending on the option, value1 could be a character string, an integer number or a real number. For example, consider
the following commands to run [TRNSPORT] from the GAMS model library,
All the four commands above are equivalent, and each directs the output listing to the file myrun.lst. o is the name of the
option, and it is set to myrun.lst. In addition, in each case, the log of the run is redirected to the file trnsport.log.
202 The GAMS Call
This section describes each of the command line parameters in detail. These parameters are in alphabetical order for easy
reference. In each of the following options, an abbreviation and the default value, if available, are bracketed.
Action (string): GAMS processing requests -
Synonym: A
3 Detailed Description of Command Line Parameters 209
GAMS currently processes the input file in multiple passes. The three passes in order are:
Compilation During this pass, the file is compiled, and syntax errors are checked for. Data initialization
statements like scalar, parameter, and table statements are also processed during this stage.
Execution During this stage, all assignment statements are executed.
Model Generation During this stage, the variables and equations involved in the model being solved are
generated.
Default: CE
value meaning
R Restart After Solve
C CompileOnly
E ExecuteOnly
CE Compile and Execute
G Glue Code Generation
GT Trace Report
value meaning
0 reset expand file
1 append to expand file
value meaning
0 reset log file
1 append to logfile
value meaning
0 reset listing file
1 append to listing file
AsyncSolLst (integer): Print solution listing when asynchronous solve (Grid or Threads) is used -
210 The GAMS Call
Default: 0
value meaning
0 Do not print solution listing into lst file for asynchronous solves
1 Print solution listing into lst file for asynchronous solves
value meaning
0 write listing file in mixed case
1 write listing file in upper case only
Default: 0
value meaning
0 no error limit (default)
n stop after n errors
value meaning
0 use limited GAMS characters set
1 accept any character in comments and text items (foreign language characters)
3 Detailed Description of Command Line Parameters 211
value meaning
0 date as mm/dd/yy
1 date as dd.mm.yy
2 date as yy-mm-dy
parameters
a(i) capacity of plant i in cases
/ seattle 350
san-diego 600 /
variables
x(i,j) shipment quantities in cases
z total transportation costs in thousands of dollars ;
positive variable x ;
equations
cost define objective function
supply(i) observe supply limit at plant i
demand(j) satisfy demand at market j ;
All comments have been removed from [TRNSPORT] for brevity. Running this model and saving the work
files through the save parameter leads to the generation of eight work files. The second file (say trans2.gms)
generated from [TRNSPORT] looks as follows,
solve transport using lp minimizing z ;
display x.l, x.m ;
One can then run trans2.gms restarting from the saved work files generated from running trans1.gms. The
result obtained is equivalent to running [TRNSPORT].
Attention
In order to use the dumpopt parameter effectively, it is required that the first line in the restart file is the
solve statement.
To illustrate the use of the dumpopt option, run the second model using the following command
gams trans2 r=trans dumpopt=1
where trans is the name of the saved files generated through the save parameter from trans1.gms. A new
file trans2.dmp is created as a result of this call, and looks as follows,
* This file was written with DUMPOPT=1 at 11/30/11 08:43:06
*
* INPUT = C:\Fred\GAMS options\test\trnsport2.gms
* DUMP = C:\Fred\GAMS options\test\trnsport2.dmp
* RESTART = C:\Fred\GAMS options\test\trans1.g0?
*
* with time stamp of 11/30/11 08:40:41
*
* You may have to edit this file and the input file.
Model transport;
Note that all the data entering the model in the solve statement has been regenerated. The parameter d has
not been regenerated since it does not appear in the model, but the parameter c is. Changing the value of the
parameter dumpopt will result in alternate names being used for the identifiers in the regenerated file.
Default: 0
value meaning
0 no dumpfile
1 extract referenced data from the restart file using original set element names
2 extract referenced data from the restart file using new set element names
3 extract referenced data from the restart file using new set element names and drop symbol text
4 extract referenced symbol declarations from the restart file
11 write processed input file without comments
21 write processed input file with all comments
value meaning
0 no logging
1 lists accepted/set parameters
2 log of file operations plus list of accepted/set parameters
value meaning
0 any number of keys or values
1 only one key-value pair on a line
The listing file that results from running this model contains the following section,
1 set i /1*10/ ; set j(i) /10*11/;
**** $170
2 parameter a(jj) / 12 25.0 / ;
**** $120
3
Note that numbers ($170 and $120) flag the two errors as they occur, but the errors are explained only at the end
of the source listing. However, if the code is run using the option errmsg=1, the resulting listing file contains
the following,
1 set i /1*10/ ; set j(i) /10*11/;
**** $170
**** 170 Domain violation for element
2 parameter a(jj) / 12 25.0 / ;
**** $120
**** 120 Unknown identifier entered as set
3
Note that the explanation for each error is provided immediately following the error marker.
Default: 0
value meaning
0 Place error messages at the end of compiler listing
1 Place error messages immediately following the line with the error
2 Suppress error messages
ErrorLog (integer): Max error message lines written to the log for each error -
Synonym: ER
value meaning
0 no error messages to LOG file
n Number of lines for each error that will be written to LOG file
Default: 0
value meaning
0 no errors allowed limit
n max number allowed
value meaning
0 everything allowed
1 interactive shells in $call and execute commands are prohibited
2 all $call and execute commands are prohibited
3 $echo or put commands can only write to directories in or below the working or scratchdir
4 $echo and put commands are not allowed
a = a+1 ;
display a ;
Running the model with the command line flag expand myfile.fil results in the creation of the file
myfile.fil. The content of this file is provided below,
1 INPUT 0 0 0 1 7 E:\TEMP\FILE1.GMS
2 INCLUDE 1 1 2 2 4 E:\TEMP\FILE2.INC
3 INCLUDE 1 1 3 5 7 E:\TEMP\FILE2.INC
The first row always refers the parent file called by the GAMS call. The first column gives the sequence number
of the input files encountered. The second column refers to the type of file being referenced. The various types
of files are
0 INPUT
1 INCLUDE
2 BATINCLUDE
3 LIBINCLUDE
4 SYSINCLUDE
The third column provides the sequence number of the parent file for the file being referenced. The fifth column
gives the local line number in the parent file where the $include appeared. The sixth column gives the global
(expanded) line number which contained the $include statement. The seventh column provides the total
number of lines in the file after it is processed. The eighth and last column provides the name of the file.
FDDelta (real): Step size for finite differences -
Range: [1.000000000000000E-9, 1]
Default: 1.000000000000000E-5
FDOpt (integer): Options for finite differences -
Default: 0
value meaning
0 All derivatives analytically, for numerical Hessian use gradient values, scale delta
1 All derivatives analytically, for numerical Hessian use function values, scale delta
2 Gradient analytically, force Hessian numerically using gradient values, scale delta
3 Gradient analytically, force Hessian numerically using function values, scale delta
4 Force gradient and Hessian numerically, scale delta
10 Same as 0, but no scale of delta
11 Same as 1, but no scale of delta
12 Same as 2, but no scale of delta
13 Same as 3, but no scale of delta
14 Same as 4, but no scale of delta
The first column refers to the global row number of the error in the listing file. The second column refers to the
row number of the error in the individual file where the problem occurs. This will be different from the first
column only if the error occurs in an include file. In this case, the second column will contain the line number in
the include file where the error occurs, while the first number will contain the global line number (as reported in
the listing file) where the error occurs. The number in the third column refers to the error number of the error.
The fourth number refers to the column number of the error in the source file. The fifth column contains the
individual file in which the error occurred.
FileCase (integer): Casing of new file names (put, gdx, ref etc.) -
This option allows one to alter the file name casing GAMS uses in saving put, gdx, ref etc. files. It only works
with new file names but for example it won't create trnsport.REF if TRNSPORT.ref already exists.
Default: 0
value meaning
0 causes GAMS to use default casing
1 causes GAMS to uppercase filenames
2 causes GAMS to lowercase filenames
FileStem (string): Sets the file stem for output files which use the input file name as stem by default -
Sets the base of the file name for all output files which use the input file name as base by default (as long as
those names are not set explicitly). In particular, the following files can be set by fileStem: dump file (see
DumpOpt), GDX file (if GDX was set to default), log file (see LogFile), lst file (see Output), reference file (if
Reference was set to default), and trace summary file.
Default: <input file basename>
ForceOptFile (integer): Overwrites other option file section mechanism -
Default: 0
ForceWork (integer): Force newer GAMS systems to translate and read save files generated by older systems -
Synonym: FW
Most of the work files generated by GAMS using the save option are in binary format. The information inside
these files will change from version to version. Every attempt is made to be backward compatible and ensure
that all new GAMS systems are ablse to read save files generated by older GAMS systems. However, at certain
versions, we are forced to concede default incompatibility (regarding save files, not source files) in order to
protect efficiency. The forcework option is used to force newer GAMS systems into translating and reading
save files generated by older systems.
Default: 0
value meaning
0 no translation
1 try translation
Default: 0
value meaning
0 workfile only written to file specified by SAVE if no errors occur
1 workfile always written to file specified by SAVE or if SAVE is not present to a name made up by
GAMS
Default: 0
value meaning
0 use only latest syntax
1 allow version 2.05 syntax only
2 allow version 2.25 syntax only
value meaning
0 do not compress gdx files
1 compress gdx files
value meaning
v5 version 5 gdx file, does not support compression
v6 version 6 gdx file
3 Detailed Description of Command Line Parameters 219
value meaning
v7 version 7 gdx file
value meaning
Squeezed write only the UELs to Universe, that are used by the exported symbols
Full write all UELs to Universe
value meaning
0 fixed variables are not treated as constants
1 fixed variables are treated as constants
value meaning
0 unknown environment
1 runs under GAMS IDE
Synonym: I
Completing the input file name with the current directory composes the final name. If such a file does not exist
and the extension was not specified, the standard input extension is attached and a second attempt is made to
open an input file.
Default: Filename
InputDir (string): Input file directories -
Synonym: IDIR
In general, GAMS searches for input and include files in the current working directory only. This option allows
the user to specify additional directories for GAMS to search for include and batinclude files. A maximum of 40
separate directories can be included with the directories separated by Operating System specific symbols. On a
PC the separator is a semicolon (;) character, and under Unix it is the colon (:) character. Note that libinclude
and sysinclude files are handled differently, and their paths are specified by libincdir and sysincdir.
Consider the following illustration:
gams myfile idir \mydir;\mydir2
The search order for the file myfile (or myfile.gms) and all included files in PC systems is as follows: (1)
current directory, (2) directories specified by inputdir (\mydir and \mydir2 directories) in order. Under
Unix, the corresponding command is
gams myfile idir \mydir:\mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir10 (string): Input file directory number N -
Synonym: IDIR10
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
3 Detailed Description of Command Line Parameters 221
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir11 (string): Input file directory number N -
Synonym: IDIR11
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir12 (string): Input file directory number N -
Synonym: IDIR12
222 The GAMS Call
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir13 (string): Input file directory number N -
Synonym: IDIR13
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir14 (string): Input file directory number N -
3 Detailed Description of Command Line Parameters 223
Synonym: IDIR14
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir15 (string): Input file directory number N -
Synonym: IDIR15
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
224 The GAMS Call
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir17 (string): Input file directory number N -
Synonym: IDIR17
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
3 Detailed Description of Command Line Parameters 225
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir18 (string): Input file directory number N -
Synonym: IDIR18
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir19 (string): Input file directory number N -
Synonym: IDIR19
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
226 The GAMS Call
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir2 (string): Input file directory number N -
Synonym: IDIR2
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir20 (string): Input file directory number N -
Synonym: IDIR20
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
3 Detailed Description of Command Line Parameters 227
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir21 (string): Input file directory number N -
Synonym: IDIR21
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir22 (string): Input file directory number N -
Synonym: IDIR22
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
228 The GAMS Call
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir23 (string): Input file directory number N -
Synonym: IDIR23
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir24 (string): Input file directory number N -
Synonym: IDIR24
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir25 (string): Input file directory number N -
Synonym: IDIR25
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir26 (string): Input file directory number N -
Synonym: IDIR26
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
230 The GAMS Call
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir27 (string): Input file directory number N -
Synonym: IDIR27
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir28 (string): Input file directory number N -
Synonym: IDIR28
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3 Detailed Description of Command Line Parameters 231
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir29 (string): Input file directory number N -
Synonym: IDIR29
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir3 (string): Input file directory number N -
Synonym: IDIR3
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
232 The GAMS Call
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir30 (string): Input file directory number N -
Synonym: IDIR30
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir31 (string): Input file directory number N -
Synonym: IDIR31
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir32 (string): Input file directory number N -
Synonym: IDIR32
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir33 (string): Input file directory number N -
Synonym: IDIR33
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
234 The GAMS Call
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir34 (string): Input file directory number N -
Synonym: IDIR34
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir35 (string): Input file directory number N -
Synonym: IDIR35
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
3 Detailed Description of Command Line Parameters 235
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir36 (string): Input file directory number N -
Synonym: IDIR36
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir37 (string): Input file directory number N -
Synonym: IDIR37
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
236 The GAMS Call
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir38 (string): Input file directory number N -
Synonym: IDIR38
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir39 (string): Input file directory number N -
Synonym: IDIR39
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
3 Detailed Description of Command Line Parameters 237
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir4 (string): Input file directory number N -
Synonym: IDIR4
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir40 (string): Input file directory number N -
Synonym: IDIR40
238 The GAMS Call
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir5 (string): Input file directory number N -
Synonym: IDIR5
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir6 (string): Input file directory number N -
3 Detailed Description of Command Line Parameters 239
Synonym: IDIR6
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir7 (string): Input file directory number N -
Synonym: IDIR7
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
240 The GAMS Call
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
InputDir9 (string): Input file directory number N -
Synonym: IDIR9
This keyword gives the name of the directories to be searched by GAMS given a file name with number 1 being
first then number 2 etc up to 40 when encountering an include or batinclude. Directory names must be listed in a
form consistent with the way of indicating directory names on the operating system being employed.
The same information as in inputdir can be transferred to GAMS by entering the individual directories
separately. A maximum of 40 directories can be passed on in this manner. The number appended to inputdir
is important because the earlier inputdir directories are searched first.
The example used to illustrate the inputdir option can also be equivalently called as
gams myfile idir1 mydir1 idir2 mydir2
1. current directory
2. mydir1
3. mydir2
then the search order is altered to be as follows: Note that the search order in this case is as follows:
1. current directory
2. mydir2
3. mydir1
3 Detailed Description of Command Line Parameters 241
Note that it is not the order in which they are specified that matters but the number of the inputdir that they have
been assigned to.
Integer1 (integer): Integer communication cell N -
This integer communication cell that can contain any integer number.
Integer2 (integer): Integer communication cell N -
This integer communication cell that can contain any integer number.
Integer3 (integer): Integer communication cell N -
This integer communication cell that can contain any integer number.
Integer4 (integer): Integer communication cell N -
This integer communication cell that can contain any integer number.
Integer5 (integer): Integer communication cell N -
This integer communication cell that can contain any integer number.
InteractiveSolver (integer): Allow solver to interact via command line -
Default: 0
value meaning
0 Interaction with solvelink 0 is not supported
1 Interaction with solvelink 0 is supported
value meaning
0 set default upper bound for integer variables to +INF
1 pass a value of 100 instead of +INF to the solver as upper bound for integer variables
2 same as 0 but writes a message to the log if the level of an integer variable is greater than 100
3 same as 2 but issues an execution error if the level of an integer variable is greater than 100
value meaning
0 delete process dir
1 keep process dir
GAMS searches for any referenced $libinclude file in the directory <GAMS System Directory>/mydir.
Default: <GAMS System Directory>/inclib
License (string): Use alternative license file -
This option should only be used by advanced users attempting to override internal license information. The file
name is used as given. The default license file is gamslice.txt in the GAMS system directory.
Default: <GAMS System Directory>/gamslice.txt
LimCol (integer): Maximum number of columns listed in one variable block -
This controls the number of columns that are listed for each variable in the COLUMN LISTING section of the
listing file. Specify zero to suppress the COLUMN LISTING altogether.
Default: 3
LimRow (integer): Maximum number of rows listed in one equation block -
This controls the number of rows that are listed for each equation in the EQUATION LISTING section of the
listing file. Specify zero to suppress the LISTING altogether
Default: 3
LogFile (string): Log file name -
Synonym: LF
This option is used in conjunction with the LogOption. If lo is set to 2, then this option will specify the name of
the log file name. The name provided by the option is completed using the current directory. If no logfile is
given but the value of lo is 2, then the file name will be input file name with the extension .log.
To illustrate the use of the logfile option, run [TRNSPORT] with the options lo=2 and lf=myfile.log. The
resulting log file is redirected to myfile.log, and looks as follows:
--- Starting compilation
--- trnsport.gms(69) 3 Mb
--- Starting execution: elapsed 0:00:00.002
--- trnsport.gms(44) 4 Mb
--- Generating LP model transport
--- trnsport.gms(65) 4 Mb
--- 6 rows 7 columns 19 non-zeroes
--- Executing CPLEX: elapsed 0:00:00.007
IBM ILOG CPLEX Jul 14, 2011 23.7.1 WEX 26779.26792 WEI x86 64/MS Windows
Cplex 12.3.0.0
Reading data...
3 Detailed Description of Command Line Parameters 243
Starting Cplex...
Tried aggregator 1 time.
LP Presolve eliminated 1 rows and 1 columns.
Reduced LP has 5 rows, 6 columns, and 12 nonzeros.
Presolve time = 0.00 sec.
IBM ILOG CPLEX Jul 14, 2011 23.7.1 WEX 26779.26792 WEI x86 64/MS Windows
Cplex 12.3.0.0
Reading data...
Starting Cplex...
Tried aggregator 1 time.
LP Presolve eliminated 1 rows and 1 columns.
Reduced LP has 5 rows, 6 columns, and 12 nonzeros.
Presolve time = 0.00 sec.
Comparing this output to the one shown in the example of option logfile, one can see that the line numbers
are absent from the log file.
Default: 2
value meaning
0 no line tracing
1 minimum line tracing
2 automatic and visually pleasing
244 The GAMS Call
value meaning
0 no log output
1 log output to screen (console)
2 log output to logfile
3 log output to standard output
4 log output to logfile and standard output
MCPRHoldfx (integer): Print list of rows that are perpendicular to variables removed due to the holdfixed setting -
Range: [0, 1]
Default: 0
MINLP (string): Mixed-Integer Non-Linear Programming - default solver -
By default, running a file containing just the two statements shown above results in the following listing file,
1 a(i) = b(i)*5 ;
**** $140$120$140
2 b(i) = c(j) ;
**** $140$120$149
None of the sets i, or j have been defined or initialized, and the identifiers a, b, and c have not been defined.
Further, an assignment cannot be made without the right hand side of the assignment being known. In both
assignments in the example above, there is no data available for the right hand side. Running the model with the
setting mp=1 results in the following listing file,
1 a(i) = b(i)*5 ;
2 b(i) = c(j) ;
**** $149
Error Messages
149 Uncontrolled set entered as constant
**** 1 ERROR(S) 0 WARNING(S)
Note that the statements in the example have now been processed independently of its context. They are now
checked only for consistency. GAMS now assumes that sets i and j, as well as the identifiers a, b, and c are
defined and, if necessary, initialized elsewhere. The only error that is reported is the inconsistency of indices in
the second statement.
Default: 0
value meaning
0 standard compilation
1 check-out compilation
2 as 1, and skip $call and ignore missing file errors with $include and $gdxin
value meaning
0 AllowNewVarEqu
1 DoNotAllowNewVarEqu
value meaning
0 No error messages
1 Issue error messages
The option file that is being used after this assignment is solvername.opt, where solvername is the name of
the solver that is specified. For CONOPT, the option file is called conopt.opt; for MINOS, it is minos.opt.
The names that you can use are listed in the Solver Manual.
Attention
Setting modelname.optfile in the GAMS input file overrides the value of the optfile parameter passed
through the command line.
To allow different option file names for the same solver, the optfile parameter can take other values as well.
Formally, the rule is optfile=n will use solvename.opt if n=1, and solvername.opX, solvername.oXX or
solvername.XXX, where X's are the characters representing the value of n, for n > 1 and will use no option
file at all for n=0. For example, the following optfile values profile the option file names for the CONOPT
solver
0 no option file used
3 Detailed Description of Command Line Parameters 247
1 conopt.opt
2 conopt.op2
26 conopt.o26
345 conopt.345
1234 conopt.1234
Default: 0
value meaning
0 no option file will be used
1 the option file solvername.opt will be used
2 the option file solvername.op2 will be used
3 the option file solvername.op3 will be used
15 the option file solvername.o15 will be used
222 the option file solvername.222 will be used
1234 the option file solvername.1234 will be used
The first call will create an output file called trnsport.lst (for PC and Unix platforms) in the current directory.
The second call will create a file called trnsport.out in the current directory. The last call will create the file
as listed. If the directory c:\test does not exist, GAMS will exit with a parameter error.
Default: <input file basename>.lst
PageContr (integer): Output file page control option -
Synonym: PC
This option affects the page control in the listing file.
Default: 3
value meaning
0 no page control, with padding
1 FORTRAN style line printer format
2 no page control, no padding
3 Formfeed character for new page
In this case the range is from 0 to 32767 and if the value is above the range, then it is set to 32767.
Range: [72, 32767]
Default: 255
ParmFile (string): Command Line Parameter include file -
Synonym: PF
This option specifies the name of a secondary customization parameter file to use. It is used to augment the
command line adding more command line parameters from a file. It is read from the current directory unless a
path is specified.
PLicense (string): Privacy license file name -
This keyword tells the name of a privacy license file that contains file encryption codes. A full path should be
used.
PrefixLoadPath (integer): Prepend GAMS system directory to library load path (this is ignored for Windows and AIX) -
Default: 0
value meaning
0 Do not set GAMS system directory at beginning of library load path
1 Set GAMS system directory at beginning of library load path
0 no profiling
1 minimum profiling
n profiling depth for nested control structures
A value of 0 does not cause an execution profile to be generated. A value of 1 reports execution times for each
statement and the number of set elements over which the particular statement is executed. A value of 2 reports
specific times for statements inside control structures like loops etc. Running [TRNSPORT] with profile=1
3 Detailed Description of Command Line Parameters 249
The first column provides the line number in the input file of the statement being executed. The second column
provides the type of statement being executed.
ExecInit denotes the beginning of the execution phase of the GAMS input file.
GAMS Fini denotes the end of this phase.
Note that GAMS finishes processing of an input file as soon as a solve statement is processed, and passes control
to the solver being called. After the solver is done, GAMS restarts. This causes two ExecInit GAMS Fini
pairs to be generated for [TRNSPORT].
Assignment c denotes an assignment statement involving the identifier c.
Solve Init, Solver Fini are book ends enclosing the generation of the model [TRNSPORT].
Note that only equations are listed, and not variables. This happens because GAMS uses an equation based
scheme to generate a model. The third and fourth columns provide the individual time needed to execute the
statement, and the cumulative time taken by the GAMS system so far. The last column gives the number of
assignments generated in the specified line.
At the end of the log file a profile summary is created which contains (up to) ten of the slowest execution steps.
For example such a summary looks like this:
--- Profile Summary (184 records processed)
0.062 3621 GAMS Fini
0.047 3621 Solve Read wsisn
0.046 3529 Equation divcnlsea (86)
0.032 3621 Solve Fini wsisn (39489)
0.016 3274 Assignment wnr (2502)
0.016 3447 Equation cost (15)
0.016 3475 Equation laborc (180)
0.016 3519 Equation waterbaln (180)
0.016 3546 Equation subirrc (84)
0.015 3030 Assignment gwtsa (273)
Note that this summary does not belong to [TRNSPORT] but is more capable for illustration because the summary
of [TRNSPORT] is empty.
Default: 0
value meaning
0 no profiling
1 minimum profiling
n profiling depth for nested control structures
ProfileTol (real): Minimum time a statement must use to appear in profile generated output -
Synonym: PTOL
This option sets profile tolerance in seconds. All statements that take less time to execute than this tolerance are
not reported in the listing file.
Default: 0.00
PutDir (string): Put file directory -
Synonym: PDir
This option specifies the directory where the put files are generated and saved. If not specified, it will be set to
the working directory. This option does not work if an absolute file name is provided through the file statement.
Default: Working directory
QCP (string): Quadratically Constrained Programs - default solver -
RMIQCP (string): Relaxed Mixed Integer Quadratically Constrained Programs - default solver -
RMPEC (string): Relaxed Mathematical Programs with Equilibrium Constraints - default solver -
Synonym: S
This option specifies the name of a workfile to be written that allows the GAMS program to be restarted. The
file written is platform independent.
The final name is composed by completing the save file name with the current directory and the standard workfile
extension. Eight save files are generated, so the name provided by the user for the save file should be such that
GAMS can generate eight names from it. GAMS distinguishes file names from their extensions. If no extension
is provided by the user, GAMS adds the extensions g01 through g08 to name the eight saved work files. The
presence of a ? character in the save file name is used by GAMS to substitute the numbers 1 through 8 in its
place.
The following table illustrates through examples, the generation of names for the save files by GAMS from the
name proided through the save parameter.
myfile: myfile.g01, myfile.g02, ..., myfile.g08
myfile?: myfile1.g01, myfile2.g02, ..., myfile8.g08
myfile.00?: myfile.001, myfile.002, ..., myfile.008
myfile?.wrk: myfile1.wrk, myfile2.wrk, ..., myfile8.wrk
myfile?.???: myfile1.111, myfile2.222, ..., myfile8.888
Attention
On Unix platforms the ? character is a special character and may require a backslash character (\) in
front of it in order to be interpreted correctly. The name myfile? should be written on this platform as
myfile\?.
value meaning
0 no point gdx file is to be saved
1 a point gdx file from the last solve is to be saved
2 a point gdx file from every solve is to be saved
to be set explicitly to the script that should be called after GAMS terminates. An empty template of an exit script
can be found in the GAMS system directory (gmsxitnt.cmd (Windows) or gmsxitus.run (Unix)).
ScriptFrst (string): First line to be written to GAMSNEXT file. -
Synonym: SF
The default is an empty string and the first line is not written.
ScriptNext (string): Script mailbox file name (GAMSNEXT) -
Synonym: SCRIPT
Default: gamsnext
ScrNam (string): Work file names stem -
Synonym: SN
Name stem used to complete the names of intermediate work files. This name stem has to have at least one '?'.
Name will be completed with the scratch directory and the standard scratch name extension.
Seed (integer): Random number seed -
This option specifies the seed used for the pseudo random number generator.
Default: 3141
SolPrint (integer): Solution report print option -
This option controls the printing of the model solution to the listing file.
Default: 1
value meaning
0 remove solution listings following solves
1 include solution listings following solves
2 suppress all solution information
value meaning
0 GAMS operates as it has for years
1 solver is called from a shell and GAMS remains open
2 solver is called with a spawn (if possible) or a shell (if spawn is not possible) and GAMS remains
open
3 GAMS starts the solution and continues in a Grid computing environment
4 GAMS starts the solution and wait (same submission process as 3) in a Grid computing environment
5 the problem is passed to the solver in core without use of temporary files
6 the problem is passed to the solver in core without use of temporary files, GAMS does not wait for
the solver to come back
7 the problem is passed to the solver in core without use of temporary files, GAMS waits for the
solver to come back but uses same submission process as 6
Solver (string): Default solver for all model types that the solver is capable to process -
The command line option solver=abc initializes the default solver for the model types solver abc is capable of to
3 Detailed Description of Command Line Parameters 253
abc. This initialization is done before the default solvers of individual model types are set via command line
options. So a command line with lp=conopt solver=bdmlp will first set BDMLP as the default solver for model
types LP, RMIP, and MIP (these are the model types BDMLP can handle) and then reset Conopt as the default
solver for LP. The order of these parameters on the command line has no impact (i.e. lp=conopt solver=bdmlp
behaves identically to solver=bdmlp lp=conopt). If multiple occurrences of option solver appear, the last one
sets the option as it is with other options, including LP, MIP, ...
SolverCntr (string): Solver control file name -
Synonym: SCNTR
Name completed with scratch directory and scratch extension.
SolverDict (string): Solver dictionary file name -
Synonym: SDICT
Name completed with scratch directory and scratch extension.
SolverInst (string): Solver instruction file name -
Synonym: SINST
Name completed with scratch directory and scratch extension.
SolverMatr (string): Solver matrix file name -
Synonym: SMATR
Name completed with scratch directory and scratch extension.
SolverSolu (string): Solver solution file name -
Synonym: SSOLU
Name completed with scratch directory and scratch extension.
SolverStat (string): Solver status file name -
Synonym: SSTAT
Name completed with scratch directory and scratch extension.
StepSum (integer): Summary of computing resources used by job steps -
This option controls the generation of a step summary of the processing times taken by GAMS during a given
run.
To illustrate the use of the stepsum option, the default GAMS listing file from running [TRNSPORT] with the
option stepsum=1 contains the following step summaries.
STEP SUMMARY: 0.000 0.000 STARTUP
0.000 0.000 COMPILATION
0.000 0.000 EXECUTION
0.000 0.000 CLOSEDOWN
0.000 0.000 TOTAL SECONDS
0.008 0.008 ELAPSED SECONDS
3.949 3.949 MAX HEAP SIZE (Mb)
the run, while the second column reports accumulated times including previous sections.
Default: 0
value meaning
0 no step summary
1 step summary printed
value meaning
0 Take first record if assignment to singleton set has multiple elements
1 Error if assignment to singleton set has multiple elements
value meaning
0 no substitution if symbol undefined and no error
1 error if symbol undefined
2 remove entire symbol reference if undefined and no error
Default: 0
value meaning
0 standard compiler listing
1 suppress compiler listing
SymPrefix (string): Prefix all symbols encountered during compilation in save file -
Sys10 (integer): Changes rpower to ipower when the exponent is constant and within e-12 of an integer -
Default: 0
value meaning
0 Disable conversion
1 Enable conversion
Sys11 (integer): Dynamic resorting if indices in assignment/data statements are not in natural order -
Speed-up for expressions containing constant indices or indices that are not in the natural order at the cost of
increased memory use.
Default: 0
value meaning
0 Automatic optimization/restructuring of data
1 no optimization
2 always optimize/restructure
value meaning
0 Automatic switching to dense data structures
1 No switching
2 Always switch
1x Print additional information in lst file
Sys16 (integer): Disable search record memory (aka execute this as pre-GAMS 24.5) -
Range: [0, 1]
Default: 0
Sys17 (integer): Disable sparsity trees growing with permutation (aka execute this as pre-GAMS 24.5) -
Range: [0, 1]
Default: 0
SysDir (string): GAMS system directory where GAMS executables reside -
This option sets the GAMS system directory. This option is useful if there are multiple systems installed on the
machine, or when GAMS is called from an external system like Visual Basic.
SysIncDir (string): SysInclude directory -
Synonym: SDIR
Used to complete a file name for $sysinclude. If the sdir option is not set, the GAMS system directory is
searched.
Attention
Unlike idir, additional directories cannot be set with sdir. The string passed will be treated as one
directory. Passing additional directories will cause errors.
Note that if the sdir parameter is set, the default system include directory is not searched.
256 The GAMS Call
GAMS searches for any referenced $sysinclude file in the directory mydir.
Default: GAMS system directory
SysOut (integer): Solver Status file reporting option -
This option controls the printing of all solver messages (i.e., the solver status file) to the GAMS listing file.
The contents of the solver status file are useful for debugging or to get additional information about a solver
run. Normally, only those messages flagged by the solver as destined for the listing file get listed. If the solver
crashes or encounters any unexpected difficulties, the contents of the solver status file will be automatically sent
to the listing file. sysout exists only as a global option, that is, it can only be set from the command line by
using an integer (e.g., sysout=1).
Default: 0
value meaning
0 suppress additional solver generated output
1 include additional solver generated output
Default: 8
value meaning
0 tabs are not allowed
1 tabs are replaced by blanks
n tabs are 1, n+1, 2n+1,.. (default: n=8)
value meaning
0 time as hh:mm:ss
1 time as hh.mm.ss
Default: 1
value meaning
0 use number of available cores
n use n threads
minus n number of cores to leave free for other tasks
value meaning
0 use number of available cores
n use n threads
minus n number of cores to leave free for other tasks
Default: 0
value meaning
0 interpreted as +inf, no details echoed
n echo all details about internal GAMS instructions that took more than n milli seconds to the log
value meaning
0 solver and GAMS step trace without headers
1 solver and GAMS step trace
258 The GAMS Call
value meaning
2 solver step trace only
3 trace file format used for GAMS performance world
5 trace file with all available trace fields
value meaning
0 no warning when a rounding occurs because of ZeroRes
1 issue warnings whenever a rounding occurs because of ZeroRes
260 The GAMS Call
Chapter 21
1 Introduction
The Dollar Control Options are used to indicated compiler directives and options. Dollar control options are not part of the
GAMS language and must be entered on separate lines recognized by a $ symbol in the first column. A dollar control option
line may be placed anywhere within a GAMS program and it is processed during the compilation of the program. The $
symbol is followed by one or more options identified by spaced. Since the dollar control options are not part of the GAMS
language, they do not appear on the compiler listing unless an error had been detected. Dollar control option lines are not
case sensitive and a continued compilation uses the previous settings.
1.1 Syntax
In general, the syntax in GAMS for dollar control options is as follows,
where option name is the name of the dollar control option, while argument list is the list of arguments for the option.
Depending on the particular option, the number of arguments required can vary from 0 to many.
Attention
No blank space is permitted between the $ character and the first option that follows.
In most cases, multiple dollar control options can be processed on a line. However, some dollar control options
require that they be the first option on a line.
The effect of the dollar control option is felt immediately after the option is processed.
Note that there is no blank space between the $ character and the option that follows. The first dollar control option $title
sets the title of the pages in the listing file to the text that follows the option name. In the second line of the example above,
two options are set - $onsymxref and $onsymlist. Both these options turn of the echoing of the symbol reference table and
listings to the listing file.
program control
GDX operations
environment variables
macro definitions
Compression and encrypting
The following subsections briefly describe the various options in each of the categories. Section Detailed Description of
Dollar Control Options contains a reference list of all dollar control options in alphabetical order with detailed description for
each.
Non-default settings are reported before the file summary at the end of a GAMS listing as a reminder for future continued
compilations. This is only relevant if a restart file has been requested with the GAMS call.
Option Description
comment set the comment character
eolCom set end-of-line comment character
inlinecom set in line comment character
maxCol set right hand margin of input file
minCol set left hand margin of input file
offEolCom turn off end-of-line comments
offInline turn off in-line comments
offMargin turn off margin marking
offNestCom turn off nested comments
offText off text mode
onEolCom turn on end-of-line comments
onInline turn on in-line comments
onMargin turn on margin marking
onNestCom turn on nested comments
onText on text following lines are comments
Option Description
dollar set the dollar character
offDelim delimited data statement syntax off
offDigit off number precision check
offEmbedded no embedded text or data allowed
offEmpty disallow empty data initialization statements
offEnd disallow alternate program control syntax
2 List of Dollar Control Options 263
Option Description
offEps disallow interpretation of EPS as 0
offGlobal disallow inheritance of parent file settings
offUNDF do not allow UNDF as input
offWarning do not convert domain errors into warnings
onDelim delimited data statement syntax on
onDigit on number precision check
onEmbedded allow embedded text or data in set and parameter statements
onEmpty allow empty data initialization statements
onEnd allow alternate program control syntax
onEps interpret EPS as 0
onGlobal force inheritance of parent file settings
onUNDF allow UNDF as input
onWarning convert certain domain errors into warnings
use205 Release 2.05 language syntax
use225 Release 2.25 Version 1 language syntax
use999 latest language syntax
version test GAMS compiler version number
Option Description
double double-spaced listing follows
echo echo text
echoN echo a string to a file without ending the line
eject advance to next page
hidden ignore text and do not list
lines next number of lines have to fit on page
log send message to the log
offDollar turn the listing of Dollar Control Option lines off
offEcho end of block echo
offInclude turn off listing of include file names
offListing turn off echoing input lines to listing file
offLog turn off line logging
offPut end of block put
offVerbatim stop verbatim copy
onDollar turn the listing of Dollar Control Option lines on
onEcho start of block echo with substitution
onEchoS start of block echo with substitution
onEchoV start of block echo without substitution
onInclude include file name echoed to listing file
onListing input lines echoed to listing file
onLog reset line logging
onPut start of block put without substitution
onPutS start of block put with substitution
onPutV start of block put without substitution
264 Dollar Control Options
Option Description
onVerbatim start verbatim copy if dumpopt 10
remark comment line with suppressed line number
single single-spaced listing follows
stars set characters in listing file
sTitle set subtitle and reset page
title set title, reset subtitle and page
Option Description
offSymList off symbol list
offSymXRef off symbol cross reference listing
offUElList off unique element listing
offUElXRef off unique element cross reference
onSymList on symbol list
onSymXRef on symbol cross reference listing
onUElList on unique element listing
onUElXRef on unique element cross listing
Option Description
abort issue an error message and abort compilation
batInclude include file with substitution arguments
call executes program during compilation
call.Async executes another program asynchronously
clear reset all data for an identifier to its default values
clearError clear compilation errors
clearErrors clear compilation errors
else else clause
elseIf elseIf structure with case sensitive compare
elseIfE elseIf structure with expression evaluation
elseIfI elseIf structure with case insensitive compare
endif closing of ifThen/ifThenE/ifThenI control structure
error issue an error message
exit exit from compilation
funcLibIn load extrinsic function library
goto go to line with given label name
hiddenCall executes another program (hidden)
if conditional processing, case sensitive
ifE if statement with expression evaluation
ifI conditional processing, case insensitive
ifThen ifThen-elseIf structure with case sensitive compare
ifThenE ifThen-elseIf structure with expression evaluation
2 List of Dollar Control Options 265
Option Description
ifThenI ifThen-elseIf structure with case insensitive compare
include include file
kill kill data connected with identifier
label label name as entry point from $goto
libInclude include file from library directory
offGlobal turns off global options
offMulti turns off redefinition of data
offOrder allow lag and lead operations on dynamic or unordered sets
offRecurse disable recursive include files
offStrictSingleton take first record if data statement for singleton set has multiple elements
onGlobal turns on global options
onMulti turn on redefinition of data
onOrder lag and lead operations on constant and ordered sets only
onRecurse enable recursive include files
onStrictSingleton error if data statement for singleton set has multiple elements
maxGoto maximum number of jumps to the same label
phantom defines a phantom element
shift DOS shift operation
stop stop compilation
sysInclude include file from system directory
terminate terminate compilation and execution
warning issue compilation warning
Option Description
gdxIn open GDX file for input
gdxOut open GDX file for output
load load symbols from GDX file - domain filtered
loadDC load symbols from GDX file - domain checked
loadDCM Load symbols from GDX file - domain checked - merge
loadDCR load symbols from GDX file - domain checked - replace
loadM load symbols from GDX file - domain filtered - merge
loadR load symbols from GDX file - domain filtered - replace
unload unload symbols into GDX file
Option Description
drop drop a scoped environment variable
dropEnv drop an OS environment variable
dropGlobal drop a global environment variable
dropLocal drop a local environment variable
escape define the % escape symbol
266 Dollar Control Options
Option Description
eval evaluates and defines a scoped environment variable
evalLocal evaluates and defines a local environment variable
evalGlobal evaluates and defines a global environment variable
prefixPath prefix the path environment variable
set define a scoped environment variable
setArgs define local environment variables using argument list
setComps unpack dotted names into local variables
setDDList check double dash GAMS parameters
setEnv define an OS environment variable
setGlobal define a global environment variable
setLocal define a local environment variable
setNames unpack a filename into local environment variables
show show current GAMS environment variables
splitOption unpack a key/value pair into local environment variables
Option Description
macro preprocessing macro definition
offDotL do not assume .l for variables in assignments
offExpand do not expand macros when processing macro arguments
offLocal limit .local nesting to one
offMacro do not recognize macros for expansion
onDotL assume .l for variables in assignments
onExpand expand macros when processing macro arguments
onLocal no limit on .local nesting
onMacro recognize macros for expansion
Option Description
compress create compressed GAMS system file
decompress decompress a GAMS system file
encrypt create encrypted GAMS system file
expose remove all access control restrictions
hide hide objects from user
protect protect objects from user modification
purge remove the objects and all associated data
This option will issue a compilation error and abort the compilation.
Consider the following example,
$if not %system.filesys% == UNIX
$abort We only do UNIX
This attempts to stop compilation if the operating system is not Unix. Running the above example on a non-Unix
platform results in the compilation being aborted, and the following listing file,
2 $abort We only do UNIX
**** $343
Error Messages
343 Abort triggered by above statement
batinclude
The $batinclude facility performs the same task as the $include facility in that it inserts the contents of the
specified text file at the location of the call. In addition, however, it also passes on arguments which can be used
inside the include file:
$batinclude file arg1 arg2 ...
The $batinclude option can appear in any place the $include option can appear. The name of the batch include
file may be quoted or unquoted, while arg1, arg2,.. are arguments that are passed on to the batch include
file. These arguments are treated as character strings that are substituted by number inside the included file.
These arguments can be single unbroken strings (quoted or unquoted) or quoted multi-part strings.
The syntax has been modeled after the DOS batch facility. Inside the batch file, a parameter substitution is
indicated by using the character % followed immediately by an integer value corresponding to the order of
parameters on the list where %1 refers to the first argument, %2 to the second argument, and so on. If the integer
value is specified that does not correspond to a passed parameter, then the parameter flag is substituted with a
null string. The parameter flag %0 is a special case that will substitute a fully expanded file name specification
of the current batch included file. The flag %$ is the current $ symbol (see $dollar). Parameters are substituted
independent of context, and the entire line is processed before it is passed to the compiler. The exception to this
is that parameter flags appearing in comments are not substituted.
Attention
GAMS requires that processing the substitutions must result in a line of less than or equal to the
maximum input line length (currently 255 characters).
The case of the passed parameters is preserved for use in string comparisons.
1 parameter a,b,c ;
2 a = 1 ; b = 0 ; c = 2 ;
BATINCLUDE D:\GAMS\INC2.INC
4 b = sqr(a) - a ;
5 display b ;
BATINCLUDE D:\GAMS\INC2.INC
7 b = sqr(c) - c ;
8 display b ;
BATINCLUDE D:\GAMS\INC2.INC
10 b = sqr(a+5) - a+5 ;
11 display b ;
Note that the three calls to $batinclude with the various arguments lead to GAMS interpreting the contents of
batch include file in turn as
b = sqr(a) - a ;
b = sqr(c) - c ;
b = sqr(a+5) - a+5 ;
Note that third call is not interpreted as sqr(a+5)-(a+5), but instead as sqr(a+5)-a+5. The results of the
display statement are shown at the end of the listing file,
---- 5 PARAMETER B = 0.000
---- 8 PARAMETER B = 2.000
---- 11 PARAMETER B = 40.000
The third call leads to b = sqr(6)-1+5 which results in b taking a value of 40. If the statement in the batch
include file was modified to read as follows,
%1 = sqr(%2) - (%2) ;
the results of the display statement in the listing file would read,
---- 5 PARAMETER B = 0.000
---- 8 PARAMETER B = 2.000
---- 11 PARAMETER B = 30.000
The third call leads to b = sqr(6)-6 which results in b taking a value of 30.
Attention
A $batinclude call without any arguments is equivalent to a $include call.
call
Passes a followed string command to the current operating system command processor and interrupts compilation
until the command has been completed. If the command string is empty or omitted, a new interactive command
processor will be loaded.
Consider the following slice of code,
$call dir
This command makes a directory listing on a PC.
The command string can be passed to the system and executed directly without using a command processor by
prefixing the command with an '=' sign. Compilation errors are issued if the command or the command processor
cannot be loaded and executed properly.
$call gams trnsport
$call =gams trnsport
The first call runs [TRNSPORT] in a new command shell. The DOS command shell does not send any return
codes from the run back to GAMS. Therefore any errors in the run are not reported back. The second call,
however, sends the command directly to the system. The return codes from the system are intercepted correctly
and available to the GAMS system through the errorlevel DOS batch function.
3 Detailed Description of Dollar Control Options 269
Attention
Some commands (like copy on a PC and cd in Unix) are shell commands and cannot be spawned off to
the system. Using these in a system call will create a compilation error.
With JobTerminate(pid) an interrupt signal can be sent to a running job. If this was successful the return value is
one, otherwise it is zero. With JobKill(pid) a kill signal can be sent to a running job. If this was successful the
return value is one, otherwise it is zero.
clear
This option resets all data for an identifier to its default values:
$clear id1 id2 ...
id1, id2, ... are the identifiers whose data is being reset. Note that this is carried out during compile time, and
not when the GAMS program executes. Not all data types can be cleared - only set, parameter, equation
and variable types can be reset.
Consider the following example,
set i /1*20/ ; scalar a /2/ ;
$clear i a
display i, a ;
The $clear option resets i and a to their default values. The result of the display statement in the listing file
shows that i is now an empty set, and a takes a value of 0.
---- 3 SET I
(EMPTY)
---- 3 PARAMETER A = 0.000
Attention
The two-pass processing of a GAMS file can lead to seemingly unexpected results. Both the dollar control
options and the data initialization is done in the first pass, and assignments in the second, irrespective of
their relative locations. This is an issue particularly with $clear since data can be both initialized and
assigned.
The scalar data initialization statement is processed during compilation and the assignment statement a=5 during
execution. In the order that it is processed, the example above is read by GAMS as,
* compilation step
scalar a /12/ ;
$clear a
* execution step
a=5;
display a ;
The example results in a taking a value of 5. The display statement in the resulting listing file is as follows,
---- 4 PARAMETER A = 5.000
clearError(s)
$clearError and $clearErrors clear GAMS awareness of compiler errors. Consider the following example,
scalar z /11/;
$eval x sqrt(-1)
$clearerror
$log %x%
display z;
Without the use of $clearerror(s) the programm would not continue with the execution.
comment ()
This option changes the start-of-line comment to a single character which follows immediately the $comment
keyword. This should be used with great care, and one should reset it quickly to the default symbol .
Attention
The case of the start-of-line comment character does not matter when being used.
dollar ($)
This option changes the current $ symbol to a single character which follows immediately the $dollar keyword.
When a include file is inserted, all dollar control options are inherited, and the current $ symbol may not be
known. The special %$ substitution symbol can be used to get the correct symbol (see $batinclude ).
Consider the following example,
$dollar #
#hidden now we can use # as the $ symbol
double
The lines following the $double statement will be echoed double spaced to the listing file.
Consider the following example,
set i /1*2/ ;
scalar a /1/ ;
$double
set j /10*15/ ;
scalar b /2/ ;
The resulting listing file looks as follows,
1 set i /1*2/ ;
2 scalar a /1/ ;
4 set j /10*15/ ;
5 scalar b /2/ ;
Note that lines before the $double option are listed singly spaced, while the lines after the option are listed with
double space.
drop
Destroys a variable that was defined with $set. The syntax is $drop varname.
dropEnv
Destroys an operating system envorinment variable. The syntax is $dropenv varname. For detailed infoemation
check $setEnv.
dropGlobal
Destroys a variable that was defined with $setGlobal. The syntax is $dropGlobal varname.
dropLocal
Destroys a variable that was defined with $setLocal. The syntax is $dropLocal varname.
echo
The echo option allows to write text to a file:
$echo text > file
$echo text >> file
These options send the message 'text' to the file file. Both the text and the file name can be quoted or unquoted.
The file name is expanded using the working directory. The $echo statement tries to minimize file operations by
keeping the file open in anticipation of another $echo to be appended to the same file. The file will be closed at
the end of the compilation or when a $call or any kind of $include statement is encountered. The redirection
symbols > and >> have the usual meaning of starting at the beginning or appending to an existing file.
Consider the following example,
$echo > echo
$echo The message written goes from the first non blank >> echo
$echo to the first > or >> symbol unless the text is >> echo
272 Dollar Control Options
$echo "is quoted. The Listing File is %gams.input%. The" >> echo
$echo file name "echo" will be completed with >> echo
$echo %gams.workdir%. >> echo
$echo >> echo
The contents of the resulting file echo are as follows,
The message written goes from the first non blank
to the first > or >> symbol unless the text is
is quoted. The Listing File is C:\PROGRAM FILES\GAMSIDE\CC.GMS. The
file name "echo" will be completed with
C:\PROGRAM FILES\GAMSIDE\.
echoN
Sends a text message to an external file like $echo but writes no end of line marker so the line is repeatedly
appended to by subsequent commands. Consider the following example,
$echoN Text to be sent > aaa
$echoN More text >> aaa
$echoN And more and more and more >> aaa
$echo This was entered with $echo >> aaa
$echo This too >> aaa
The created file aaa contains,
Text to be sentMore textAnd more and more and moreThis was entered with $echo
This too
The redirection symbols > and >> have the usual meaning of starting at the beginning or appending to an
existing file.
Note that the text and the file name can be quoted or unquoted. By default the file name will go in the working
directory.
eject
Advances the output to the next page.
Consider the following example,
$eject
Set i,j ;
Parameter data(i,j) ;
$eject
This will force the statements between the two $eject calls to be reported on a separated page in the listing file.
else
$else always appears together with an $ifThen[E/I] statement. It is followed by an instruction which is executed
if the matching if statement is not true.
elseIf
$elseIf always appears together with an $ifThen[E/I] statement. It is followed by another condition and
instruction.
elseIfE
$elseIfE does the same as $elseIf but evaluates numerical values of the control variables.
elseIfI
$elseIfI does the same as $elseIf but is case insensitive.
encrypt
Causes a file to be converted into an encrypted file. The syntax is $encrypt source target where source is
the name of the source file to be encrypted and target is the name for the resulting encrypted file. Note that
3 Detailed Description of Dollar Control Options 273
encryption requires a special GAMS license. The use of the Plicense parameter specifies the target license
to be used as a user key for decrypting. This must be done with the same license as was used in encryption.
Decryption is done when reading the GAMS system files. GAMS recognizes whether a file is compressed or
encrypted and will process the files accordingly.
endIf
$endIf must be matched with an $ifThen, $ifThenE or $ifThenI.
eolcom (!!)
This option redefines the end-of-line comment symbol, which can be a one or two character sequence. By default
the system is initialized to '!!' but not active. The $oneolcom option is used to activate the end-of-line comment.
The $eolcom option sets $oneolcom automatically.
Consider the following example,
$eolcom ->
set i /1*2/ ; -> set declaration
parameter a(i) ; -> parameter declaration
The character set -> serves as the end-of-line-comment indicator.
Attention
GAMS requires that one does not reset the $eolcom option to the existing symbol.
The following code is illegal since $eolcom is being reset to the same symbol as it is currently,
$eolcom ->
$eolcom ->
error
This option will issue a compilation error and will continue with the next line.
Consider the following example,
$if not exist myfile
$error File myfile not found - will continue anyway
This checks if the file myfile exists, and if not, it will generate an error with the comment 'File not found - will
continue anyway', and then compilation continues with the following line.
escape
Allows one to print out or display the text sequence for the % syntax. It is employed using the syntax $escape
symbol. This renders all subsequent commands of the form %symbol to not have parameter substitution done for
them and on display or in a put to come out as just a %. One may reverse this action with $escape %. Consider
the following example,
$set tt DOIT
file it
put it
$escape &
display "third %tt%";
display "fourth %&tt%&";
put "display third ", "%system.date%" /;
put "display fourth " "%&system.date%&"/;
274 Dollar Control Options
$escape %
display "fifth %tt%";
display "sixth %&tt%&";
put "display fifth ", "%system.date%" /;
put "display sixth " "%&system.date%&"/;
The resulting listing file contains,
---- 6 first DOIT
$include test.gms
$evalGlobal Dnumber 44
$evalLocal Enumber 55
$eval Fnumber 66
The resulting listing file contains,
---- 4 Anumber equals 11
one to define scoped, local and global variables with the same name and has to prioritize under some cases.
Consider the following slice of code,
$evalglobal notunique 11
$evallocal notunique 22
$eval notunique 33
$log %notunique%
$log will echo 22, the current value of notunique, to the log file.
exit
This option will cause the compiler to exit (stop reading) from the current file. This is equivalent to having
reached the end of file.
Consider the following example,
scalar a ; a = 5 ;
display a ;
$exit
a = a+5 ; display a ;
The lines following the $exit will not be compiled.
Note that there is a difference to $stop. If you have only one input file $stop and $exit will do the same thing.
If you are in an include file, $exit acts like an end-of file on the include file. However, if you encounter a $stop
in an include file, GAMS will stop reading all input.
expose
removes all privacy restrictions from the named item or items. The syntax is
$expose item1 item2 ...
or
$expose all
In the first case the privacy restrictions are removed only for the listed items and in the second case they are
removed for all items. One can set these privacy restrictions with $hide or $protect.
Note that a special license file is needed for this feature to work and that the expose only takes effect in subsequent
restart files.
funcLibIn
Function libraries are made available to a model using the compiler directive:
$FuncLibIn <InternalLibName> <ExternalLibName>
Similar to sets, parameters, variables, and equations, functions must be declared before they can be used:
Function <InternalFuncName> /<InternalLibName>.<FuncName>/;
gdxIn
This dollar command is used in a sequence to load specified items from a GDX file. It is employed using the
syntax $gdxIn filename where filename gives the name of the GDX file (with or without the extension GDX)
and the command opens the specified GDX file for reading.
The next use of $gdxIn closes the specified GDX file. The command must be used in conjunction with the
command $load .
gdxOut
This dollar command is used in a sequence to unload specified items from a GDX file. It is employed using
the syntax $gdxOut filename where filename gives the name of the GDX file (with or without the extension
GDX) and the command opens the specified GDX file for writing. The next use of $gdxOut closes the specified
GDX file. The command must be used in conjunction with the command $unload.
goto id
3 Detailed Description of Dollar Control Options 277
This option will cause GAMS to search for a line starting with '$label id' and then continue reading from there.
This option can be used to skip over or repeat sections of the input files. In batch include files, the target labels
or label arguments can be passed as parameters because of the manner in which parameter substitution occurs in
such files. In order to avoid infinite loops, one can only jump a maximum of 100 times to the same label.
Consider the following example,
scalar a ; a = 5;
display a ;
$goto next
a = a+5 ; display a ;
$label next
a = a+10 ; display a ;
On reaching the $goto next option, GAMS continues from $label next. All lines in between are ignored.
On running the example, a finally takes a value of 15.
Attention
The $goto and $label have to be in the same file. If the target label is not found in the current file, and
error is issued.
hidden
This line will be ignored and will not be echoed to the listing file. This option is used to enter information only
relevant to the person manipulating the file.
Consider the following example,
$hidden You need to edit the following lines if you want to:
$hidden
$hidden 1. Change form a to b
$hidden 2. Expand the set
The lines above serve as comments to the person who wrote the file. However, these comments will not be
visible in the listing file, and are therefore hidden from view.
hiddenCall
$hiddenCall does the same as $call but makes sure that the statement is neither shown on the log nor the listing
file.
hide
hides the named items so they cannot be displayed or computed but still allows them to be used in model
calculations (.. commands when the solve statement is executed). The syntax is
$hide item1 item2 ...
or
$hide all
In the first case the listed items are hidden and in the second case all items are hidden. These restrictions can be
removed with $expose or $purge.
Note that special license file is needed for this feature to work.
if
The $if dollar control option provides the greatest amount of control over conditional processing of the input
file(s). The syntax is similar to the IF statement of the DOS Batch language:
$if [not] <conditional expression> new_input_line
The syntax allows for negating the conditional with a not operator followed by a conditional expressions. The
<conditional expression> can be: acrtype, decla ok, declared, defined, dexist, dimension,
equtype, errorfree, errorlevel, eval, evalglobal, evallocal, exist, filtype, funtype,
gamsversion, mactype, modtype, partype, pretype, protype, putopen, readable, set, setenv,
278 Dollar Control Options
setglobal, setlocal, settype, solver, vartype, warnings, xxxtype, as well as, a string com-
parison.
The result of the conditional test is used to determine whether to read the remainder of the line, which can be
any valid GAMS input line.
New input line is the remainder of the line containing the $if option, and could be any valid GAMS input
line.
Attention
The first non-blank character on the line following the conditional expression is considered to be the
first column position of the GAMS input line. Therefore, if the first character encountered is a comment
character the rest of the line is treated as a comment line. Likewise if the first character encountered is the
dollar control character, the line is treated as a dollar control line.
An alternative to placing new input line on the same line as the conditional is to leave the remainder of the
line blank and place new input line on the line immediately following the if line. If the conditional is found
to be false, either the remainder of the line (if any) is skipped or the next line is not read.
In the following some of the alternatives are explained in more detail:
The exist file operator can be used to check for the existence of the given file name specification. The string
compare consists of two strings (quoted or unquoted) for which the comparison result is true only if the strings
match exactly. Null (empty) strings can be indicated by an empty quote:
Attention
The case of the strings provided either explicitly or, more likely, through a parameter substitution, is
preserved and therefore will effect the string comparison.
Quoted strings with leading and trailing blanks are not trimmed and the blanks are considered part of
the string.
If the string to be compared is a possibly empty parameter, the parameter operator must be quoted.
The first statement illustrates the use of the $if option inside a batch include file where parameters are passed
through the $batinclude call from the parent file. The $if condition checks if the parameter is empty, and if not
processes the $goto option. Note that the string comparison attempted, "\%1a" == a, can also be done using
%1 == "".
The second statement illustrates using standard GAMS statements if the conditional is valid. If the file name
passed as a parameter through the $batinclude call does not exist, the GAMS display statement is processed.
Attention
In line and end of line comments are stripped out of the input file before processing for new input line.
If either of these forms of comments appears, it will be treated as blanks.
Attention
It is suggested that a $label not appear as part of the conditional input line. The result is that if the $label
appears on the $if line, a $goto to this label will re-scan the entire line thus causing a reevaluation of the
conditional expression. On the other hand, if the $label appears on the next line, the condition will not be
reevaluated on subsequent gotos to the label.
The following example illustrates how an unknown number of file specifications can be passed on to a batch
include file that will include each of them if they exist. The batch include file could look as follows,
/* Batch Include File - inclproc.bch */
/* Process and INCLUDE an unknown number of input files */
$label nextfile
$if "%1a" == a $goto end
$if exist "%1" $include "%1" /* name might have blanks */
$shift goto nextfile
$label end
The call to this file in the parent file could look like:
$batinclude inclproc.bch fil1.inc fil2.inc fil3.inc fil4.inc
The following example illustrates how to perform a errorlevel test.
$if errorlevel 1 $abort one or more errors encountered
The errorlevel is retrieved from the previous system call, i.e. $call statement. The conditional statement
errorlevel 1 is true ,if the returned errorlevel is >=1 and, if so, the GAMS program is aborted immediately at
compilation time.
The next example shows how to test if a named item is defined.
set i /seattle/;
$if defined i $log set i is defined
The conditional expression defined i is true because a label, namely seattle, has been defined in set i.
The following example illustrates how to check if a solver exists.
$if solver badname
The conditional expression is false because no solver named badname exists in the GAMS System.
280 Dollar Control Options
ifE
The $ifE dollar control option does the same as $if but allows constant expression evaluation. There are two
different forms of that statement.
$ife expr1 == expr2 true if (expr1-expr2)/(1+abs(expr2)) < 1e-12
$ife expr true if expr1 <> 0
Consider the following example,
scalar a;
$ife (log2(16)^2)=16 a=0; display a;
$ife log2(16)^2 == 16 a=1; display a;
$ife NOT round(log2(16)^2-16) a=2; display a;
$ife round(log2(16)^2-16) a=3; display a;
$ife round(log2(16)^2-17) a=4; display a;
This will create the following ouput,
---- 2 PARAMETER a = 1.000
Consider the following example which illustrates the use of $ifThen and $elseIf.
$set x a
$label two
$ifthen %x% == a $set x c $log $ifthen with x=%x%
$elseif %x% == b $set x k $log $elseif 1 with x=%x%
$elseif %x% == c $set x b $log $elseif 2 with x=%x%
$else $set x e $log $else with x=%x%
$endif $if NOT %x% == e $goto two
3 Detailed Description of Dollar Control Options 281
---- 4 it3
because the first condition (x == y) is obviously not true and the fourth condition (b == b) is not tested because
the second one (a == a) was already true.
ifThenE
$ifThenE does the same as $ifThen but evaluates numerical values of the control variables.
ifThenI
$ifThenI does the same as $ifThen but is case insensitive.
include
The $include option inserts the contents of a specified text file at the location of the call. The name of the file
to be included which follows immediately the keyword include may be quoted or unquoted. Include files can
be nested.
The include file names are processed in the same way as the input file is handled. The names are expanded using
the working directory. If the file cannot be found and no extension is given, the standard GAMS input extension
is tried. However, if an incomplete path is given, the file name is completed using the include directory. By
default, the library include directory is set to the working directory. The default directory can be reset with the
idir command line parameter.
The start of the include file is marked in the compiler listing. This reference to the include file can be omitted by
using the $offinclude option.
The following example illustrates the use of an include statement,
$include myfile
$include "myfile"
Both statements above are equivalent, and the search order for the include file is as follows:
Attention
The current settings of the dollar control options are passed on to the lower level include files. However,
the dollar control options set in the lower level include file are passed on to the parent file only if the
$onglobal option is set.
Compiler errors in include files have additional information about the name of the include file and the local line
number.
At the end of the compiler listing, an include file summary shows the context and type of include files. The line
number where an include file has been called is given. For example, in the Include File Summary below we see
that:
SEQ GLOBAL TYPE PARENT LOCAL FILENAME
1 1 INPUT 0 0 C:\TEST\TEST1.GMS
2 1 INCLUDE 1 1 .C:\TEST\FILE1.INC
3 6 INCLUDE 1 4 .C:\TEST\FILE2.INC
The first column named SEQ gives the sequence number of the input files encountered. The first row always
refers the parent file called by the GAMS call. The second column named GLOBAL gives the global (expanded)
line number which contained the $include statement. The third column named TYPE refers to the type of file
being referenced. The various types of files are INPUT, INCLUDE, BATINCLUDE, LIBINCLUDE, and SYSINCLUDE.
The fourth column named PARENT provides the sequence number of the parent file for the file being referenced.
The fifth column named LOCAL gives the local line number in the parent file where the $include appeared. In
the example listed above, the include files file1.inc and file2.inc were included on lines 1 and 4 of the
parent file test1.gms.
inlinecom ( / /)
This option redefines the in-line comment symbols, which are a pair of one or two character sequence. By
default, the system is initialized to ' /' and ' /', but is not active. The $oninline option is used to activate the
in-line comments. The $inlinecom option sets the $oninline automatically.
Consider the following example,
$inlinecom {{ }}
set {{ this is an inline comment }} i /1*2/ ;
The character pair {{ }} serves as the indicator for in-line comments.
Attention
GAMS requires that one not reset the $inlinecom option to an existing symbol.
The following code is illegal since $inlinecom is being reset to the same symbol as it is currently,
$inlinecom {{ }}
$inlinecom {{ }}
Attention
The $onnestcom enables the use of nested comments.
kill
Removes all data for an identifier and resets the identifier, only the type and dimension are retained. Note that
this is carried out during compile time, and not when the GAMS program executes. Not all data types can be
killed - only set, parameter, equation and variable types can be reset.
Consider the following example,
set i / 1*20 /; scalar a /2/
$kill i a
Note that this is different from $clear in the case that after setting $kill, i and a are treated as though they
have been only defined and have not been initialized or assigned. The result of the $kill statement above is
3 Detailed Description of Dollar Control Options 283
libinclude
Equivalent to $batinclude:
$libinclude file arg1 arg2 ...
However, if an incomplete path is given, the file name is completed using the library include directory. By
default, the library include directory is set to the inclib directory in the GAMS system directory. The default
directory can be reset with the ldir command line parameter.
Consider the following example,
$libinclude abc x y
This call first looks for the include file [GAMS System Directory]/inclib/abc, and if this file does not
exist, GAMS looks for the file [GAMS System Directory]/inclib/abc.gms. The arguments x and y are
passed on to the include file to interpret as explained for the $batinclude option.
Consider the following example,
$libinclude c:\abc\myinc.inc x y
This call first looks specifically for the include file c:\abc\myfile.inc. The arguments x and y are passed on
to the include file to interpret as explained for the $batinclude option.
lines n
This option starts a new page in the listing file if less than n lines are available on the current page.
Consider the following example,
$hidden Never split the first few lines of the following table
$lines 5
table io(i,j) Transaction matrix
This will ensure that if there are less than five lines available on the current page in the listing file before the next
statement (in this case, the table statement) is echoed to it, the contents of this statement are echoed to a new
page.
load
This dollar command loads specified items from a GDX file. It is employed using the syntax $load item1
284 Dollar Control Options
item2 ... but must be used in conjunction with the command $gdxIn.
$load must be preceded and succeeded by a $gdxIn. The preceding $gdxIn specifies the GDX file name
and opens the file. The succeeding $gdxIn closes the file. More than one $load can appear in between.
When $load is not followed by arguments this causes a listing of the GDX file contents to be generated.
If the same symbol names as in the underlying GDX file should be used, the symbols are listed as arguments
after $load, e.g. $load i j.
Symbols can also be loaded with a new name, e.g. $load i new=i j new=j.
The universal set can be loaded using $load uni=.
Consider the following example, where transsol is the GDX file of the model [TRNSPORT] which can be
found in the GAMS Model Library.
$gdxin transsol
Sets i, jj, uni;
$load i jj=j
Parameters a(i), bb(jj);
$load a
$load bb=b
Scalar f;
$load f uni=*
$gdxin
display i, jj, a, bb, f, uni;
The resulting listing file contains,
---- 11 SET i canning plants
seattle , san-diego
Consider the following example where transsol is the GDX file of the model [TRNSPORT] which can be
found in the GAMS Model Library
set i,j;
parameter b(i),a(j);
$gdxin transsol
$load i b
$loadDC j a
$gdxin transsol
Note that in transsol a depends on i and b depends on j in contrast to this example. While $load i b
works and b is just empty after that line $loadDC j a triggers a domain violation error because in transsol a
depends on i.
loadDCM
$loadDCM does the same as $loadM plus domain checking like $loadDC .
loadDCR
$loadDCR does the same as $loadR plus domain checking like $loadDC.
loadM
$loadM is an alternative form of $load. Instead of replacing an item or causing a domain violation error if the
item was already initialized it merges the contents. Consider the following example where transsol is the
GDX file of the model [TRNSPORT] which can be found in the GAMS Model Library.
set j /1*5/;
$gdxin transsol
$loadm j
display j;
$gdxin transsol
The resulting listing file contains
---- 4 SET j markets
1 , 2 , 3 , 4 , 5 , new-york
chicago , topeka
loadR
$loadR item1 item2 ... will replace the parameters or sets item1 item2 ... by the data stored in the
current GDX file. It must be used in conjunction with the command $gdxIn. Consider the following example,
where transsol is the GDX file of the model [TRNSPORT] which can be found in the GAMS Model Library.
sets i / 1*3 /
j / 1*2 /;
$gdxin transsol
$loadr i j
$gdxin
display i,j;
The resulting listing file contains,
---- 6 SET i canning plants
seattle , san-diego
This option will send a message to the log file. By default, the log file is the console. The default log file can be
reset with the lo and lf command line parameters.
Attention
Leading blanks are ignored when the text is written out to the log file using the $log option.
All special % symbols will be substituted out before the text passed through the $log option is sent to
the log file.
maxGoto 100
Sets the maximum number of jumps to the same label. Once the maximum number is reached an error is
triggered. Consider the following example,
scalar a / 1 /;
$maxgoto 5
$label label1
a = a+10;
display a ;
$goto label1
When $goto label1 is called for the fifth time an error is triggered.
mincol n (1)
Sets the left margin for the input file. All valid data is after and including column n in the input file. All text
before column n is treated as comment and ignored.
Consider the following example,
3 Detailed Description of Dollar Control Options 289
$mincol 30
set definition set i /vienna, rome/
scalar definition scalar a /2.3/ ;
The text strings set definition and scalar definition are treated as comments and ignored since they
begin before column 30.
Any changes in the margins via $maxcol or $mincol will be reported in the listing file with the message that
gives the valid range of input columns. For example, the dollar control option $mincol 20 maxcol 110 will
trigger the message:
NEW MARGIN = 20-110
Attention
GAMS requires that the left margin set by $mincol is smaller than the right margin set by $maxcol.
[on][off]Delim ($offDelim)
Controls whether data in table statements are in comma delimited format. Consider running the following slice
of code,
SETS
PLANT PLANT LOCATIONS /NEWYORK,CHICAGO,LOSANGLS /
MARKET DEMANDS /MIAMI,HOUSTON, PORTLAND/
table dist(plant,market)
$ondelim
,MIAMI,HOUSTON,PORTLAND
NEWYORK,1300,1800,1100
CHICAGO,2200,1300,700
LOSANGLS,3700,2400,2500
$offdelim
display dist;
The resulting listing file contains,
---- 12 PARAMETER dist
$set it TEST
$OnechoV > externalfile1
send %it% to external file
line 2 to send
$Offecho
contains
send %it% to external file
line 2 to send
In contrast to the second case in the first case %it% is substituded by TEST. Note that when there is no path
included the file by default will be placed in the working directory.
[on][off]Embedded ($offEmbedded)
Enables or disables the use of embedded values in parameter and set data statements. For sets, the final text is
concatenated with blank separators. For example, the element texts for the set i and j will be identical:
set k /a,b/
l /a/;
set i(k,l) / a.a aaaa cccc dddd, b.a bbbb cccc dddd /
$onEmbedded
set j(k,l) / (a aaaa, b bbbb).(a cccc) dddd /
[on][off]Empty ($offEmpty)
This option allows empty data statements for list or table formats. By default, data statements cannot be empty.
Consider running the following slice of code,
set i /1,2,3/ ;
set j(i) / / ;
parameter x(i) empty parameter / / ;
table y(i,i) headers only
1 2 3
;
$onempty
set k(i) / / ;
parameter xx(i) empty parameter / / ;
table yy(i,i)
1 2 3
;
The listing file that results looks like,
1 set i /1,2,3/ ;
2 set j(i) / / ;
**** $460
3 parameter x(i) empty parameter / / ;
**** $460
4 table y(i,i) headers only
5 1 2 3
6 ;
**** $462
8 set k(i) / / ;
9 parameter xx(i) empty parameter / / ;
10 table yy(i,i)
11 1 2 3
12 ;
Error Messages
292 Dollar Control Options
460 Empty data statements not allowed. You may want to use $ON/OFFEMPTY
462 The row section in the previous table is missing
Note that empty data statements are not allowed for sets, parameters or tables. These are most likely to
occur when data is being entered into the GAMS model by an external program. Using the $onempty dollar
control option allows one to overcome this problem.
Attention
The empty data statement can only be used with symbols, which have a known dimension. If the dimension
is also derived from the data, the $phantom dollar control option should be used to generate 'phantom' set
elements.
[on][off]End ($offEnd)
Offers alternative syntax for flow control statements. Endloop, endif, endfor, and endwhile are introduced
as key-words with the use of the $onend option that then serves the purpose of closing the loop, if, for, and
while language constructs respectively.
The following example provides the alternate syntax for the four language constructs mentioned above (standard
syntax as eolcomment).
set i/1*3/ ; scalar cond /0/;
parameter a(i)/1 1.23, 2 2.65, 3 1.34/;
$maxcol 40
$onend
loop i do loop (i,
display a; display a;
endloop; );
[on][off]EolCom ($offEolCom)
Switch to control the use of end-of-line comments. By default, the end-of-line comment symbol is set to '!!' but
the processing is disabled.
Consider running the following slice of code,
$oneolcom
set i /1*2/ ; !! set declaration
parameter a(i) ; !! parameter declaration
Note that comments can now be entered on the same line as GAMS code.
3 Detailed Description of Dollar Control Options 293
Attention
$eolcom automatically sets $oneolcom.
7 $ondollar
8 $hidden text inside include file
9 $hidden after second call to include file
Note that the effect of the $ondollar dollar control option inside the include file does not affect the parent file
until $onglobal is turned on. The $hidden text is then echoed to the listing file.
[on][off]Include ($onInclude)
Controls the listing of the expanded include file name in the listing file.
Consider running the following slice of code,
$include inc.inc
$offinclude
$include inc.inc
where the file inc.inc contains the line,
$ondollar
$hidden text inside include file
The resulting listing file is as follows,
INCLUDE D:\GAMS\INC.INC
2 $ondollar
3 $hidden text inside include file
6 $ondollar
7 $hidden text inside include file
Note that the include file name is echoed the first time the include file is used. However, the include file name is
not echoed after $offinclude is set.
[on][off]Inline ($offInline)
Switch to control the use of in-line comments. By default, the in-line comment symbols are set to the two
character pairs / and / but the processing is disabled. These comments can span lines till the end-of-comment
characters are encountered.
Consider running the following slice of code,
$oninline
/* the default comment symbols are now
active. These comments can continue
to additional lines till the closing
comments are found */
Attention
$inlinecom automatically sets $oninline.
Attention
Nested in-line comments are illegal unless $onnestcom is set.
[on][off]Listing ($onListing)
Controls the echoing of input lines to the listing file. Note that suppressed input lines do not generate entries in
the symbol and reference sections appearing at the end of the compilation listing. Lines with errors will always
be listed.
Consider running the following slice of code,
3 Detailed Description of Dollar Control Options 295
set i /0234*0237/
j /a,b,c/ ;
table x(i,j) very long table
a b c
0234 1 2 3
$offlisting
0235 4 5 6
0236 5 6 7
$onlisting
0237 1 1 1
The resulting listing file looks as follows,
1 set i /0234*0237/
2 j /a,b,c/ ;
3 table x(i,j) very long table
4 a b c
5 0234 1 2 3
10 0237 1 1 1
Note that the lines in the source file between the $offlisting and $onlisting settings are not echoed to the
listing file.
[on][off]Local ($onLocal)
$onLocal allows unlimited use of .local on the same symbol in one control stack while $offLocal limits
the use to one. Consider the following example,
set i /1*3/; alias(i,j);
parameter xxx(i,j) / 1.1 1, 2.2 2, 3.3 3, 1.3 13, 3.1 31 /;
display xxx;
parameter g(i,i);
g(i.local-1,i.local) = xxx(i,i); display g;
$offlocal
g(i.local-1,i.local) = xxx(i,i)+1; display g;
The use of $offlocal causes a compilation error in the following line because .local is used twice on the
same symbol in one control stack.
[on][off]Log ($onLog)
Turns on/off line logging for information about the line number and memory consumption during compilation.
This is scoped like the $on/offListing applying only to included files and any subsequent included files but
reverting to $onlog in the parent files i.e. when file1 includes file 2 and file 2 contains $offlog then subsequent
lines in file 2 will not be logged but lines in file 1 will be.
[on][off]Macro ($onMacro)
Enables or disables the expansion of $macros. For example
$macro oneoverit(y) 1/y
$offmacro
y = oneoverit(x1);
display y;
causes an error because the macro oneoverit can not be expanded in line 3.
[on][off]Margin ($offMargin)
Controls the margin marking. The margins are set with $mincol and $maxcol.
Consider running the following slice of code,
$onmargin mincol 20 maxcol 45
Now we have set i plant /US, UK/ This defines I
turned on the scalar x / 3.145 / A scalar example.
296 Dollar Control Options
Attention
The two-pass processing of a GAMS file can lead to seemingly unexpected results. Both the dollar control
options and the data initialization is done in the first pass, and assignments in the second, irrespective of
their relative locations. This is an issue particularly with $onmulti since it allows data initializations to be
performed more than once.
match.
Consider running the following slice of code,
$inlinecom { } onnestcom
{ nesting is now possible in comments { braces
have to match } }
[on][off]Order ($onOrder)
Lag and lead operations require the reference set to be ordered and constant. In some special cases one would
want to use those operation on dynamic and/or unordered sets. The option $on/offOrder has been added to
locally relax the default requirements. The use of this option comes with a price, the system will not be able to
diagnose odd and incorrect formulations and data sets.
[on][off]Put
Causes a block of text to be placed in a put file. These commands are used employing the syntax
file putfile
put putfile
$onPut
Line 1 of text
Line 2 of text
Line 3 of text
Line 4 of text
$offPut
The resulting file putfile.put contains
Line 1 of text
Line 2 of text
Line 3 of text
Line 4 of text
There is also a variant $onPutS that permits parameter substitution and another variant onPutV that forbids
parameter substitution as onPut also does. Consider the following example,
$set it TEST
file putfile
put putfile
$onPutS
Line 1 of text "%it%"
Line 2 of text %it%
$offPut
The created putfile contains
Line 1 of text "TEST"
Line 2 of text TEST
while the putfile created by
$set it TEST
file putfile
put putfile
$onPutV
Line 1 of text "%it%"
Line 2 of text %it%
$offPu
contains
Line 1 of text "%it%"
298 Dollar Control Options
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 thousands of dollars per case
D distance in thousands of miles
F freight in dollars per case per thousand miles
VARIABLES
X shipment quantities in cases
Z total transportation costs in thousands of dollars
EQUATIONS
COST define objective function
DEMAND satisfy demand at market j
SUPPLY observe supply limit at plant i
MODELS
TRANSPORT
FILES
FILE Current file name for FILE.xxx use
PREDEFINED
DIAG
SAMEAS
This serves as a simple description of the symbols used in a model, and can be used in reports and other
documentation.
[on][off]SymXRef ($offSymXRef)
This option controls the following,
3 Detailed Description of Dollar Control Options 299
Collection of cross references for identifiers like sets, parameters, and variables.
Cross-reference report of all collected symbols in listing file
Listing of all referenced symbols and their explanatory text by symbol type in listing file. This is also
reported by using $onsymlist.
SETS
i
k
[on][off]Text
The $onText - $offText pair encloses comment lines. Line numbers in the compiler listing are suppressed to
mark skipped lines.
Consider the following,
* standard comment line
$ontext
Everything here is a comment
until we encounter the closing $offtext
like the one below
$offtext
* another standard comment line
The resulting listing file is as follows,
1 * standard comment line
Everything here is a comment
until we encounter the closing $offtext
like the one below
7 * another standard comment line
Attention
GAMS requires that every $ontext has a matching $offtext, and vice versa.
[on][off]UElList ($offUElList)
This option controls the complete listing of all set elements that have been entered, in the listing file.
The unique element listing in the listing file generated by running [TRNSPORT] with $onUElList is as
follows,
Unique Element Listing
$offVerbatim
$log 123
[on][off]Warning ($$offWarning)
Switch for data domain checking. In some cases it may be useful to accept domain errors in data statements that
are imported from other systems and report warnings instead of errors. Data will be accepted and stored, even
though it is outside the domain.
Attention
This switch effects three types of domain errors usually referred to as error numbers 116, 170 and 171.
This can have serious side affects and one has to exercise great care when using this feature.
Error Messages
E x e c u t i o n
---- 9 SET i
one , two , three
---- 9 SET j
four, five, zero
302 Dollar Control Options
---- 4 SET J
a, b
Note that null does not appear in the listing file.
Attention
Assignment statements on the phantom label are ignored.
a 1.000
prefixPath
Augments the search path in the Windows path environment variable. The use of $prefixpath value results
in the text in value being appended to the beginning of the search path. Consider the following example,
display "%sysenv.PATH%";
$prefixpath C:\somewhereelse\anotherpath
display "%sysenv.PATH%";
If %sysenv.PATH% contains C:\some\path\somehwere in the beginning it will also contain C:\somewhereelse\anotherpath
after the second line and the resulting listing file contains
---- 1
C:\some\path\somehwere
---- 3
C:\somewhereelse\anotherpath;C:\some\path\somehwere
protect
Freezes all values of the named parameters not allowing modification but still allowing their use in model
calculation (.. commands when models are set up) in a privacy setting. The syntax is
$protect item1 item2 ...
3 Detailed Description of Dollar Control Options 303
or
$protect all
where one can list multiple items to protect them. The word all causes protection of all items. These privacy
restrictions can be removed with $expose or $purge.
purge
removes the items and all data associated in a privacy setting. The syntax is
$purge item1 item2 ...
or
$purge all
In the first case only the listed items are removed, in the second case all items are removed. One can set the
corresponding privacy restrictions with $hide or $protect.
Note that a special license file is needed for this feature to work and that the removal only takes effect in the
restart files.
remark
Adds a comment to the listing file with parameter substitution and suppressed line number. Consider the
following example,
$set it TEST
$remark write %it% to the listing file
The resulting listing file contains
write TEST to the listing file
set
Establishes or redefines contents of a control variable that is accessible in the code where the command appears
and all code included therein. The syntax is $set varname expression where varname is any user chosen
variable name and expression is optional and can contain text or a number. These variables are destroyed
using $drop varname.
In contrast to $eval the $set command does not evaluate the expression at compile time.
For differences to $setGlobal and $setLocal consider the following example,
$setGlobal Anumber 3**2+2
$setLocal Bnumber 44/2
$set Cnumber min(33,34)
$ife %Anumber%=11 display "Anumber equals 11"
$ife %Bnumber%=22 display "Bnumber equals 22"
$ife %Cnumber%=33 display "Cnumber equals 33"
$include test2.gms
$setGlobal Dnumber 44
$setLocal Enumber 55
$set Fnumber 66
The resulting listing file contains,
---- 4 Anumber equals 11
---- 3 v2 = delim
---- 4 v3 = string
$log %sysenv.verysilly%
$if NOT "%env%" == "%sysenv.verysilly%" $error setenv did not work
$dropenv verysilly
$if setenv verysilly $error should not be true
The following output is echoed to the log file,
--- Starting compilation
this is very silly
this is very silly
setGlobal
Establishes or redefines contents of a control variable that is accessible in the code where the command appears
and all code included therein. The syntax is $setglobal varname expression where varname is any user
chosen variable name and expression is optional and can contain text or a number. These variables are
destroyed using $dropglobal varname.
In contrast to $evalGlobal the $setGlobal command does not evaluate the expression at compile time. For
differences to $set and $setLocal check the example in the description of $set.
Note that GAMS allows one to define scoped, local and global variables with the same name but treats them as
different under some cases and prioritizes them when using $ife or $if. Consider the following example,
$setglobal notunique aa
$setlocal notunique bb
$set notunique cc
$if "%notunique%" == "aa" display "it is aa";
$if "%notunique%" == "bb" display "it is bb";
$if "%notunique%" == "cc" display "it is cc";
The resulting listing file contains,
---- 5 it is bb
setLocal
Establishes or redefines contents of a control variable that is accessible only in the code module where defined.
The syntax is $setLocal varname expression where varname is any user chosen variable name and
expression is optional and can contain text or a number. These variables are destroyed using $droplocal
varname.
In contrast to $evalLocal the $setLocal command does not evaluate the expression at compile time. For
differences to $set and $setGlobal check the example in the description of $set.
Note that GAMS allows one to define scoped, local and global variables with the same name but treats them as
different under some cases and prioritizes them when using $ife or $if.
Consider the following example,
$setglobal notunique aa
$setlocal notunique bb
$set notunique cc
$if "%notunique%" == "aa" display "it is aa";
$if "%notunique%" == "bb" display "it is bb";
$if "%notunique%" == "cc" display "it is cc";
The resulting listing file contains,
---- 5 it is bb
setNames
Establishes or redefines three control variables so they contain the drive subdirectory, filename and extension
of a file named with full path. The syntax is setnames FILE filepath filename fileextension where
FILE is any filename, filepath is the name of a control variable that will contain the name of the subdirectory
3 Detailed Description of Dollar Control Options 307
where the file is located, filename is the name of a control variable that will contain the root name of the file
and fileextension is the name of a control variable that will contain the extension of the file. Consider the
following example,
$setnames d:\gams\xxx.txt filepath filename fileextension
$setglobal name %filepath%%filename%%fileextension%
$log %name%
FILE is seperated into its three components placing d:\gams into filepath, xxx into filename and
.txt into fileextension. The three items can be recombined back into the original filename by using
%filepath%%filename%%fileextension% as shown in the example.
shift
The $shift option is similar to the DOS batch shift operator. It shifts the order of all parameters passed once to
the 'left'. This effectively drops the lowest numbered parameter in the list. Consider the following example,
scalar a, b, c ; a = 1 ;
$batinclude inc.inc a b c
display a, b, c ;
where the batch include file inc.inc is as follows,
%2 = %1 + 1 ;
$shift
%2 = %1 + 1 ;
The resulting listing file contains,
1 scalar a, b, c ; a = 1 ;
BATINCLUDE C:\PROGRAM FILES\GAMSIDE\INC.INC
3 b = a + 1 ;
5 c = b + 1 ;
6 display a, b, c ;
In the first statement in the include file, %1 is the first argument in the $batinclude call and is interpreted in this
case as a. %2 is the second argument in the $batinclude call and is interpreted as b. This leads to the overall
assignment being interpreted as b=a+1.
The $shift option shifts the arguments to the left. So now, %1 is interpreted as b, and %2 is interpreted as c.
This leads to the second assignment being interpreted as c=b+1.
The result of the display statement in the input file is therefore,
---- 6 PARAMETER A = 1.000
PARAMETER B = 2.000
PARAMETER C = 3.000
show
Shows current values of the control variables plus a list of the macros. Consider the following example,
$set it 1
$setlocal yy
$setglobal gg what
$include includ
$show
where indlud.gms is
$set inincs
$setlocal inincsl
$setglobal inincsg
$show
The resulting listing file contains,
Level SetVal Type Text
308 Dollar Control Options
-----------------------------------------------------
1 inincsl LOCAL
1 inincs SCOPED
0 yy LOCAL
0 it SCOPED 1
0 gg GLOBAL what
1 inincsg GLOBAL
and
Level SetVal Type Text
-----------------------------------------------------
0 yy LOCAL
0 it SCOPED 1
0 gg GLOBAL what
1 inincsg GLOBAL
Note that only the item defined as $setGlobal in the included file carries over.
single
The lines following a $single option will be echoed single spaced on the compiler listing. This option is the
default, and is only useful as a switch to turn off the $double option.
Consider the following example,
set i /1*2/ ;
scalar a /1/ ;
$double
set j /10*15/ ;
scalar b /2/ ;
$single
set k /5*10/ ;
scalar c /3/ ;
The resulting listing file looks as follows,
1 set i /1*2/ ;
2 scalar a /1/ ;
4 set j /10*15/ ;
5 scalar b /2/ ;
7 set k /5*10/ ;
8 scalar c /3/ ;
Note that lines between the $double and $single options are listed double spaced, while the lines after the
$single option revert back to being listed singly spaced.
splitOption
Establishes or redefines two compile-time variables so they contain the name and value of an option key/value
pair specified in various formats. The syntax is splitOption KEYVALPAIR optname optvalue where
KEYVALPAIR is a string formatted as -opt=val or -opt val (instead of - one can also use /). optname is
the name of a compile-time variable that will contain the name of the option and optvalue is the name of a
compile-time variable that will contain the value of the option. This is useful in particular in combination with
batInclude files. Consider the following example,
* Default values for named arguments
$set a1 1
$set a2 2
$set a3 3
$label ProcessNamedArguments
$ splitOption "%1" key val
3 Detailed Description of Dollar Control Options 309
Error Messages
36 = or .. or := or $= operator expected
rest of statement ignored
140 Unknown symbol
299 Unexpected end of file
stitle
This option sets the subtitle in the page header of the listing file to 'text' which follows immediately the keyword
stitle. The next output line will appear on a new page in the listing file.
Consider the following example,
$stitle data tables for input/output
stop
Stops program compilation without creating an error. But there is a difference to $exit. If you have only one
input file $stop and $exit will do the same thing. If you are in an include file, $exit acts like an end-of file on
the include file. However, if you encounter a $stop in an include file, GAMS will stop reading all input.
sysInclude
Equivalent to $batInclude:
$sysinclude file arg1 arg2 ...
However, if an incomplete path is given, the file name is completed using the system include directory. By
default, the system include directory is set to the GAMS system directory. The default directory can be reset
with the sdir command line parameter.
310 Dollar Control Options
Parameters
$gdxout tran
$unload i j
$unload b=dem a=sup
$unload d
$gdxout
This will create a file tran.gdx containing i,j,d and parameters a and b which are now declared as dem and
sup.
use205
3 Detailed Description of Dollar Control Options 311
This option sets the GAMS syntax to that of Release 2.05. This is mainly used for backward compatibility. New
keywords have been introduced in the GAMS language since Release 2.05. Models developed earlier that use
identifiers that have since become keywords will cause errors when run with the latest version of GAMS. This
option will allow one to run such models.
Consider the following example,
$use205
set if /1.2.3/; scalar x ;
The word if is a keyword in GAMS introduced with the first version of Release 2.25. The setting of the
$use205 option allows if to be used as an identifier since it was not a keyword in Release 2.05.
use225
This option sets the GAMS syntax to that of first version of Release 2.25. This is mainly used for backward
compatibility. New keywords have been introduced in the GAMS language since the first version of Release
2.25. Models developed earlier that use identifiers that have since become keywords will cause errors when run
with the latest version of GAMS. This option will allow one to run such models.
Consider the following example,
$use225
set for /1.2.3/; scalar x ;
The word for is a keyword in GAMS introduced with the later versions of Release 2.25. The setting of the
$use225 option allows for to be used as an identifier since it was not a keyword in the first version of Release
2.25.
use999
This option sets the GAMS syntax to that of the latest version of the compiler. This option is the default.
Consider the following example,
$use225
set for /1.2.3/; scalar x ;
$use999
for (x=1 to 3, display x) ;
The word for is used as a set identifier by setting the option $use225, and later the keyword for is used as a
looping construct by setting the language syntax to that of the latest version by setting $use999.
version
$version nnn issues a compilation error if nnn is greater than the current GAMS version.
warning
$warning issues a compilation warning but continues compilation and execution.
312 Dollar Control Options
Chapter 22
1 Introduction
The option statement is used to set various global system parameters that control output detail, solution process and the
layout of displays. They are processed at execution time unlike the dollar control options discussed in Chapter Dollar Control
Options . They are provided to give flexibility to the user who would like to change the way GAMS would normally do
things. GAMS does provide default values that are adequate for the most purposes, but there are always cases when the user
would like to maintain control of aspects of the run.
where the 'keyword1' and 'keyword2' are recognized option names (but not reserved words) and the 'value1' and
'value2' are valid values for each of the respective options. Note that commas or end-of-line characters are both legal
separators between options.
Attention
Option names are not reserved words and therefore do not conflict with other uses of their name.
Attention
An option statement is executed by GAMS in sequence with other instructions. Therefore, if an option statement
comes between two solve statements, the new values are assigned between the solves and thus apply only to the
second one.
The values associated with an option can be changed as often as necessary, with the new value replacing the older
one each time.
option profit:0:3:2;
option eject
iterlim = 100 , solprint = off ;
solve mymodel using lp maximizing profit ;
display profit.l ;
input("val1") = 5.3 ;
option iterlim = 50 ;
solve mymodel using lp maximizing profit ;
The option statement in the second line affects the display format of the identifier profit. More details on this option can
be found under the heading <identifier> in the following section. The option on the second line has no value associated
with it, and serves to advance the output in the listing file to the next page. The third line contains two options - iterlim,
and solprint. The values associated with the two options on the fourth line are of different types - iterlim has an integer
value while solprint requires a character string as a value. Note also that the end of line and the comma serve as legal
separators between two options.
The option iterlim serves to limit the number of iterations taken by the solver while attempting to solve the lp model
mymodel. After mymodel is solved for the first time, some of the input data is changed and the model is solved again.
However, before the second solve statement, the option iterlim is changed to 50. The effect of the sequence above is to
limit the first solve to less than 100 iterations and the second to less than 50.
2 List of Options
The options available through the option statement are grouped into the following functional categories affecting
output detail
solver specific parameters
input program control
choice of solver
The following subsections briefly describes the various options in each of the categories. Section Detailed Description of
Options contains a reference list of all options available through the option statement in alphabetical order with detailed
description for each.
Option Description
<identifier> controls print format
asyncsollst Print solution listing when asynchronous solve (Grid or Threads) is used
decimals global control of print format
eject advances output to next page
2 List of Options 315
Option Description
limcol number of columns listed
limrow number of rows listed
mcprholdfx Print list of rows that are perpendicular to variables removed due to the holdfixed setting
profile lists program execution profile
profiletol sets tolerance for execution profile
solprint controls printing of solution
solslack controls type of equation information
sysout controls printing of solver status file
Option Description
bratio use of advanced basis
domlim limits number of domain errors
iterlim limits number of solver iterations
optca sets absolute optimality tolerance
optcr sets relative optimality tolerance
reslim limits amount of solver time
savepoint save solver point in GDX file
solvelink solver link options
threads number of threads to be used by a solver
Option Description
cns sets solver for cns model type
dnlp sets solver for dnlp model type
lp sets solver for lp model type
mcp sets solver for mcp model type
minlp sets solver for minlp model typ
mip sets solver for mip model type
mpec sets solver for mpec model type
nlp sets solver for nlp model type
rminlp sets solver for rminlp model type
rmip sets solver for rmip model type
solver sets solver for all model types that the solver can process
Option Description
seed resets seed for pseudo random number generator
solveopt controls return of solution values to
strictsingleton error if assignment to singleton set has multiple elements
316 The Option Statement
Option Description
integer1 integer communication cell
real1 real communication cell
shuffle rearranges the values of a parameter in random order
This section describes each of the options in detail. The options are listed in alphabetical order for easy reference. In each of
the following options, the default value, if available, is bracketed.
<identifier>
Display specifier: identifier:d, identifier:d:r:c Defines print formats for identifier when used in a
display statement. d is the number of decimal places, r is the number of index positions printed as row labels, c
is the number of index positions printed as column labels; the remaining index positions (if any) will be used to
index the planes (index order: plane, row, column); if r is zero list format will be used. The default setting is
described in Section The Label Order in Displays.
asyncsollst (0)
Print solution listing when asynchronous solve (Grid or Threads) is used.
bratio (0.25)
Certain solution procedures can restart from an advanced basis that is constructed automatically. This option is
used to specify whether or not basis information (probably from an earlier solve) is used. The use of this basis is
rejected if the number of basic variables is smaller than bratio times the size of the basis. Setting bratio to 1
will cause all existing basis information to be discarded, which is sometimes needed with nonlinear problems. A
bratio of 0 accepts any basis, and a bratio of 1 always rejects the basis. Setting bratio to 0 forces GAMS to
construct a basis using whatever information is available. If bratio has been set to 0 and there was no previous
solve, an 'all slack' (sometimes called 'all logical' ) basis will be provided. This option is not useful for MIP
solvers.
Range: [10,31]
cns (default)
The default cns solver is set during installation.The user can change this default by setting this option to the re-
quired solver. The list of cns solvers available with your system can be obtained by reading the gamscmp.txt
file that is present in the GAMS system directory. A value of default will change the cns solver back to the
default one as specified in gamscmp.txt.
decimals (3)
Number of decimals printed for symbols not having a specific print format attached.
Range: [0,8]
dnlp (default)
This option controls the solver used to solve dnlp models. For details cf. option cns.
domlim (0)
This controls the maximum number of domain errors (undefined operations like division by zero) a nonlinear
solver will perform, while calculating function and derivative values, before it terminates the run. Nonlinear
solvers have difficulty recovering after attempting an undefined operation.
eject
Advances output in the listing file to the next page.
3 Detailed Description of Options 317
integer1 to integer5
Integer communication cell that can contain any integer number.
iterlim (2000000000)
This option will cause the solver to interrupt the solution process after iterlim iterations and return the current
solution values to GAMS.
limcol (3)
This controls the number of columns that are listed for each variable in the COLUMN LISTING section of the
listing file. Specify zero to suppress the COLUMN LISTING altogether.
limrow (3)
This controls the number of rows that are listed for each equation in the EQUATION LISTING section of the
listing file. Specify zero to suppress the EQUATION LISTING altogether.
mcprholdfx (0)
Print list of rows that are perpendicular to variables removed due to the holdfixed setting.
mpec (default)
This option controls the solver used to solve mpec models. For details cf. option cns.
lp (default)
This option controls the solver used to solve lp models. For details cf. option cns.
mcp (default)
This option controls the solver used to solve mcp models. For details cf. option cns .
minlp (default)
This option controls the solver used to solve minlp models. For details cf. option cns .
mip (default)
This option controls the solver used to solve mip models. For details cf. option cns .
miqcp (default)
This option controls the solver used to solve miqcp models. For details cf. option cns.
nlp (default)
This option controls the solver used to solve nlp models. For details cf. option cns.
optca (0.0)
This option is only used with problems containing discrete variables (i.e. the GAMS model type mip). General
mixed integer problems are often extremely difficult to solve, and proving that a solution found is the best
possible can use enormous amounts of resources. This option sets an absolute termination tolerance,
which means that the solver will stop and report on the first solution found whose objective value is within
optca of the best possible solution.
optcr (0.1)
This option sets a relative termination tolerance for problems containing discrete variables, which means that
the solver will stop and report on the first solution found whose objective value is within 100optcr of the best
possible solution.
profile (0)
This option is used to generate more information on program execution profiles. This option is equivalent in
function to the profile command line parameter.
0 No execution profile is generated in listing file
1 The listing file reports execution times for each statement and the number of set elements over
which the particular statement is executed.
318 The Option Statement
When the parameter has no data, the domain or the universe is used to assign the numbers 1 to N where N is the
number of elements in the domain or the universe. (See declaration of A and B below). When the parameter has
data, the domain or the universe is used to insert zeroes for the missing entries. These zero values participate in
the random shuffle, but will not be stored in the parameter (See declaration of C and D below):
* some different declarations to show their impact on the shuffle option
set i /i1*i5/
j /j1*j5/;
parameter A(*);
option shuffle=A; display A;
parameter A(i);
option shuffle=A;
i1 YES
i2 YES
i3 YES
i4 YES
i5 YES
i6 YES
solprint (on)
This option controls the printing of the model solution in the listing file. Using this specification suppresses the
list of the solution following a solve.
on The solution is printed one line per row and column in the listing file.
off Solution details are not printed. Although this saves paper, we do not recommend it unless you
understand your model very well and solve it often.
silent Suppress all solution information
320 The Option Statement
solslack (0)
This option causes the equation output in the listing file to contain slack variable values instead of level values.
0 Equation output in listing file contains level values between lower and upper bound values
1 Equation output in listing file contains slack values between lower and upper bound values
solvelink (0)
This option controls GAMS function when linking to solve.
0 GAMS operates as always
1 the solver is called from a shell and GAMS remains open
2 the solver is called with a spawn (if possible as determined by GAMS) or a shell if the spawn is
not possible) and GAMS remains open
3 GAMS starts the solution and continues in a Grid computing environment
4 GAMS starts the solution and waits (same submission process as 3) in a Grid computing
environment
5 the problem is passed to the solver in core without use of temporary files
6 the problem is passed to the solver in core without use of temporary files, GAMS does not wait for
the solver to come back
7 the problem is passed to the solver in core without use of temporary files, GAMS waits for the
solver to come back but uses same submission process as 6
solver (default)
The solver for multiple model types can be set via the Option solver=abc; in the GAMS model source code. This
sets the solver for model types abc can handle to abc. With the option solver=abc; the order among other solver
setting options is significant. For example, option lp=conopt, solver=bdmlp; will first set the solver for LP to
Conopt and in the next step to BDMLP because BDMLP is capable of handling model type LP. Setting solver
twice can also make sense: option solver=conopt, solver=cbc; will result into setting the solver for model types
CNS, DNLP, NLP, QCP, RMIQCP, and RMINLP to Conopt and the solver for model types LP, RMIP, and MIP
to CBC.
solveopt (merge)
This option tells GAMS how to manage the model solution when only part of the variables and equations are in
the particular problem being solved.
replace All equations appearing in the model list will be completely replaced by the new model
results. Variables are only replaced if they appear in the final model.
merge The new model results are merged into the existing structures.
clear Similar to the replace option; in addition, variables appearing in the symbolic equations but
squeezed out in the final model, are removed.
strictSingleton (1)
This option affects the behavior of a membership assignment to a singleton set.
0 GAMS does not complain about an assignment with more than one element on the right hand
side but takes the first one
1 GAMS creates an error for an assignment with more than one element on the right hand side
sysout (off)
This option controls the printing of the solver status file as part of the listing file. The contents of the solver
status file are useful if you are interested in the behavior of the solver. If the solver crashes or encounters any
difficulty, the contents of the solver status file will be automatically sent to the listing file.
on Prints the system output file of the solver
3 Detailed Description of Options 321
off No subsystem output appears on output file unless a subsystem error has occurred.
threads (1)
This option controls the number of threads or CPU cores to be used by a solver.
-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)
322 The Option Statement
Chapter 23
1 Introduction
GAMS saves the information provided in the input files in intermediate, mostly binary, files. These files are referred to as
work files or scratch files. Some of these files are used to exchange information between GAMS and the various solvers. Just
before a GAMS run is complete, these files are usually deleted.
Input files can be processed in parts through the use of these intermediate files. This is an extremely powerful feature that can
reduce the time needed when several runs of the same model are being made with different data.
It may be clearer if the process is described in a different way. Imagine taking a large GAMS program and running it,
producing one output file. Then think of splitting the program into two pieces. The first piece is run and the resulting work
file is saved along with the resulting listing file. Then the second piece is run after reading in the data from the work file saved
previously. A new listing file is generated for the second piece. The content of the output that results is the same, though
slightly rearranged, as the case when the large file was run. Splitting the files allows one to interrupt a GAMS task and restart
it later without loss of information. Furthermore, changes could be made or errors corrected to the later parts.
Sets
i "canning plants" / seattle, san-diego /
j "markets" / new-york, chicago, topeka / ;
Parameters
a(i) "capacity of plant i in cases"
/ seattle 350
san-diego 600 /
Variables
x(i,j) "shipment quantities in cases"
z "total transportation costs in 1000$" ;
Positive Variable x ;
Equations
cost "define objective function"
supply(i) "observe supply limit at plant i"
demand(j) "satisfy demand at market j" ;
Note that [TRNSPORT] results from appending file2.gms at the end of file1.gms.
The information in file1.gms can be stored by using the following call to GAMS,
Attention
The Work file preserves all information (including declarations, values, option settings and compiler dollar
directives) known to GAMS at the end of the run that created them.
The work file is not machine specific, it is portable between platforms. For example, a work file generated on a
PC running Windows can be re-used on a Sun machine running Solaris.
GAMS reads the work file named trans.g00 and regenerates the information stored in file1.gms. Then file2.gms is
run and the result is as if the two files were concatenated.
A restarted run also requires a continuation input file. The restart does not alter work files. They can be used repeatedly to
continue a particular run many times, possibly with many different continuation input files.
The most common mistake that occurs in using the save and restart feature is running GAMS on the same file twice, so all
the data and equation definitions get repeated which causes compilation errors during restart. The following calls will cause
errors:
In general, definitions of data constructs should not be repeated either in the same file or across files used in the Save and
Restart operation. GAMS works as if the two files are actually concatenated. In order to avoid any syntax problems, one
needs to understand the GAMS syntax regarding data entry. By default GAMS that each data item be entered only once.
Once the elements that form the set have been defined, the set cannot be redefined through the data statement. For example,
the following set of statements are all invalid:
Similar rules apply to Scalar, Parameter, and Table declarations. One can only use assignment statements to change values of
scalars, parameters and tables once they have been specified by the data statement. For example,
parameter a(i) /
seattle 20
san-diego 50 / ;
a("seattle") = 10 ;
a("san-diego") = 100 ;
One can, however, separate the definition of the data type from the actual data entry. For example, the following succession
of statements is valid:
Set i ;
Set i /seattle, san-diego / ;
This is true with the other data types as well. This last feature is very useful in completely separating the model definition
from the data, and leads to the development of a good runtime GAMS model.
Attention
It is the responsibility of the modeler to ensure that the contents of the input file matches that of the work
file, although the compiler will issue errors if it detects any inconsistencies, such as references to symbols not
previously declared.
A Work file can be used only by GAMS tasks requesting a restarted run.
A Work file can be saved following a restarted run, thus producing another work file that reflects the state of the
job following completion of the statements in the continuation file.
Positive Variable x ;
Note that this representation does not contain any data, and is a purely algebraic representation of the transportation problem.
Running this model and saving the resulting work file will allow the model to be used with the data stored in a separate file
(file2.gms).
Table d(i,j)
new-york chicago topeka
seattle 2.5 1.7 1.8
san-diego 2.5 1.8 1.4 ;
Scalar f / 90 / ;
This file contains the data for the model and the solve statement.
and then distribute the file trans.g00 file that result, along with the example file2.gms.
If the end-user has a run-time license for GAMS, they will not be able to see the model, nor change it by adding any new
variables or equations. The end-user will only be able to change the data, and run the model developed during the save
process. However, the end-user will have full control of the data, and will be able to manipulate the number of elements in
the set, and the values of the various scalars, parameters, and tables.
328 The Save and Restart Feature
The end user will run the model with the following command:
1 Introduction
When models are distributed to users other than the original developers or embedded in applications to be deployed by other
developers, issues of privacy, security, data integrity and ownership arise. We may have to hide, protect or purge some parts
of the model before it can be released. The information to be protected can be of numeric or symbolic nature. For example:
Privacy
A Social Accounting Matrix supplied by a Statistical Office is required in a general equilibrium model to be
used by the Ministry of Finance. The data from the statistical office needs to be protected for obvious privacy
reasons and the model experiments are used to evaluate policy options that are highly confidential. Most of the
model structure is public, most of the data however is private and model results need to be transformed in such a
way as to prohibit the discovery of the original data.
Security
Components of a model contain proprietary information that describes mathematically a chemical reaction. The
associated algebra and some of the data are considered of strategic importance and need to be hidden completely.
The final model however, will be used at different locations around the world.
Integrity
Data integrity safeguards are needed to assure the proper functioning of a model. Certain data and symbolic
information needs to be protected from accidental changes that would compromise the operation of the model.
To address these issues, access control at a symbol level and secure restart files have been added to the GAMS system.
Access Control
The access to GAMS symbols like sets, variables, parameters and equations can be changed once with the
compile time commands $purge, $hide, $protect and $expose.
A special license is required to set the access controls and to create a corresponding secure work file. Reporting features have
been added to allow audits and traces during generation and use of secure work files.
2 A First Example
The model [TRNSPORT] from the GAMS model library will be used to illustrate the creation and deployment of a secure
work file. Assume we want to distribute this model but have concerns about proprietary formulations and data. In addition we
would like to protect the user from making unintentional modifications to the model. We assume that the objective function
and the supply constraints are to be hidden from other users and only the demand figures can be changed. Data that is not
needed any more will be purged as well. This will be demonstrated below using the command line interface to GAMS . 2
First we will copy the model from the model library, run the model and save a normal work file:
We continue to enter access control commands in a file called t2.gms and create a secure work file with the name t2.g00:
$eolcom //
$protect all // make all symbol read only
$purge d f // remove items d and f
$hide cost supply a // make objective invisible
$expose transport b // allow changes to b
The access control commands are activated by the use of the privacy GAMS license option PLICENSE. This option specifies
the name of the target user license file. The save/restart file t2.g00 can only be read with the target license file.
The three lines starting with '' are a recap of the content of the target license file. From now on, the source and the target
licensees are 'burned into' this file and all its descendants. We are ready to send the restart file to the target user or system.
The target user can now run the model with new data, add new GAMS statements, and make new save/restart files. The only
restrictions are that some of the symbols are hidden and that this model can only be executed using the target license file. For
example, the target user may want to half the demand and compare the original solution with the new one. We will call this
program t3.gms and it will be executed on the target system:
rep(i,j,half) = x.l(i,j);
display rep;
Note that the originator/owner of the secure work file is mentioned by name on the log file. A similar message is contained in
the listing file:
A more detailed inspection of the listing file will show that the hidden variables and equations do not appear in the usual
equation/variable listings and the solution print. The hidden items can only be accessed via a public (exposed) model and a
solve statement.
In the following two sections we will describe secure work files and the access control commands in more detail.
The keyword ALL applies the ACC to all identifiers defined up to this point in the GAMS source code. ACC's can be changed
and redefined within the same GAMS program. Identifiers inherited from a restart file cannot be changed, however.
$include trnsport.gms
variable newc(i,j) new tansport data;
equation defnewc(i,j) definition of new transport data;
model getc compute new transport data / defnewc /;
defnewc(i,j).. newc(i,j) =e= f*d(i,j)/1000;
solve getc using cns;
Next, we change the objective function of the original model to a more complicated nonlinear function. Furthermore, we
will compute a base case value to be used later in the reporting model. Note the reference to newc.l(i,j), since nexc is a
variable we have to specify that we only want the level value:
We will save the above GAMS code under the name p1.gms, execute and make a save/restart file with the name p1.g00 as
follows:
> gams p1 s=p1
Now we are ready to make some test runs similar to those we expect to be defined by the target user. We will define three
scenarios to be solved in a loop and name the file u1.gms:
set s / one,two,three /;
parameter sbeta(s) / one 1.25, two 1.5, three 2.0 /
sf(s) / one 85, two 75, three 50 /;
parameter report summary report;
loop(s,
beta = sbeta(s);
f = sf(s);
solve getc using cns;
solve newtrans using nlp minmizing z;
solve rep using cns;
report(i,j,s) = delta.l(i,j);
report(,beta,s) = beta;
report(,f,s) = f;
report(obj,z,s) = z.l ) ;
display report;
When executing the above GAMS code together with the original transport model from the GAMS model library we will get
the following results.
Note that all symbols are still completely exposed. We need to add access controls to the model p1.gms before we can ship it
to the target client. The information to be protected is the original distance matrix and derived information. We start out
by hiding everything and then give access to selected parts of the model. We collect the access control information in the
file s1.gms shown below and save the secure work file under the name s1.g00. Since we are still testing, we use our own
license as target user. This will allows us to test the system the same way the target user will use it:
$hide all
$expose getc newtrans rep
$expose i j z delta
$expose f beta a b
To test the new secure file, we run again the problem u1.gms. When doing so you will observe that equation, variable and
solution listings related to the hidden variables are not shown any more. Any attempt to reference a hidden variable will case
a compilation error.
> gams u1 r=s1
Before we can ship a secure work file we need a copy of the target user license file. We then will restart again from p1.gms,
zip the resulting secure files and we are ready to distribute the model:
Solvers are not security aware and it would be possible to write a special GAMS solver that extracts information about
a specific model instance. Primal and duals values as well as first partial derivatives could be extracted and displayed.
The names and explanatory text of all GAMS symbols are retained in the work file and could be accessed by a special
GAMS solver.
The source and target license files locked to the secure work file cannot be changed. If the target user upgrades the
GAMS system and receives a new license file, the secure work file cannot be read any more.
Now we move the obfuscated work file to a non-secure machine and execute there:
We bring the new (still obfuscated) work file 1obfuscated.g00 with the results back to the safe machine and do a continued
compilation with reporting and export. The continued compilation restarts from the obfuscated work file with all the results
but gets a second work file (r=0named) with proper names through a new option RestartNamed (rn):
We take everything from the obfuscated work file but only read the string pool and the listing file title and subtitle from the
file specified via rn. We do the following checks to ensure that the named and obfuscated work files are consistent:
3. the first 10 labels point to the same addresses in the string pool
All these checks can be done very quickly without reading too much of the named work file.
The first two checks imply that we can't do a continued compilation with code that introduces new symbols or labels off the
obfuscated work file or even new strings (display 'this is a new string'; ). We can't write useful code that can be
executed off the obfuscated work file since we don't know the obfuscated symbols and labels. So practically we can just
execute the obfuscated work file off an empty GAMS program as shown above.
336 Secure Work Files
Chapter 25
1 Introduction
When models are distributed to users other than the original developers, issues of privacy, security, data integrity and
ownership arise. Besides using secure work files, one can compress and encrypt GAMS input files. The compression and
decompression of files is available to any GAMS user. The encryption follows the work file security model and requires
special licensing. Three new Dollar Control Options have been introduced:
Option Description
Encrypts into a GAMS system file
$Encrypt <source> <target>
Compresses into a GAMS system file
$Compress <source> <target>
Decompresses a GAMS system file
$Decompress <source> <target>
Encryption is only available if a system is licensed for secure work files and usually requires a target license file which will
contain the user or target encryption key. Once a file has been encrypted it cannot be decrypted any more.
The use of a PLICENSE parameter will specify the target or privacy license to be used as a user key for encrypting.
Decompression and encrypting is done on the fly into memory when reading the GAMS system files. GAMS will recognize
if a file is just plain text or compressed and/or encrypted and will validate and process the files accordingly.
Finally, all compressed and encrypted files are, of course, platform independent as any other GAMS input file.
2 A First Example
The model [TRNSPORT] from the GAMS model library will be used to illustrate the creation of a compressed input file.
First we will copy the model from the GAMS model and create a compressed version. Spaces are recognized as separators
between the source and target file names which means you have to use quotes (single or double) if the filenames contain
spaces:
...
--- Compress Source: C:\support\28Dec\trnsport.gms
338 Compressed and Encrypted Input Files
Now we can treat the compressed input files like any other GAMS input file and the listing files will be identical because the
decompressed input is echoed just like any normal input line:
Finally, we may want to encrypt the input file in a way to hide the equation definitions. To do this we just insert $Offlisting
and $Onlisting around the blocks of GAMS code we want to hide. We now can encrypt the modified model file by using a
privacy or target license file to lock the new encrypted file to this license key.
This new version of t1.gms can only be used with the target license file. To simulate the target environment we can force the
target license to be used instead of the installed one.
Note the use of dumopt=19 which is sometimes used for debugging and maintenance, writes a clean copy of the input to the
file t1.dmp (all include files and macros are expanded). In the file t1.dmp you will see that the input text between $offlisting
and $onlisting is suppressed.
An attempt to $Decompress and decrypt the file will fail as well. Once a file has been encrypted, it cannot be decrypted any
more. For example, trying to decompress as in the example before will fail:
> gams t4
...
--- Decompress Source: C:\support\28Dec\t1.gms
--- Decompress Target: C:\support\28Dec\t3.org
--- Decompress Error : Security violation
$ontext
This model demonstrates the use of compressed input files.
Remember, if the file names contain spaces you need
4 The ENCRYPT GAMSLIB Model 339
$ontext
Input files can be encrypted and use the save/privacy license
file mechanism for managing the user password. Similar to
compression, we offer an $encrypt utility to lock any file to a
specific target license file. Once a file has been encrypted it
can only be read by a gams program that has the matching license
file. There is no inverse operation possible: you cannot recover
the original GAMS file from the encrypted version.
$offtext
$eolcom //
$if NOT errorfree $abort pending errors
$decompress t1.gms t1.org // this has to fail
$if errorfree $abort decompress did not fail
$clearerror
1 Introduction
As systems with multiple CPUs and High Performance Computing Grids are becoming available more widely, the GAMS
language has been extended to take advantage of these new environments. New language features facilitate the management
of asynchronous submission and collection of model solution tasks in a platform independent fashion. A simple architecture,
relying on existing operating system functionality allows for rapid introduction of new environments and provides for an
open research architecture.
A typical application uses a coarse grain approach involving hundreds or thousands of model solutions tasks which can be
carried out in parallel. For example:
Scenario Analysis
Monte Carlo Simulations
Lagrangian Relaxation
Decomposition Algorithms
Advanced Solution Approaches
The grid features work on all GAMS platforms and have been tailored to many different environments, like the Condor
Resource Manager, a system for high throughput computing from the University of Wisconsin or the Sun Grid Engine.
Researchers using Condor reported a delivery of 5000 CPU hours in 20 hours wall clock time.
Disclaimer. The use of the term grid computing may be offensive to some purists in the computer science world. We use it
very loosely to refer to a collection of computing components that allow us to provide high throughput to certain applications.
One may also think of it as a resurrection of the commercial service bureau concept of some 30 years ago.
Caution. Although these features have been tested on all platforms and are part of our standard release we may change the
approach and introduce alternative mechanisms in the future.
Acknowledgments. Prof. Monique Guignard-Spielberg from the Wharton School at U Penn introduced us to parallel
Lagrangian Relaxation on the SUN Grid Environment. Prof. Michael Ferris from the University of Wisconsin at Madison
adopted our original GAMS grid approach to the high throughput system Condor and helped to make this approach a practical
proposition.
2 Basic Concepts
The grid facility separates the solution into several steps which then can be controlled separately. We will first review what
happens during the synchronous solution step and then introduce the asynchronous or parallel solution steps.
When GAMS encounters a solve statement during execution it proceeds in three basic steps:
344 The Grid and Multi-Threading Solve Facility
1. Generation. The symbolic equations of the model are used to instantiate the model using the current state of the
GAMS data base. This instance contains all information and services needed by a solution method to attempt a solution.
This representation is independent of the solution subsystem and computing platform.
2. Solution. The model instance is handed over to a solution subsystem and GAMS will wait until the solver subsystem
terminates.
3. Update. The detailed solution and statistics are used to update the GAMS data base.
In most cases, the time taken to generate the model and update the data base with the solution will be much smaller than the
actual time spent in a specific solution subsystem. The model generation takes a few seconds, whereas the time to obtain an
optimal solution may take a few minutes to several hours. If sequential model solutions do not depend on each other, we can
solve in parallel and update the data base in random order. All we need is a facility to generate models, submit them for
solution and continue. At a convenient point in our GAMS program we will then look for the completed solution and update
the data base accordingly. We will term this first phase the submission loop and the subsequent phase the collection loop:
Submission Loop.
In this phase we will generate and submit models for solutions that can be solved independently.
Collection Loop.
The solutions of the previously submitted models are collected as soon a solution is available. It may be necessary
to wait for some solutions to complete by putting the GAMS program to 'sleep'.
Note that we have assumed that there will be no errors in any of those steps. This, of course, will not always be the case and
elaborate mechanisms are in place to make the operation fail-safe.
3 A First Example
The model [QMEANVAR] from the GAMS Model Library will be used to illustrate the use of the basic grid facility. This
model traces an efficiency frontier for restructuring an investment portfolio. Each point on the frontier requires the solution
of independent quadratic mixed integer models. The original solution loop is shown below:
Loop(p(pp),
ret.fx = rmin + (rmax-rmin)/(card(pp)+1)*ord(pp) ;
Solve minvar min var using miqcp ;
xres(i,p) = x.l(i);
report(p,i,inc) = xi.l(i);
report(p,i,dec) = xd.l(i) );
This loop will save the solutions to the model MINVAR for different returns RET. Since the solutions do not depend on the
order in which they are carried out, we can rewrite this loop to operate in parallel. The first step is to write the submit loop:
The model attribute .solvelink controls the behavior of the solve statement. A value of '3' tells GAMSto generate and submit
the model for solution and continue without waiting for the completion of the solution step. There is a new model attribute
.handle which provides a unique identification of the submitted solution request. We need to store those handle values, in
this case in the parameter h, to be used later to collect the solutions once completed. This is then done with a collection loop:
loop(pp$handlecollect(h(pp)),
3 A First Example 345
xres(i,pp) = x.l(i);
report(pp,i,inc) = xi.l(i);
report(pp,i,dec) = xd.l(i) );
The function handlecollect interrogates the solution process. If the solution process has been completed the results will be
retrieved and the function returns a value of 1. If the solution is not ready to be retrieved the value zero will be returned.
The above collection loop has one big flaw. If a solution was not ready it will not be retrieved. We need to call this loop
several times until all solutions have been retrieved or we get tired of it and quit. We will use a repeat-until construct and the
handle parameter h to control the loop to look only for the not yet loaded solutions as shown below:
Repeat
loop(pp$handlecollect(h(pp)),
xres(i,pp) = x.l(i);
report(pp,i,inc) = xi.l(i);
report(pp,i,dec) = xd.l(i);
display$handledelete(h(pp)) trouble deleting handles ;
h(pp) = 0 ) ;
display$sleep(card(h)*0.2) sleep some time;
until card(h) = 0 or timeelapsed > 100;
xres(i,pp)$h(pp) = na;
Once we have extracted a solution we will set the handle parameter to zero. In addition, we want to remove the instance from
the system by calling the function handledelete which returns zero if successful (see definition). No harm is done if it fails
but we want to be notified via the conditional display statement. Before running the collection loop again, we may want to
wait a while to give the system time to complete more solution steps. This is done with the sleep command that sleeps some
time. The final wrinkle is to terminate after 100 seconds elapsed time, even if we did not get all solutions. This is important,
because if one of the solution steps fails our program would never terminate. The last statement sets the results of the missed
solves to NA to signal the failed solve. The parameter h will now contain the handles of the failed solvers for later analysis.
Alternatively, we could have used the function handlestatus and collect the solution which is stored in a GDX file. For
example we could write:
loop(pp$(handlestatus(h(pp))=2),
minvar.handle = h(pp);
execute_loadhandle minvar;
xres(i,pp) = x.l(i);
report(pp,i,inc) = xi.l(i);
report(pp,i,dec) = xd.l(i) );
The function handlestatus interrogates the solution process and returns '2' if the solution process has been completed and the
results can be retrieved. The solution is stored in a GDX file which can be loaded in a way similar to other gdx solution
points. First we need to tell GAMS what solution to retrieve by setting the minvar.handle to the appropriate value. Then we
can use execute loadhandle to load the solution for model minvar back into the GAMS data base. Using handlestatus
and loadhandle instead of the simpler handlecollect adds one more layer of control to the final collection loop. We now
need one additional if statement inside the above collection loop:
Repeat
loop(pp$h(pp),
if(handlestatus(h(pp))=2,
minvar.handle = h(pp);
execute_loadhandle minvar;
xres(i,pp) = x.l(i);
report(pp,i,inc) = xi.l(i);
report(pp,i,dec) = xd.l(i);
display$handledelete(h(pp)) trouble deleting handles ;
346 The Grid and Multi-Threading Solve Facility
h(pp) = 0 ) ) ;
display$sleep(card(h)*0.2) sleep some time;
until card(h) = 0 or timeelapsed > 100;
xres(i,pp)$h(pp) = na;
Now we are ready to run the modified model. The execution log will contain some new information that may be useful on
more advanced applications:
--- LOOPS pp = p1
--- 46 rows 37 columns 119 non-zeroes
--- 311 nl-code 7 nl-non-zeroes
--- 14 discrete-columns
--- Submitting model minvar with handle grid137000002
--- Executing after solve
...
--- GDXin=C:\answerv5\gams_srcdev\225j\grid137000003\gmsgrid.gdx
--- Removing handle grid137000003
The log will now contain some additional information about the submission, retrieval and removal of the solution instance. In
the following sections we will make use of this additional information. You can find a complete example of a grid enabled
transport model in the GAMS Model Library.
At a final note, we have made no assumptions about what kind of solvers and what kind of computing environment we will
operate. The above example is completely platform and solver independent and it runs on your Windows laptop or on a
massive grid network like the Condor system without any changes in the GAMS source code.
minvar.handle = h(pp);
execute_loadhandle minvar;
status(pp,solvestat) = minvar.solvestat;
status(pp,modelstat) = minvar.modelstat;
status(pp,seconds) = minvar.resusd;
else
handle := Waiting );
status(pp,status) = handle );
display status;
To run the above program we will restart from the previous save file by using the restart or r parameter.
> gams qcheck r=submit gdir=c:\test\grid
The output may then look like:
You may want to do some more detailed analysis on one of the solved model instances. Then we may have a qanalyze.gms
program that may look like and be called using the double dash option, which sets a GAMS environment variable:
loop(pp$handlestatus(h(pp)),
minvar.handle = h(pp);
execute_loadhandle minvar;
xres(i,pp) = x.l(i);
report(pp,i,inc) = xi.l(i);
report(pp,i,dec) = xd.l(i);
display$handledelete(h(pp)) trouble deleting handles ;
h(pp) = 0 );
xres(i,pp)$h(pp) = na;
. . .
We would restart the above program from the save file that was created by the submitting job like:
> gams qreport r=submit gdir=c:\test\grid
Note that it would not be necessary to run the job out of the same directory we did the initial submission. We don't even have
to run the same operating system.
348 The Grid and Multi-Threading Solve Facility
The instantiated (generated) models and their corresponding solution are kept in unique directories, reachable from your
submitting system. Each GAMS job can have only one Grid Directory. By default, the grid directory is assumed to be the
scratch directory. This can be overwritten by using the GAMS parameter GridDir, or short GDir. For example:
> gams myprogram ... GDir=gridpath
If gridpath is not a fully qualified name, the name will be completed using the current directory. If the grid path does not
exist, an error will be issued and the GAMSjob will be terminated. A related GAMS parameter is the ScrDir (SDir for short).
Recall the following default mechanism:
When a GAMS job starts, a unique process directory is created in the current (job submitting), directory. These directories
are named 225a to 225z. When a GAMS job terminates it will remove the process directory at the completion of a GAMS
job. Any file that has not been created by the GAMS core system will be flagged.
Using the program gamskeep instead of gams will call another exit script which (the default script) will do nothing and the
process directory will not be removed.
If we do not specify a scratch directory, the scratch directory will be the same as the process directory. If we do not specify a
grid directory, the grid directory will be the same as the scratch directory.
350 The Grid and Multi-Threading Solve Facility
If there is a danger that some of the model instances may fail or we want to break the GAMS program into several pieces to
run as separate jobs, we need to be careful not to remove the model instance we have not completely processed. In such
cases, we have to use the GridDir option in order to be able to access previously created model instances.
1. Create a subdirectory in the GridDir with the name gridnnn. Where nnn stands for the numeric value of the handle. The
handle value is the internal symbol ID number x 1e6 + the model instance number. For example, in the [QMEANVAR]
example the first grid subdirectory was grid137000002.
2. Remove the completion signal in case the file already exists. Currently the signal is a file called finished. For example,
grid137000002/finished.
3. Create or replace a gdx file called gmsgrid.gdx which will contain a dummy solution with failed model and solver status.
This file will be overwritten by the final step of the solution process and will be read when calling execute loadhandle.
4. Place all standard GAMSsolver interface files into the above instance directory.
5. Execute the submission wrapper called gmsgrid.cmd under Windows or gmsgrid.run under Unix. These submission
scripts are usually located in the GAMSsystem directory but are found via the current path if not found in the
GAMSsystem directory.
The grid submission script gmsgrid.cmd or gmsgrid.run is called with three arguments needed to make a standard
GAMSsolver call:
The submission script then does the final submission to the operating system. This final script will perform the following
steps:
If we want to use the function handlesubmit() we also have to create the gmsrerun.cmd or gmsrerun.run script which could
later be used to resubmit the job.
For example, the default submission script for Windows is shown below:
@echo off
: gams grid submission script
:
: arg1 solver executable
: 2 control file
7 Multi-Threading 351
: 3 scratch directory
:
: gmscr_nx.exe processes the solution and produces gmsgrid.gdx
:
: note: %3 will be the short name because START cannot
: handle spaces and/or "...". We could use the original
: and use %~s3 which will strip ".." and makes the name :
: short
: gmsrerun.cmd will resubmit runit.cmd
echo @echo off > %3runit.cmd
echo %1 %2 >> %3runit.cmd
echo gmscr_nx.exe %2 >> %3runit.cmd
echo echo OK ^> %3finished >> %3runit.cmd
echo exit >> %3runit.cmd
echo @start /b %3runit.cmd ^> nul > %3gmsrerun.cmd
start /b %3runit.cmd > nul
exit
7 Multi-Threading
Note: This feature is in beta status.
As described above, using the Grid facility, each solve is handled in its own process space. When setting the SolveLink
option (or model attribute) to 6 instead (compile time constant %solveLink.Async Threads%) a separate thread is used, which
allows efficient in-memory communication between GAMS and the solver (like it is done with SolveLink = %solveLink.Load
Library% =5). Other than that, the multi-threading facility works in the same way as the Grid facility: After a solve statement,
which generates the model and passes it to the solver in a separate thread, one can store a handle of the model instance (using
the model attribute mymodel.handle) and use the same functions that are used for the Grid Facility to collect the solution and
deal with the model instance: HandleCollect, HandleDelete, HandleStatus, and ReadyCollect.
The option ThreadsAsync (available on the command line and with the option statement) sets the maximum number of
threads that should be used for the asynchronous solves.
The following matrix shows which solvers can be used with SolveLink = 6 on which platform:
Solver x86 32bit x86 64bit x86 64bit x86 64bit x86 64bit Sparc 64bit IBM Power
MS MS Linux Mac OS X SOLARIS SOLARIS 64bit
Windows Windows AIX
GUROBI
SCIP
SNOPT
XPRESS
MOSEK
CONOPTD
CPLEXD
352 The Grid and Multi-Threading Solve Facility
Solver x86 32bit x86 64bit x86 64bit x86 64bit x86 64bit Sparc 64bit IBM Power
MS MS Linux Mac OS X SOLARIS SOLARIS 64bit
Windows Windows AIX
OsiCplex
OsiGurobi
If a solver is selected for which SolveLink = 6 is not supported on the corresponding platform, SolveLink = 3 will be used
instead (which is noted in the log).
Extrinsic Functions
1 Introduction
Functions play an important role in the GAMS language, especially for non-linear models. Similarly 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 ( Functions ) provides the means for managing that trade-off. In this Appendix the extrinsic
function libraries that are included in the GAMS distribution are described. In addition, we provide some pointers for users
wishing to build their own extrinsic function library.
In the tables that follow, the Endogenous Classification (second column) specifies in which models the function can legally
appear with endogenous (non-constant) arguments. In order of least to most restrictive, the choices are any, NLP, DNLP or
none.
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.
2 Fitpack Library
FITPACK by Paul Dierckx 1 is a FORTRAN based library for one and two dimensional spline interpolation. This library has
been repackaged to work with the GAMS Function Library Facility. As it can be seen in the GAMS Test Library model
fitlib01 the function data needs to be stored in a GDX file fit.gdxcontaining a three dimensional parameter fitdata.
The first argument of that parameter contains the function index, the second argument is the index of the supporting point and
the last one needs to be one of w(weight), x(x-value), y(y-value) or z (z-value).
Table 1: Fitpack functions
The function FitParamcan be used to change certain parameters used for the evaluation:
FuncInd sets the function index. SegInd defines the index of the segment (or interval) which is decribed here. LeftBound
gives the lower bound of the segment. The upper bound is the lower bound on the next row, or infinity if this is the last
segment. CoefX defines the Xth degree coefficient of the polynomial corresponding to this segment.
This library is made available by the following directive:
4 Stochastic Library
The stochastic library provides random deviates, probability density functions, cumulative density functions and inverse
cumulative density functions for certain distributions. This library is made available by the following directive:
Function Description
SetSeed(SEED) defines the seed for random number generator
Continous distributions
Function Description
beta(SHAPE 1,SHAPE 2) Beta distribution with shape parameters SHAPE 1 and SHAPE 2, see MathWorld
cauchy(LOCATION,SCALE) Cauchy distribution with location parameter LOCATION and scale parameter SCALE,
see MathWorld
ChiSquare(DF) Chi-squared distribution with degrees of freedom DF, see MathWorld
exponential(LAMBDA) Exponential distribution with rate of changes LAMBDA, see MathWorld
f(DF 1,DF 2) F-distribution with degrees of freedom DF 1 and DF 2, see MathWorld
gamma(SHAPE,SCALE) Gamma distribution with shape parameter SHAPE and scale parameter SCALE, see
MathWorld
gumbel(LOCATION,SCALE) Gumbel distribution with location parameter LOCATION and scale parameter
SCALE, see MathWorld
invGaussian(MEAN,SHAPE) Inverse Gaussian distribution with mean MEAN and scaling parameter SHAPE, see
MathWorld
laplace(MEAN,SCALE) Laplace distribution with mean MEAN and scale parameter SCALE, see MathWorld
logistic(LOCATION,SCALE) Logistic distribution with location parameter LOCATION and scale parameter
SCALE, see MathWorld
logNormal(LOCATION,SCALE) Log Normal distribution with location parameter LOCATION and scale parameter
SCALE, see MathWorld
normal(MEAN,STD DEV) Normal distribution with mean MEAN and standard deviation STD DEV, see
MathWorld
pareto(SCALE,SHAPE) Pareto distribution with scaling parameter SCALE and shape parameter SHAPE, see
MathWorld
rayleigh(SIGMA) Rayleigh distribution with parameter SIGMA, see MathWorld
studentT(DF) Student's t-distribution with degrees of freedom DF, see MathWorld
triangular(LOW,MID,HIGH) Triangular distribution between LOW and HIGH, MID is the most probable number,
see MathWorld
uniform(LOW,HIGH) Uniform distribution between LOW and HIGH, see MathWorld
weibull(SHAPE,SCALE) Weibull distribution with shape parameter SHAPE and scaling parameter SCALE,
see MathWorld
Discrete distributions
Function Description
binomial(N,P) Binomial distribution with number of trials N and success probability P in each
trial, see MathWorld
geometric(P) Geometric distribution with success probability P in each trial, see MathWorld
356 Extrinsic Functions
Function Description
hyperGeo(TOTAL,GOOD,TRIALS) Hypergeometric distribution with total number of elements TOTAL, number of
good elements GOOD and number of trials TRIALS, see MathWorld
logarithmic(P-FACTOR) Logarithmic distribution with parameter P-FACTOR, also called log-series distri-
bution, see MathWorld
negBinomial(FAILURES,P) Negative Binomial distribution with the number of failures until the experiment is
stopped FAILURES and success probability P in each trial. The generated random
number describes the number of successes until we reached the defined number of
failures, see MathWorld
poisson(LAMBDA) Poisson distribution with mean LAMBDA, see MathWorld
uniformInt(LOW,HIGH) Integer Uniform distribution between LOW and HIGH, see MathWorld
For each distribution in table Table 3, the library offers four functions in Table 4:
Table 4: Distribution functions
The function d<DistributionName> needs the arguments described in table Table 4. The other functions get an additional
argument at the first position: The point to evaluate. This parameter can be an endogenous variable. The following table
shows all fours functions for the Normal distribution:
Table 5: Normal distribution functions
The function sampleLS<DistributionName> creates a sample of the specified distribution according to the distribution
parameters and returns a HANDLE that references the sample as illustrated in the example down below. The Parameter
SAMSIZE must be specified and describes the size of the sample while VARRED is optional and provides the possibility to
define a variance reduction method (0=none, 1=Latin Hyper Square, 2=Antithetic). If omitted Latin Hyper Square Sampling
is used.
Table 6:LINDO sampling functions
5 LINDO Sampling Library 357
Function Description
getSampleValues(HANDLE) Retrieve sampling.
induceCorrelation(CORTYPE) Induce correlation that has to be set with
setCorrelationbefore.CORTYPEdescribes the correlation type
and must be one of 0 (PEARSON), 1 (KENDALL) or 2 (SPEARMAN).
setCorrelation(SAMPLE1,SAMPLE2,COR) Define correlation between two samplings.
setSeed(SEED) Define the seed for random number generator.
setRNG(RNG) Define the random number generator to use, possible values are -1
(FREE), 0 (SYSTEM), 1 (LINDO1), 2 (LINDO2), 3 (LIN1), 4 (MULT1),
5 (MULT2) and 6 (MERSENNE).
Continuous distributions
Function Description
beta(SHAPE 1,SHAPE 2,SAMSIZE[,VARRED]) Beta distribution specified by two shape parameters.
cauchy(LOCATION,SCALE,SAMSIZE[,VARRED]) Cauchy distribution specified by location and scale parameter.
chisquare(DF,SAMSIZE[,VARRED]) Chi-Squared distribution specified by degrees of freedom.
exponential(RATE,SAMSIZE[,VARRED]) Exponential distribution specified by rate of change.
f(DF 1,DF 2,SAMSIZE[,VARRED]) F distribution specified by degrees of freedom.
Note that sampleLSgamma uses another version of the F dis-
tribution than dF from the Stochastic Library.
gamma(SHAPE,SCALE,SAMSIZE[,VARRED]) Gamma distribution specified by shape and scale parameter.
Note that the use of sampleLSgamma(A,B) is equivalent to the
use of dGamma(B,A) from the Stochastic Library.
gumbel(LOCATION,SCALE,SAMSIZE[,VARRED]) Gumbel distribution specified by location and scale parameter.
laplace(LOCATION,SCALE,SAMSIZE[,VARRED]) Laplace distribution specified by location and scale parameter.
logistic(LOCATION,SCALE,SAMSIZE[,VARRED]) Logistic distribution specified by location and scale parameter.
lognormal(LOCATION,SCALE,SAMSIZE[,VARRED]) Log Normal distribution specified by location and scale param-
eter.
normal(MEAN,STD DEV,SAMSIZE[,VARRED]) Normal distribution specified by given mean and standard
deviation.
pareto(SCALE,SHAPE,SAMSIZE[,VARRED]) Pareto distribution specified by shape and scale parameter.
studentt(DF,SAMSIZE[,VARRED]) Student's t-distribution specified by degrees of freedom.
triangular(LOW,MID,HIGH,SAMSIZE[,VARRED]) Triangular distribution specified by lower and upper limit and
mid value.
uniform(LOW,HIGH,SAMSIZE[,VARRED]) Uniform distribution specified by the given bounds.
weibull(SCALE,SHAPE,SAMSIZE[,VARRED]) Weibull distribution specified by scale and shape parameter.
Note that the use of sampleLSweibull(A,B) is equivalent to the
use of dWeibull(B,A) from the Stochastic Library .
Discrete distributions
Function Description
binomial(N,P,SAMSIZE[,VARRED]) Binomial distribution specified by number of trials Nand
success probability Pin each trial.
hypergeo(TOTAL,GOOD,TRIALS,SAMSIZE[,VARRED]) Hypergeometric distribution specified by total number of
elements, number of good elements and number of trials.
358 Extrinsic Functions
Function Description
logarithmic(P-FACTOR,SAMSIZE[,VARRED]) Logarithmic distribution specified by P-Factor.
Note that sampleLSlogarithmic uses another version of the
logarithmic distribution than dLogarithmic from the Stochas-
tic Library.
negbinomial(SUCC,P,SAMSIZE[,VARRED]) Negative Binomial distribution specified by the number of
successes and the probability of success. The generated
random number describes the number of failures until we
reached the defined number of successes.
Note that the use of sampleLSnegbinomial(R,P) is equiva-
lent to the use of dNegBinomial(R,P-1) from the Stochastic
Library .
poisson(MEAN,SAMSIZE[,VARRED]) Poisson distribution specified by mean.
The following example illustrates the use of the sample generator and shows how the commands setCorrelation and
induceCorrelation work:
scalar d,h,k;
h = normalSample(5,2,12);
k = normalSample(5,2,12);
set i /i01*i12/;
parameter sv(i);
loop(i,
sv(i) = getSampleVal(k);
);
display sv;
loop(i,
sv(i) = getSampleVal(h);
);
display sv;
d=setCor(h,k,-1);
d=indCor(1);
loop(i,
sv(i) = getSampleVal(k);
);
display sv;
loop(i,
sv(i) = getSampleVal(h);
);
display sv;
The resulting output shows that the values of sv are restructured according to the desired correlation:
---- 18 PARAMETER sv
6 Build Your Own: Trigonometric Library Example 359
i01 7.610, i02 5.710, i03 3.755, i04 5.306, i05 2.382, i06 2.174
i07 6.537, i08 4.975, i09 8.260, i10 3.067, i11 6.216, i12 4.349
---- 22 PARAMETER sv
i01 7.610, i02 5.710, i03 3.755, i04 5.306, i05 2.382, i06 2.174
i07 6.537, i08 4.975, i09 8.260, i10 3.067, i11 6.216, i12 4.349
---- 28 PARAMETER sv
i01 2.382, i02 4.349, i03 6.216, i04 4.975, i05 7.610, i06 8.260
i07 3.067, i08 5.306, i09 2.174, i10 6.537, i11 3.755, i12 5.710
---- 32 PARAMETER sv
i01 7.610, i02 5.710, i03 3.755, i04 5.306, i05 2.382, i06 2.174
i07 6.537, i08 4.975, i09 8.260, i10 3.067, i11 6.216, i12 4.349
The C implementation of this extrinsic function library can be found in the files tricclib.c and tricclibql.c. Together
with the API specification file extrfunc.h, these files document the callbacks that need to implemented by a GAMS
extrinsic function library.
Note that the file tricclibql.c, which implements the querylibrary callback, has been generated by the Python helper
script ql.py. The purpose of the querylibrary callback is to provide information about the library itself and the extrinsic
functions it implements to the GAMS execution system. For example, the information that the cosine function has an
endogenous required first argument and an exogenous optional second argument is available from the querylibrary callback.
The ql.py file that generated the file tricclibql.c (and also the Delphi and Fortran90 equivalents tridclibql.inc and
triifortlibql.f90) does so by processing the specification file tri.spec. See the comments in this file for info on how
to write such a specification. The ql.py script is invoked by executing ./ql.py tri.spec from the shell.
When implementing a function in a library this function needs to return the function value of the input point. Furthermore,
the solver might need derivative information at the input point. Therefore, the implementation of the function needs to be
able to return gradient and Hessian values. This can sometimes be inconvenient. GAMS can use the function values at points
close to the input point to estimate the gradient and Hessian values using finite differences. However, this is not as accurate
as analytic derivatives and requires a number of function evaluations, so the convenience comes at a price. The attribute
MaxDerivative in the specification of a function signals GAMS the highest derivatives this function will provide. For
360 Extrinsic Functions
higher order derivatives GAMS will use finite differences to approximate the derivative values.
7 Build Your Own: Reading the GAMS Parameter File in your Library
This library serves as an example of how to code and build an extrinsic function library that reads the information from the
GAMS parameter file. The library is included in the GAMS distribution in binary form and also as source code written
in C, that comes along with the GAMS Test Library model [parlib01]. Table Table 8 lists the extrinsic functions that are
implemented by the libraries.
Table 8: GAMS Parameter File reading
The C implementation of this extrinsic function library can be found in the files parcclib.c and parcclibql.c. Together
with the API specification file extrfunc.h. The reading of the GAMS Parameter file is done in the function LibInit.
8 CPP Library
This library serves both as an example of how to use C++ to obtain gradients and Hessians for free'' and as a source
of functions based on the multivariate normal distribution. The library is available in compiled form and as C++ source.
Test Library model cpplib00 exercises the process of building a shared library from C++ source and doing some basic
tests, while models [cpplib01] through [cpplib05] are more thorough tests for the CPP library extrinsics shipped with the
distribution. These functions are listed and described in Table Table 9.
Table 9: CPP Library functions
pdfNormal and cdfNormal functions from the stochastic extrinsic library LINDO Sampling Library . For the multivariate
cases, we based our implementation on the TVPACK from Alan Genz 2 , with modifications to allow for proper computation
of derivatives. Again, the number of arguments allowed is a consideration, so we chose to implement functions taking
correlation coefficients as arguments, not a covariance matrix. The conversion from the latter case to the former is relatively
straightforward. Here we describe it with some R code, making use of the mnormt package that computes the multivariate
CDF using similar code from Genz:
For the bivariate case, there is one correlation coefficient, r. The CDF implementation is not quite accurate to machine
precision, having 14 or 15 digits of accuracy. The trivariate case includes 3 correlation coefficients, the 3 off-diagonal
elements from the lower triange of R above. The accuracy of the CDF depends on the inputs: it is higher when the correlation
is nearly zero and poorer as the condition number of R increases. Typically, an accuracy of 1011 is all that can be achieved.
In both multivariate cases, you should avoid evaluating at or near points where the correlation matrix is degenerate. At nearly
degenerate points, the accuracy of the distribution and density functions suffers, and when the correlation matrix becomes
degenerate the distribution becomes so also.
An example of a data statement where we use a external function to set a variable level: x1.l=sqr(integralx(0,2));
Debugging support: support for numerical gradient and hessian
user provided: integralx.grad(2:0,2) vs. numerically provided by GAMS: integralx.gradn(2:0,2)
The user can not provide a solver with Hessian information for external equations, however, many solvers can solve
without Hessian information, for example,by approximating the Hessian.
Additional notes:
CONOPT verifies by a numerical estimation of the derivatives that the user has provided reasonable derivative
information (a unreasonable derivative results in Fatal error).
Global solvers ( ANTIGONE, BARON, Couenne, LindoGlobal, SCIP) analyze the algebra and can therefore not
handle extrinsic functions or external equations.
Examples of use:
Extrinsic functions can be used for special purposes, see Fitpack, Piecewise Polynomial, Stochastic Library, LINDO
Sampling, Trigonometric libraries in the GAMS user's guide
External equation provides a unrestricted way to solve custom equations and equation systems, for example, a partial
differential equation system.
External Equations
Although GAMS provides a powerful language for manipulating data and defining highly structured collections of variables
and equations, there are times when you would like to define some parts of your model using a more traditional programming
language such as Fortran or C.
This document describes a facility for connecting code written in Fortran, C, Java, Delphi, or some other programming
language to equations and variables in a GAMS model. We will refer to these GAMS equations as external equations and the
compiled version of the programming routines as the external module defining the external functions (Note that external
functions are something completely different than GAMS extrinsic functions, see e.g. a side-by-side comparison). The form
of the external module will depend on the operating system being used. The external module under Windows 95/98/NT is a
Dynamic Link Library (.dll), and the external module under Unix is a shared object (.so). In principle, any language or
system can be used to build the DLL or shared object defining the external module, as long as the interface conventions are
not changed.
The basic mechanism is to declare all the equations and variables using the normal GAMS syntax. The interpretation of the
external equations is done in a special way. Instead of the usual semantic content, the external equations specify the mapping
between the equation and variable names used in GAMS and the function and variable indices used in the external module.
This mapping is described in the section on the GAMS interface.
The external module can be written in C, Fortran or most other programming languages. The next sections describe the
general definitions for an external module for C, Delphi, and Fortran from a programming language perspective. The way
the program is compiled and converted into an external module is system and compiler specific. A set of scripts for various
systems and compilers is available together with some examples consisting of GAMS models and C, Delphi, Java, and
Fortran files implementing the external functions.
The external equation interface is not intended as a way to bypass some of the very useful model checking done by GAMS
when external equations are used with an NLP solver. The external equations a re still assumed to be continuous with
accurate and smooth first derivatives. The continuity assumption implies that the external functions must have very low noise
levels, considerably below the feasibility tolerance used by the solver. The assumption about accurate derivatives implies that
derivatives must be computed more accurately than can be done with standard finite differences. If these assumptions are not
satisfied then there is no guarantee that the NLP solver can find a solution that has the mathematical properties of a local
optimum, i.e. that satisfies the Karush-Kuhn-Tucker conditions within the standard tolerances used by the solver.
1 GAMS Interfaces
In order to link an external module to a GAMS model you must specify some mappings. The external functions are assumed
to be defined in terms of indices i = 1..m. These indices must be mapped to GAMS equation names. Similarly, the
variables used inside the external functions are assumed to be defined in terms of indices j = 1..n. These indices must be
mapped to GAMS variable names. Finally, the name of the external module must be specified.
All GAMS solvers are designed for large models and they rely on sparsity in large models. The last part of the specification
of a set of external equations is therefore the sparsity pattern of the external functions, i.e. which variables appear in which
364 External Equations
functions.
The external equations used to specify the interface to the external module are declared in GAMS just like any other equations.
For example:
The definition starts out like any other equation, for example:
The difference appears after the ... This part is no longer the algebra for the equation, but rather information that maps
each row of the external equation to an index in the external function. An external equation is recognized as external by the
equation type "=X=" instead of the usual GAMS equation types "=E=", "=L=" or "=G=". The value of the constant term
of the external equation must be an integer constant. The value of the constant maps the row of the GAMS equation to the
index (in 1..m) of the external functions. Several blocks of GAMS equations can be mapped to external functions using
the =X= notation and external equations can be defined over domains that are restricted by dollar conditions just like any
other equations. The mapping between GAMS external equations and external function indices must be one-to-one and the
external function indices must be contiguous from one to m (the total number of external functions). This means that two
GAMS rows cannot be mapped into the same external function index, and that there can be no holes in the list of external
function indices. Although there can be any number of blocks of GAMS external equations, they must all map into and be
implemented by one single external function exported by the external module.
The variable part of each external equation defines both the sparsity pattern of the external equation and the mapping from
GAMS variable names to the indices of the external variables. The variable part must be a sum of terms where each term is
an integer times a variable. The existence of the term indicates that the variable involved is used in the external function and
that there is a corresponding derivative. The value of the coefficient defines the index of the external variable (in 1...n)
that the GAMS variable is mapped into. For example, the term 5 Y indicates that the external equation depends on GAMS
variable Y and that Y is mapped to the 5th element in the vector of external variables. Clearly, if a variable appears in more
than one row of an external equation or equations, then the value of its coefficient must be the same in each case.
Several blocks of GAMS variables can be used in the external equations. In contrast to equations, where all rows in an
equation block are either external or not, some columns in a variable block can be external while others are not. The
mapping between GAMS variables and external variable indices must be one-to-one and the external variable indices must be
contiguous from one to n (the total number of external variables). This means that two GAMS columns cannot be mapped
into the same external variable index, and that there can be no holes in the list of external variable indices. Although there can
be any number of blocks of GAMS variables mapped to external variables, they must all map into one single vector passed to
one subroutine in the external module. Inside the module you can of course split the vector of variables any way you like.
Note that while some GAMS variables are external, there is no syntax provided to specify this explicitly, in contrast to the
=X= notation use for external equations. External variables can and will be used in normal GAMS equations as well as
external equations. Indeed, without this capability the model would be separable and the external equations/functions would
be of little use.
The actual functions/equations hidden behind these indexing schemes are always interpreted as equality constraints with zero
right hand sides. Inequalities must be converted to equalities by adding explicit slack variables, both in the GAMS model and
in the external functions, and the explicit slack must be one of the external variables. A nonzero right hand side has to be
taken care of in the external function definition.
The name of the external module in which the external functions are implemented can be defined in a number of ways. By
default, the external module is assumed to have the same name as the GAMS model with an extension that is operating
systems dependent. The extension is DLL (dynamic Link library) for Windows 95/98/NT and so (shared object) or sl (shared
library) for Unix, and it is assumed to be located in the directory from which GAMS is called.
If you would like to use a different name for the external module or if you would like to add a path, use the GAMS FILE
statement to define the name of the external file and include the file name as an extra item in the model list. If the file name
does not have an extension, a system-dependent extension mentioned above will be added. This is useful when the GAMS
model is moved between operating systems. The file name can be used in a model statement, either as an additional item in
the list of equation names, or using the syntax /ALL, Filename/.
Since the coefficients and right hand sides in the GAMS definition of the external equations are interpreted as indices, you
2 The Programming Interface 365
are not allowed to scale the external equations and variables. Also, since the external equations are treated in a special way,
the HOLDFIXED option will not remove any external variables, even if some of them are fixed.
C:
Delphi:
uses
geheader;
GE API is a DLL import/export indicator defined in the header file geheader.h; set -DGE EXPORTS when building the DLL
on a PC to have the DLL export gefunc. GE CALLCONV indicates the calling convention that should be used. Currently, this
is defined to be stdcall on a PC. It is possible to build the DLL using a different calling convention as long as GE CALLCONV
is used for the exported symbol gefunc. There is not such a clean way to specify these things in the Fortran code. When
using Watcom Fortran, an auxiliary pragma is used (see geheader.inc), while this can be done via an ATTRIBUTES directive
inside the definition of GEFUNC in the case of Visual Fortran.
When building on a Unix machine, both GE API and GE CALLCONV are empty.
The icntr vector is a control vector used to pack and communicate control information between the solver and the
external module. Some utility functions for handling icntr and the names I are defined in the appropriate header file
(Fortran: geheader.inc, Delphi: geheader.pas, C: geheader.h). In the following we use square brackets []. Fortran
programmers should replace the square brackets with round parenthesis (). The icntr-elements that the implementor of
GEFUNC should be concerned with in this initial version of the interface are defined below. The icntr vector is a control vector
used to pack and communicate control information between the solver and the external module. Some utility functions for
handling icntr and the names I are defined in the appropriate header file (Fortran: geheader.inc, Delphi: geheader.pas,
C: geheader.h). In the following we use square brackets []. Fortran programmers should replace the square brackets with
round parenthesis (). The icntr-elements that the implementor of GEFUNC should be concerned with in this initial version of
the interface are defined below.
Element Description
icntr[I Length] Holds the length of icntr in number of elements. Is defined by the solver and should usually not be
used by the implementor.
icntr[I Neq] Number of external equation rows seen in the GAMS model. Is defined by the solver.
icntr[I Nvar] Number of external variables seen in the GAMS model. Is defined by the solver.
icntr[I Nz] Number of nonzero derivatives or Jacobian elements seen in the GAMS model. Is defined by the
solver.
366 External Equations
Element Description
icntr[I Mode] Mode of operation defined by the solver as follows:
1. Initialize. This will be the first call of GEFUNC, where the implementor can perform all
initializations needed by the external module.
2. Terminate. This will be the last call of GEFUNC, where the implementor can perform all cleanup
tasks needed by the external module.
3.Function evaluation mode. This is the standard mode, where GEFUNC will be called repeatedly
during the actual optimization.
Additional mode values may be added later if the functionality of the interface is extended.
icntr[I Eqno] Index for the external function. icntr[I Eqno] is defined by the solver, but only in function
evaluation mode, i.e. if icntr[I Mode]=3. icntr[I Eqno] holds the index of the external
function to be evaluated during this call to GEFUNC. icntr[I Eqno] will be between 1 and
icntr[I Neq], inclusive. Note that the external function interface only allows you to communicate
information about one function at a time.
icntr[I Dofunc] 0-1 Flag for function evaluation. Dofunc is defined by the solver, but only in function evaluation
mode, i.e. if icntr[I Mode]=3. When icntr[I Dofunc] is 1 then GEFUNC must return the
numerical value of the function indexed by icntr[I Eqno] in the scalar f.
icntr[I Dodrv] 0-1 Flag for derivative evaluation. icntr[I Dodrv] is defined by the solver, but only in function
evaluation mode, i.e. if icntr[I Mode] = 3. When icntr[I Dodrv] is 1 then GEFUNC must
return the numerical value of the derivatives of the function indexed by icntr[I Eqno] in the
vector d.
icntr[I Newpt] 0-1 Flag for new point. icntr[I Newpt] is defined by the solver, but only in function evaluation
mode, i.e. if icntr[I Mode] = 3. When icntr[I Newpt] is 1 then the point x will be different
from last call of GEFUNC. When icntr[I Newpt] is 0 then x will not have changed since the
last call.
icntr[I Debug] If icntr[I Debug] is set to a nonzero value by the implementor then function GEstat and GElog
will write all strings to a file called debugext.txt and flush the buffer immediately after writing. The
string debugger can be used when a shared object crashes before the solver has had an opportunity
to display the messages. In Fortran the string debugger will use Fortran unit icntr[I Debug].
x Evaluation point. x is a vector with icntr[I Nvar] elements. It is defined by the solver if
GEFUNC is called in function evaluation mode, i.e. if icntr[I Mode] = 3. The individual
elements of x will always be between the bounds defined in the GAMS model. During initialization
and termination calls, x will not be defined and you should not reference x. C programmers should
index this array starting at zero, i.e. the first external variable is referenced as x[0].
f Function value: If icntr[I Mode] = 3 and icntr[I Dofunc] = 1 then the external module must
return the value of external function icntr[I Eqno] in the scalar f. During initialization and
termination calls, f must not be defined.
d Derivative values: If icntr[I Mode] = 3 and icntr[I Dodrv] = 1 then the external module must
return the values of the derivatives of external function icntr[I Eqno] with respect to all variables
in the vector D. The derivative with respect to variable x[i] is returned in d[i]. It is sufficient to
define positions in d that correspond to variables actually appearing in equation icntr[I Eqno].
Other positions are not being used by the solver and can be left undefined. During initialization and
termination calls, d must not be defined.
The msgcb argument to GEFUNC is the address of a message callback routine that can be used to send messages back to the
status and log files of the GAMS process. Its type is defined as follows:
typedef void (GE CALLCONV * msgcb t)
(const int *mode, const int *nchars, const char *buf, int len);
The mode argument is the logical or of the two flags LOGFILE = 1 and STAFILE = 2 defined in geheader.h and used to
direct messages to the log and status files, respectively. nchars is the number of bytes contained in the message (exclusive
of the null terminator if there is one present), buf is the address of the message, and len is the size or length of the string
buf. The len argument is not used but is included because it makes using this callback from Fortran much easier. GEFUNC
must return a status code using the following definition:
3 Compiling and Linking 367
After this description of the appearance of the function GEFUNC, some practical comments about implementing GEFUNC
are appropriate.
4 Initialization Mode
The initialization mode should always check whether the model has the expected size, i.e. icntr[I Neq], icntr[I Nvar],
and icntr[I NZ] should be tested against fixed expected values or values derived from some external data set.
The initialization mode can be used for a number of purposes such as allocating memory and initializing numerical information
or mapping information needed by the function evaluations to follow. Data can be computed or read from external data
sources or it can be derived from calls to an external database. Data that is shared with GAMS can be written to a file from
GAMS using the Put statement and read in GEFUNC. Note that you must close the Put file using putclose before the Solve
statement. Also note that memory used to hold information from one invocation of GEFUNC to the next should be static. For
Fortran it should either be in a Common block or it should be included in a Save statement.
5 Termination Mode
The termination mode can be used to perform a number of clean-up tasks such as computing statistics, closing files, and
returning memory. The solver will terminate shortly after the termination call and a simple implementation may rely of the
operating system to close open files and return dynamic memory. However, it is a good habit to perform these tasks explicitly.
Sometimes external modules behave different from normal programs.
6 Evaluation Mode
The bulk of the computational work will usually be in evaluation mode. It is important to recognize that GEFUNC only
works with one equation at a time. One of the reasons for this choice is that the addressing of derivatives becomes very
simple: there is one derivative for each variable and they have the same index in d and x, respectively.
In some applications several functions are naturally computed together, for example because all functions are computed
in some joint integration routine. The Newpt flag is included for these applications. Whenever icntr[I Newpt] is 1,
compute all functions using the common routines, save all function and derivative values, and return the function and/or
derivatives values corresponding to equation Eqno. When GEFUNC is called next, icntr[I Newpt] is most likely 0 and
368 External Equations
the function and derivative values can be extracted from the information computed (and saved) during the last call where
icntr[I Newpt] was 1.
7 Evaluation Errors
It is good modeling practice to add bounds to the variables in such a way that all nonlinear functions are defined for all
values of the variables within the bounds. Most solvers will also guarantee that nonlinear functions only are called when all
elements of the x-vector are between the bounds. However, it may not be practical to add all the necessary bounds, and the
implementor of GEFUNC should therefore program the evaluation routine in such a way that division by zero, taking the
logarithm of non-positive numbers, overflow in exponentiation and other exceptions are captured. GEFUNC should simply
return the value 1 to let the solver know that the function could not be computed at the current point. The solver will not use
the function and/or derivative value and it will in most cases be able to backtrack to a safe point and continue the optimization
from there.
You should be very careful when using system-default or user-defined function to handle evaluation errors (for example,
matherr()). It will not always work in the same way, or at all, inside a DLL or shared object as it does in a self-contained
program or a static library.
C:
Delphi:
10 GElog - Utility Routine for writing messages to the Log file 369
The first argument, icntr, is passed through from the first argument of GEFUNC. The content of 'line' is packed into the
control buffer as one line, and when GEFUNC returns, the content of the buffer is written to the GAMS status file. GEstat
can be called several times, each time with one line. 'Line' should not be longer than 132 characters and the overall amount
of information written in one call to GEFUNC should not exceed 1000 characters. 'Line' should not contain any special
characters such as new-line, tab, or null characters.
In practice, GEstat is often used with calls like the following:
Fortran:
C:
Delphi:
gestat(icntr, );
gestat(icntr,**** External module based on abc.dpr);
It should be mentioned that you cannot write directly to the GAMS status file since this file will be opened and controlled by
the Solver process.
C:
Delphi:
The content of 'line' is written to a buffer that in turn is written to the log file when GEFUNC returns. GElog behaves exactly
like GEstat, with Status file replaced by Log file.
It should be mentioned that you cannot write directly to the screen with some combinations of operating system and compiler;
this may also depend on the options or flags you use to build the external module. On some systems this may cause your
external module to crash. So, do not use writing to the screen as a method for debugging unless you know it works. Otherwise
you may continue to crash because of the debugging statements after all other errors have been removed. Write to a file and
flush the buffer as a safe alternative.
370 External Equations
character*(*) msgbuf
int nchars, charcount
nchars = charcount(msgbuf)
call MSGCB (mode, nchars, msgbuf)
Similar reasoning applies to the Visual Fortran compiler on the Intel platform, where instead of being placed at the end of the
argument list, the hidden length arguments are mixed into the argument list. Each character address is followed immediately
by the length (again, passed by value) of the character string. Since the only string passed in the example above is at the end
of the argument list, the code will work for Visual Fortran on Intel.
In the case of the Watcom Fortran compiler, the default mechanism for passing strings makes use of the string descriptor
(a structure consisting of a length and an address). The address of this string descriptor is what is passed. This makes it
necessary to use a more elaborate scheme to use the message callback from Watcom Fortran. In our examples, we illustrate
two techniques for handling this.
In the first example (see the files ex1f cb.for and watmsg c.c), we simply make a Fortran call to a C wrapper. The C wrapper
can use the address of the string descriptor passed to it from the Fortran routine to access the message buffer, and uses this to
call the message callback routine. In this case, we don't do any tricks or contortions in the Fortran code, but instead write C
code to accomodate the Fortran calling convention. Once we have the string in a C environment, it is clear how the callback
should be used.
In the second example (see the files ex1f cb.for and watmsg f.for), we don't introduce an additional layer with the C wrapper.
Instead, we use an auxiliary pragma to adjust the calling conventions used to make the call to msgcb from the Fortran
code. The auxiliary pragma forces the Watcom Fortran compiler to use the stdcall calling convention (this affects how the
parameters are passed). In addition, the pragma specifies, via a parm list, what is passed for each argument of the msgcb
function. In this case, we specify that the first two arguments (mode and nchars) be passed by reference (the default), the
message string be passed by data reference (only a pointer is passed), and the final len argument be passed by value.
FILE f / %gams.scrdir%filename /;
You should use the extension dat to ensure that GAMS will remove the file cleanly when it finishes. If another extension is
used and you don't delete the file, GAMS will complain about an unexpected file when it cleans up after the run. The external
function can get the name of the scratch directory from the solver during initialization. You set Icntr(I Getfil) = I scr
and return immediately. The solver will store the name and length of the scratch directory in the communication buffer, and
call the external function again, this time with a sub-mode, Icntr(I Smode) set to I Scr. You can then extract the name
using the Fortran call
13 Constant Derivatives 371
where Scrdir (declared as character255) will receive the scratch directory, and Scrlen (declared as integer) will receive the
actual length of Scrdir. In C, the call looks like
where the routine returns -1 on error, and the number or characters transferred to the buffer scratchDir on success. If there is
room, a terminating null byte is written to scratchDir. If the value returned is equal to sizeof(scratchDir), then the string
returned will not be null-terminated and may have been truncated as well.
You can get other directory or file names by setting Icntr(I Getfil) to the following values:
Value Description
I Scr Value used to request the scratch directory
I Wrk Value used to request the working directory
I Sys Value used to request the systems directory
I Cntr Value used to request the control file
After setting the Getfil flag you must always return immediately, and ncall, and the relevant call will be flagged with the
sub-mode in Icntr(I Smode).
The models ex5.gms and exmcp3.gms with their corresponding Fortran and C source files provide an example.
13 Constant Derivatives
Some solvers (the CONOPT solvers in particular) can take advantage of constant derivatives corresponding to linear terms.
This can be especially useful if an external function represents an equation like Y = expression(X), where Y is unbounded
and only appears in the objective function.
In the external module interface described above the solver cannot see that Y appears linearly. An optional extension allows
advanced users to indicate that some of the relationships are linear. During the setup call, the user must define
If the solver can use this information (not all solvers will) then GEFUNC will be called again with I Mode = 4 (or symbolic
constant DOCONSTDERIV in C), once for each equation defined in the usual way in I Eqno. The user must for each of these
calls define the values of the constant derivatives in the D-vector. The remaining elements of D, both those corresponding to
varying derivatives and to zeros, must be left untouched. These special calls will take place after the setup call and before the
first function evaluation call. In these calls other arguments such as I Dofunc, I Dodrv, and X will not be defined.
The model ex4x with the corresponding Fortran and C source files ex4xf cb.for and ex4xc cb.c shows an example of
how to use constant derivatives. The files can be compared to the corresponding files ex4f cb.for and ex4c cb.c without
constant derivatives.
Icntr[I_HVprod] = 1
If the solver can use this information (not all solvers will) then GEFUNC may be called with I Mode = 5 to request this
information. I Eqno will hold the equation number, and X will in its first I NVar positions hold the values of the variables,
372 External Equations
and in the next I Nvar positions will hold a vector V. The user should evaluate and return D = HV for the particular equation
in the particular point. D will be initialized to zero by the solver.
HV will often be needed for several vectors V in the same point X. I Newpt will be used to indicate changes in X in the usual
way.
The model ex1x with the corresponding Fortran source file shows how to use both constant derivatives and second derivatives.
15 Examples
There are several examples in the GAMS Test Library. The model [testexeq] gives an overview of the examples available
and can be used to compile and run these examples and a selection of those respectively. The Test Library model [complink]
can be used as a script to compile and link external equation libraries.
Regardless of how you build the external libraries, the different examples, e.g. [ex1] , will by default solve one model
using no external equations. To solve it with all kinds of different external equation libraries you can run the model with
"--runall=1". Alternatively, only selcted libraries will be used by setting one or more of the following flags: "--runC=1",
"--runC cb=1", "--runD=1", "--runD cb=1", "--runF=1", "--runF cb=1", "--runJ=1".
Option Description
Lkdebg Debug control: Controls how often the Function and Derivative debugger is called. The default value is -1
which means that is is called in the initial point. The value 0 will turn the debugger off, and the value +n means
that the debugger is called every n'th time derivatives are computed.
Lfderr Output Control: Controls the number of error messages. Only the first Lfderr errors will appear in the GAMS
list file. The default value of Lfderr is 10.
Rtmxj2 2nd Derivative Noise: A derivative is consider incorrect if the derivative computed by the external module
deviates from the numerically computed derivative by more than Rtmxj2 step. If the derivative is correct,
this can only happen if the 2nd derivative is greater than Rtmxj2. The default value of Rtmxj2 is 1.e4 and it
can be increased if necessary.
16 Debugging External Equations 373
Option Description
Rtzern Zero Noise: If external functions have constant derivatives then the constant terms are still part of the external
function and this can give rise to small inaccuracies in the contribution of the constant derivatives to the
function value. This noise can cause the debugger to incorrectly state that a the external equation depend on
the variable with the constant derivative. A larger value of Rtzern may cure the problem. The default value is
1.e-14.
374 External Equations
Chapter 29
When calling GAMS from a program one usually spawns gams.exe (Windows) or gams (Unix), located in the GAMS system
directory.
Using the return codes allows the calling program to find out if there were any compilation or execution errors or other
reasons why the GAMS job could not be completed. It is noted that return codes do not say anything about a model inside
the GAMS job: the model may have been infeasible or may have failed in another way while the return code says all is fine.
In fact there may be multiple solves in a GAMS job, so even conceptually it is not possible to return solution status codes in
the return code.
Note: On Unix, return codes are treated modulo 256, so the exit code 400 will be 144 on Unix.
Error 3000 is sometimes caused by specifying the current directory in Microsoft UNC format.
This document describes the GDX (GAMS Data eXchange) facilities available in GAMS. In addition to these facilities, there
are a few utilities to work with GDX files.
A GDX file is a file that stores the values of one or more GAMS symbols such as sets, parameters variables and equations.
GDX files can be used to prepare data for a GAMS model, present results of a GAMS model, store results of the same model
using different parameters etc. A GDX file does not store a model formulation or executable statements.
GDX files are binary files that are portable between different platforms. They are written using the byte ordering native to the
hardware platform they are created on, but can be read on a platform using a different byte ordering.
Users can also write their own programs using GDX files by using the gdxdclib library. The interface and usage for this
library is described in a separate document; see gdxioapi.chm or gdxioapi.pdf.
Compression:
Starting with version 22.3 of GAMS, gdx files can be written in a compressed format. Compression is controlled
by the environment variable GDXCOMPRESS. A value of 1 indicates compression.
GDX files can be converted to a compressed format or an older format too; see GDXCOPY.
The following directives are available for reading data from a GDX file into GAMS during compilation of a GAMS model:
Parameter(s) Description
Filename Specify the GDX file to be used for reading
378 GAMS Data eXchange (GDX)
Parameter(s) Description
id= Loads all unique elements from the gdx file into set id
Parameter(s) Description
id1 id2 ... idn Read GAMS symbols id1, id2, . . . idn from the GDX file
id1=gdxid1 id2=gdxid2 Read GAMS symbols id1, id2 with corresponding names gdxid1,
gdxid2 in the GDX file
id1<gdxid1 id2<gdxid2.dim3 Reads GAMS one dimensional set id1 and id2 from the GDX
parameter or set gdxid1 and gdxid2. WIthout the dimN suffix,
GAMS tries to match the domains from the right (<). If no domain
information is available for the GDX symbol, the dimN suffix
determines the index position that should be read into the GAMS
set. For more details see the fourth example.
id1<=gdxid1 id2<=gdxid2.dim3 Reads GAMS one dimensional set id1 and id2 from the GDX
parameter or set gdxid1 and gdxid2. WIthout the dimN suffix,
GAMS tries to match the domains from the left (<=). If no domain
information is available for the GDX symbol, the dimN suffix
determines the index position that should be read into the GAMS
set. For more details see the fourth example.
Note: $LOAD simply ignores elements that are not in the domain. $LOADDC will cause a compilation
error when the data read causes a domain violation.
$LOADM, $LOADR, $LOADDCM, and $LOADDCR - Additional forms of the $LOAD and $LOADDC directives.
The M indicating a merge and the R indicating a full replacement.
Parameter(s) Description
id1 id2 ... idn Read GAMS symbols id1, id2, . . . idn from the GDX file
id1=gdxid1 id2=gdxid2 Read GAMS symbols id1, id2 with corresponding names gdxid1,
gdxid2 in the GDX file
id1<gdxid1 id2<gdxid2.dim3 Reads GAMS one dimensional set id1 and id2 from the GDX
parameter or set gdxid1 and gdxid2. WIthout the dimN suffix,
GAMS tries to match the domains from the right (<). If no domain
information is available for the GDX symbol, the dimN suffix
determines the index position that should be read into the GAMS
set. For more details see the fourth example.
id1<=gdxid1 id2<=gdxid2.dim3 Reads GAMS one dimensional set id1 and id2 from the GDX
parameter or set gdxid1 and gdxid2. WIthout the dimN suffix,
GAMS tries to match the domains from the left (<=). If no domain
information is available for the GDX symbol, the dimN suffix
determines the index position that should be read into the GAMS
set. For more details see the fourth example.
1 Using the GDX facilities in GAMS 379
$LOADIDX - Read GAMS symbols from the GDX file. Each symbol should have been written using an indexed write.
Parameter(s) Description
id1 id2 ... idn Read GAMS symbols id1 id2 ... idn from the GDX file. Each symbol should
have been written using an indexed write; see Execute UnloadIDX
id1=gdxid1 id2=gdxid2 Read GAMS symbols id1, id2 with corresponding names gdxid1, gdxid2 in
the GDX file. Each symbol should have been written using an indexed write;
see Execute UnloadIDX
Attention
Only one GDX file can be open at the same time.
When reading data, the symbol to be read has to be defined in GAMS already
Parameter(s) Description
Filename Specify the GDX file to be used for writing
Parameter(s) Description
(no identifiers) Write all symbols to the gdx file
id1 id2 ... idn Write GAMS symbols id1, id2, . . . idn to the GDX file
id1=gdxid1 id2=gdxid2 Write the GAMS symbol id1 to the GDX file with name gdxid1
Attention
Only one GDX file can be open at the same time.
When writing data, an existing GDX file will be overwritten with the new data; there is no merge or append
option.
Example 1
The trnsport.gms model ( [TRNSPORT] model from the GAMS Model Library) has been modified to use the demand
data from an external source. Only the relevant declarations are shown.
The parameter B is read from the GDX file using the name 'demand', and only those elements that are in the domain J will be
used. Values for parameter B that are outside the domain J will be ignored without generating any error messages.
*Example 1
380 GAMS Data eXchange (GDX)
Set
j markets / new-york, chicago, topeka / ;
Parameter
B(j) demand at market j in cases ;
$GDXIN demanddata.gdx
$LOAD b=demand
$GDXIN
Example 2
In this example, the set J is also read from the GDX file, and is used as the domain for parameter B. All elements read for the
set J will be used. Values for the parameter B that are outside the domain J will be ignored. Note that the dimension of set J is
set to one by specifying its domain.
*Example 2
$GDXIN demanddata.gdx
Set
J(*) markets;
$LOAD j=markets
Parameter
B(j) demand at market j in cases ;
$LOAD b=demand
$GDXIN
Example 3
*Example 3
$GDXIN trnsport.gdx
$LOAD
Example 4
Sometimes, a set is implicitly given by the elements of a parameter symbol. For example,
1 Using the GDX facilities in GAMS 381
in trnsport.gms implicitly defines the set of plants i. GAMS does not allow us to provide domain checked data, if the data
for domain sets is unknown. So this code produces a compilation error:
Set i plant;
Parameter a(i) capacity / seattle 350, san-diego 600 /;
When entering data directly in the GAMS source adding the domain sets before the actual parameter declarations is usually
not a problem, but when data comes from external sources (e.g. spreadsheets, databases, etc), this often results in an additional
query to the database, spreadsheet etc. Nowadays, such data exchange happens mostly via the GD facility. With the domain
load capability of the compile time load instructions ($load, $loadDC, $loadR, $loadM, $loadDCM, and $loadDCR) one can
project an index position from a parameter or set symbol in the GDX container and load this slice into a one dimensional set.
Here is a simple example:
Set i plant;
Parameter a(i) capacity;
$gdxin data
$load i<adata a=adata
This will try to load set elements from the GDX parameter symbol adata into the set i and next load the GDX parameter
adata into the GAMS parameter a. The latter one is no problem anymore, since the data for set i is known when loading
symbol a. GAMS will use the domain information stored in GDX of parameter adata to identify the index position to project
on. If no appropriate domain information can be found in GDX, the GAMS compiler will generate an error. In such case the
user can explicitly select an index position (here first index position) from the GDX symbol:
The automatic index position matching (i.e. no .dimN) using the domain information stored in GDX matches on the name of
the set to be loaded and the domain set names stored in GDX for the symbol. The domain in GDX are searched from right
to left (start with n=symbol dimension, then n-1, n-2, ...) and stops at the first match. With the projection symbol <=, the
domain in GDX is searched from left to right. This follows the style of the GAMS run time projection operation:
Here is an example how to load. The network is defined by the capacity parameter cap contained in a GDX container
net.gdx:
The following code loads the entire node set n of the network as well as the nodes with outgoing (out) and incoming (in)
arcs and the capacity c.
There is a potential issue with loading domains from parameters that have a zero value for some record. Since GAMS works
with sparse data, it is sometime difficult to distinguish between a record with value zero (0) and the non-existence of a record.
This is usually not a problem since we know the domain of a parameter and hence know all potential records. In case of
using a parameter to define the domain this represents a source of confusion. Moreover, GDX has the capability of storing
true zeros (most GDX utilities like gdxxrw have options (Squeeze=Y or N) to either write a true 0 or squeeze the 0s when
writing GDX). So in case GDX has a zero record, a domain load from such a parameter will include this record. Here is an
example. The spreadsheet Book1.xlsx contains the following data:
The GDX utility GDXXRW with the following command line
Reads the Excel data and produces a GDX container Book1.gdx with a one dimensional parameter dat() which can be
viewed in the GDX browser in the GAMSIDE:
Notice that label a4 is present while label a3 is not part of GDX symbol dat. Without the Squeeze=N (the default is
Squeeze=Y) we also would not have seen a4. If we load dat to define the domain (remember we need to use $load i<dat.dim1
since gdxxrw does not write domain information to GDX), we will miss out on a3 but have a4 (assuming Squeeze=N). Please
also note that the zero record disappears on regular loading and is turned into an EPS when loading under $OnEps:
set i;
parameter a(i);
$gdxin Book1
$load i<dat.dim1 a=dat
display i,a;
parameter a0(i);
$OnEps
$load a0=dat
display a0;
---- 5 PARAMETER a
a1 5.000, a2 1.000
---- 9 PARAMETER a0
a1 5.000, a2 1.000, a4 EPS
With gdxxrw parameter Squeeze=Y the listing file would look as follows:
---- 5 PARAMETER a
1 Using the GDX facilities in GAMS 383
a1 5.000, a2 1.000
---- 9 PARAMETER a0
a1 5.000, a2 1.000
execute_load filename,id1,id2=gdxid2,..;
execute_loaddc filename,id1,id2=gdxid2,..;
The execute load statement acts like an assignment statement, except that it does not merge the data read with the current
data; it is a full replacement. The same restrictions apply as in an assignment statement: we cannot assign to a set that is used
as a domain, or to a set used as a loop control. With execute loaddc any domain violation will be reported and flagged
as execution error. In contrast, execute load ignores all domain violations and loads only data that meets the domain
restrictions. In addition to loading data for sets, parameters and variables, we can load a field of a variable into a parameter.
Warning: when loading a single field, all other fields are reset to their default value.
To write data
execute_unload filename,id1,id2=gdxid,..;
execute_unloaddi filename,id1,id2=gdxid,..;
execute_unloadidx filename,id1,id2=gdxid,..;
The execute unload statement replaces an existing file with that name; it does not add symbols to or replace symbols in an
existing GDX file. Without specifying any identifier, all sets, parameters, variables and equations will be written to the GDX
file. Execute unloaddi does the same as execute unload, but also writes the domains of all unloaded symbols to the same
file.
The execute unloadidx statement requires that each symbol written is a parameter; each parameter must have a domain
specified for each index position. These domains have the requirement that they are formed using an integer sequence for the
UELs that starts at 1 (one). The domain names are changed to indicate the size of each domain. This information is used
when reading the data back from the GDX file using $LoadIDX during compilation. Using the special domain names, the
UELs for the domains can be recovered without writing the domains to the GDX file; see example below.
The GAMS option gdxUELs controls which UELs are registered in filename. With option gdxUELs = squeezed; (default)
only the UELs that are required by the exported symbols are registered while all known UELs are registered if we set option
gdxUELs = full;.
Write a solution point
save_point = n
This is an option, specified on the command line, using an option statement or a model attribute, to write the current model
solution to a GDX file. The option values are:
0: do not write a point file (default)
1: write the solution to <workdir><modelname> p.gdx
2: write the solution to <workdi><modelname> p<solvenumber>.gdx
Read a solution
execute_loadpoint filename;
execute_loadpoint filename,id1,id2=gdxid2,..;
The execute loadpoint allows you to merge solution points into any GAMS database. Loading the data acts like an
assignment statement and it merges/replaces data with current data. For variables and equations, only level values and
384 GAMS Data eXchange (GDX)
marginal values (.L and .M) are used. If no symbols are specified, all symbols that match in type and dimensionality will be
loaded into the GAMS database.
The gdx file that can be used is not limited to files created with SAVE POINT; any gdx file can be used.
This example again uses the trnsport.gms model. After solving the model, we write the sets I and J and the variables Z
and X to the GDX file:
*Example 5
Set I /. . ./,
J / . . . /;
Variable X(I,J),
Z;
. . .
This example shows the use of the indexed write and read data:
Set I /1*100/,
J /1*50 /;
parameter A(I,J) /1.1=11, 1.9=19, 10.1=101/;
Execute_UnloadIDX data.gdx, A;
Viewing the file data.gdx in the gamside shows the modified domain information:
To read from data.gdx, we use the indexed read:
Set I,J;
parameter A(I,J);
*load the data
$gdxin data.gdx
$LoadIDX A
$gdxin
*write all symbols so we can inspect in the gamside
$gdxout test.gdx
$unload
$gdxout
Execute_UnloadIDX data.gdx, A;
Viewing the file test.gdx in the gamside shows that the domains have been populated:
Using the gdx option in the GAMS call, will cause all sets, parameters, variables and equations to be written to the GDX file.
For example:
2 GDX Utilities 385
Or
Using the gdx parameter when running the model using the GAMSIDE, the process window will show the GDX filename in
blue indicating that the file can be opened using a double-click with the mouse.
The $LOAD directive without any parameters will show a listing of all symbols in the file.
The GAMSIDE can be used to view the contents of a GDX file by opening the file as any other file. The IDE only
recognizes the .gdx file extension.
The GDXDUMP utility can list the symbols in the file and it also can write sets and parameters formatted as a GAMS
data statement.
The GDXDIFF utility can be used to compare two GDX files by creating a third GDX file containing the differences
between all symbols with the same name, type and dimension.
2 GDX Utilities
This section describes an alphabetical list of GDX based tools and GDX related tools, included in any GAMS distribution
and maintained by GAMS. See also Tools included in the distribution.
GDXRANK reads one or more one dimensional parameters from a GDX file, sorts each parameter and writes the sorted
indices as a one dimensional parameters to the output GDX file.
GDXRENAME renames the unique elements in a GDX file using the unique elements from second GDX file.
GDXXRW allows reading and writing of an Excel spreadsheet. This utility requires the presence of Microsoft Excel and
therefore can only be used on a PC running the Windows operating system with Microsoft Excel installed.
GDXVIEWER views and converts data contained in GDX files. Besides inspecting a GDX file, gdxviewer allows you to
export to a large number of data formats, including ASCII text, CSV, HTML, XML, database, and spreadsheet formats.
INVERT performs a matrix inversion.
Some tools listed above are MS Windows based tools for data exchange between different applications, which are included in
the current GAMS Distribution and are maintained by GAMS. These tools are designed as interactive Windows programs,
but most of them can also be operated through command line parameters. See Support Platforms for more details.
Chapter 31
When the data for this table is coming from a program it is more convenient to say in the main program:
and to have the include file to contain the machine generated statements:
d("SEATTLE","NEW-YORK") = 2.5;
d("SAN-DIEGO","NEW-YORK") = 2.5;
d("SEATTLE","CHICAGO") = 1.7;
d("SAN-DIEGO","CHICAGO") = 1.8;
d("SEATTLE","TOPEKA") = 1.8;
d("SAN-DIEGO","TOPEKA") = 1.4;
In fact GAMS can deal quite comfortably with a large number of such assignment statements. Models with hundreds of
thousands of such statements are not an exception. Sometimes it is desired not to have the input echoed to the listing file. In
that case, surround the $include by $offlisting and $onlisting instructions:
$onlisting
display d;
You will notice in the listing file that line numbers are skipped where the $offlisting is in effect. In some cases it may be more
convenient to use the PARAMETER initialization syntax. I.e. the main GAMS file could contain the fragment:
Here you see that the $include is handled in a preprocessing step before the language compiler parses the syntax: the include
statements can even be used in the middle of a GAMS statement. The data file contains the following records:
SEATTLE.NEW-YORK 2.5
SAN-DIEGO.NEW-YORK 2.5
SEATTLE.CHICAGO 1.7
SAN-DIEGO.CHICAGO 1.8
SEATTLE.TOPEKA 1.8
SAN-DIEGO.TOPEKA 1.4
This approach is preferable for very large data sets as it is more efficient for GAMS.
Attention
TABLEs and PARAMETERs in GAMS are really the same thing. Internally both are handled identically. The only
difference is how data is entered. With a TABLE a tabular input format is used, while PARAMETERS are either
calculated or inputted as a list.
put results;
$batinclude put.inc distance i j d
$batinclude put.inc cost i j c
$batinclude put.inc level i j x.l
$batinclude put.inc marginal i j x.m
putclose;
loop((%2,%3),
put "%1%,%2.tl,%3.tl,%4(%2,%3)/
);
%1,%2, etc are the positional command line arguments for the 'batinclude' file. They are substituted out with actual parameters
such as 'distance', 'i', and 'j'. The parameters of the $batinclude facility are separated by blanks - do not use commas for this
purpose.
One can also pass parameters using $libinclude or $sysinclude. The syntax only differs from Batinclude in terms of where
the file comes from. Namely, if an incomplete path is given, the file name is completed using the library include directory
(libinclude) or the system include directory (sysinclude). For details please consult the documentation.
sets
l livestock types /sheep,goat,angora,cattle,buffalo,mule,poultry/
cl livestock comm /meat,milk,wool,hide,egg/
ty time periods - years / 1974*1979 /
;
Table yieldtl(l,cl,ty) livestock "yield" time series (kg per head)
"sheep","meat","1974",10.60
"sheep","meat","1975",11.42
"sheep","meat","1976",10.60
"sheep","meat","1977",9.38
"sheep","meat","1978",8.97
"sheep","meat","1979",6.93
1 Import ASCII Files to GAMS 391
"sheep","milk","1974",23.70
"sheep","milk","1975",24.10
"sheep","milk","1976",24.20
"sheep","milk","1977",24.20
$include data.txt
$offdelim
/;
display d;
Displaying such a table in Excel is very convenient with the pivot table. After reading in the data, we have:
After adding a header row and transforming this into a pivot table, we can move dimensions around. The following screen
392 Data Exchange with ASCII Files
shots are examples of tables that can be generated with a few mouse movements:
Figure 31.2: Table after adding a header row and transforming into a pivot table
Figure 31.3: Table after adding a header row and transforming into a pivot table
status, the level values of the decision variables X(I,J) and the level value of the objective variable Z. The following fragment
will do this job:
put "Objective",z.l/;
put "Shipments"/;
loop((i,j),
put i.tl, j.tl, x.l(i,j)/
);
putclose;
This will be difficult to read into a spreadsheet for instance, as some blanks are to be considered as separators, while others
are really part of a string (e.g. Model status). The Put writing facility has an option however to generate comma delimited
files. For this we need to add the line results.pc=5:
"Model status",1.00
"Solver status",1.00
"Objective",153.67
"Shipments"
"seattle","new-york",50.00
"seattle","chicago",300.00
"seattle","topeka",0.00
"san-diego","new-york",275.00
"san-diego","chicago",0.00
"san-diego","topeka",275.00
394 Data Exchange with ASCII Files
For more information about the Put writing facility, see The Put Writing Facility .
Attention
Instead of writing PUT statements to generate a CSV file, you can also generate a GDX file, and use the GDXViewer
utility to export data to a CSV file or use gdxxrw for a direct link between Excel and gdx files, please visit the
section about Data Exchange with Excel for details.
or
A typical example for the usage of these commands is the generation of solver option file. For a extended discussion
please visit the McCarl GAMS User's Guide (Other named files: $Echo, $Offecho, $Onecho)
For more examples, please check the models [gamsutil], [gamshtm], [schulz], [solnpool], and [dicegrid] of the GAMS
Model Library.
returns:
2 Export ASCII Files from GAMS 395
GAMS Rev 149 Copyright (C) 1987-2007 GAMS Development. All rights reserved
...
--- Starting compilation
This text will show up in the log file
--- trnsport.gms(69) 3 Mb
...
396 Data Exchange with ASCII Files
Chapter 32
1 A tutorial on how to read data from Excel and to write data to Excel
This section gives a brief overview on how to use the GDX facilities in GAMS to read data from Excel and to write data to
Excel. For more detailed information please consult the document on GDX Facilities and Tools.
1.1 Introduction
GAMS communicates with Excel via GDX (GAMS Data Exchange) files. A GDX file is a file that stores the values of one or
more GAMS symbols such as sets, parameters variables and equations. GDX files can be used to prepare data for a GAMS
model, present results of a GAMS model, store results of the same model using different parameters etc. A GDX file does
not store a model formulation or executable statements.
GDX files are binary files that are portable between different platforms. They are written using the byte ordering native to the
hardware platform they are created on, but can be read on a platform using a different byte ordering. In order to write data
from GAMS to Excel, the user writes a GDX file and then writes the Excel file from the GDX file: GAMS -> GDX -> Excel.
This is practically seamless for the user and requires few commands. The process to import data from an Excel file to GAMS
is similar: Excel -> GDX -> GAMS
Note that the execute unload command is executed during the actual execution phase (not during compilation time as $
control options) and creates a GDX file called results.gdx.
Now let us write the data from the GDX file to an Excel file called results.xls. We do this using the GDXXRW utility
For the first call for x.L, there is no range specified and the data is written in cell A1 and beyond in the first available sheet.
For the marginals x.M data will be written to cells F1:I4 in the sheet NewSheet. Note that we specified var=x.L and
var=x.M. If the user wishes to write parameters to the Excel file, the relevant command is par.
Again, we will use the transportation model and make use of the results.xls file created by the previous model. First we
will create the GDX file from the Excel file. We will make use of the GDXXRW utility:
Note that since we are using the $CALL command, this occurs during the compilation phase and not during execution time.
We specify that the data in the range A1:D3 is read in as a parameter called Level. The resulting GDX file will be called
results.gdx
Before we can read in the data, we must define a parameter called Level over the appropriate sets:
Parameter Level(i,j);
$GDXIN results.gdx
$LOAD Level
$GDXIN
The $GDXIN results.gdx command specifies that data will be read in from the appropriate GDX file. We then import data
structures values using the $LOAD command. When we are finished, we terminate with $GDXIN.
In the example below, we then fix the level values of the variable x to the parameter Level so that solving results in a trivial
fixed model.
GDXXRW is a utility to read and write Excel spreadsheet data. GDXXRW can read multiple ranges in a spreadsheet and
write the data to a 'GDX' file, or read from a 'GDX' file, and write the data to different ranges in a spreadsheet. For further
information and the documentation, please consult the documentation about the GDX Facilities and Tools.
In some cases it is convenient to consider tabular data in an Excel spreadsheet as a database table and to import it using the
SQL2GMS tool. Consider the spreadsheet:
2 Import from Excel 399
The table name is equal to the sheet name(profitdata). We can pass the query to the Excel ODBC driver using the tool
SQL2GMS as follows:
$ontext
$offtext
$gdxin excel.gdx
$load d=p
display d;
INDEX 1 = 1997
sales profit
INDEX 1 = 1998
sales profit
Here are the input files : mod.gms and profit.xls, for more information see sql2gms.
The CSV (Comma-separated values) file format can be easily imported into GAMS at compilation time. This format is for
instance easily generated by Excel, using its Save As CSV functionality. Consider the GAMS table:
Notice that we added a 'dummy' string in cell A1. This is necessary as we need a placeholder there (the underlying problem
is a bug in GAMS: the comma should be enough to signal the end of a field). Now we save this worksheet as a CSV file -
which will look like:
dummy,new-york,chicago,topeka
seattle,2.5,1.7,1.8
san-diego,2.5,1.8,1.4
This file can now be included directly into GAMS by using the $ondelim and $offdelim commands:
Sets
i canning plants / seattle, san-diego /
j markets / new-york, chicago, topeka / ;
table d(i,j) distance in thousands of miles
$ondelim
$include data.csv
$offdelim
display d;
Notice we have left out a ';' between the ''TABLE'' statement and the ''display'' statement. Usually GAMS is quite tolerant
regarding this, and indeed the listing file shows:
1 Sets
2 i canning plants / seattle, san-diego /
3 j markets / new-york, chicago, topeka / ;
4 table d(i,j) distance in thousands of miles
INCLUDE C:\temp\data.csv
7 dummy ,new-york,chicago,topeka
8 seattle,2.5,1.7,1.8
9 san-diego,2.5,1.8,1.4
11 display d;
...
402 Data Exchange with Excel
dummy;new-york;chicago;topeka
seattle;2,5;1,7;1,8
san-diego;2,5;1,8;1,4
The decimal points have become decimal comma's and the comma separator symbols are now semi-colons. This file can not
be processed by GAMS as GAMS does not consult the Windows settings but sticks to US standardization.
To change the comma into a dot and the semicolon into a comma we just use one of the POSIX tools, which are part of any
GAMS system and write a few lines of GAMS code:
* translate , to . using tr
$call "tr , . <input.csv >temp.csv"
* translate ; to , using tr
2 Import from Excel 403
or
and get
Note: When importing and exporting data using the GDX Utilities, the regional settings are not an issue.
2.5 XLS2GMS
XLS2GMS is a simple utility that allows you to extract data from an Excel spreadsheet and convert it into a GAMS include file.
When running xls2gms.exe without extra command line parameters, the utility will run in interactive mode. It will come up
with the following form:
404 Data Exchange with Excel
The input file consists of an .XLS file. By default the used part of the first sheet is exported, but this can be changed by
setting an appropriate range. An example of a range that can be specified is Sheet2!A1:G8. An output file is created that
can be used as a GAMS include file. The browse buttons open a File Open or a Save As dialog box that can help you in
navigating around on your hard disk. It is advised to use absolute paths, as for windows applications it is not always obvious
what the current directory is.
The philosophy of the utility is that you write pure GAMS syntax in the spreadsheet. I.e. you can write GAMS statements
such as TABLE, SET, PARAMETER or parts of them. It is your responsibility to write correct GAMS syntax. The only smart
thing the utility does it to align cells, such that GAMS TABLE data are correctly handled.
In the above example we have a simple spreadsheet:
2 Import from Excel 405
* * -----------------------------------------------------
* * XLS2GMS 2.8 Dec 24, 2007 WIN.FR.NA 22.6 280.000.000.vis Delphi
* * Erwin Kalvelagen, GAMS Development Corp.
* * -----------------------------------------------------
* * Application: Microsoft Excel
* * Version: 12.0
* * Workbook: C:\temp\exa.xls
* * Sheet: Sheet1
* * Range: $A$1:$C$3
* * -----------------------------------------------------
* j1 j2
* i1 1 3
* i2 2 4
* * -----------------------------------------------------
3 Export to Excel
GDXXRW is a utility to read and write Excel spreadsheet data. GDXXRW can read multiple ranges in a spreadsheet and
write the data to a 'GDX' file, or read from a 'GDX' file, and write the data to different ranges in a spreadsheet. For further
information and the documentation, please consult the documentation about the GDX Facilities and Tools.
GDXVIEWER is a tool to view and convert data contained in GDX files. It can also export to csv, xls, xml-files and pivot tables.
For further information and the documentation, please consult the documentation.
When a CSV file is saved with an extension .csv Excel will read it directly. Either click on it in the explorer or use in Excel:
File|Open and then select Files of Type: Text Files (.prn; .txt; .csv). Now the file will be read directly into Excel without
further questions.
Below is a GAMS fragment to create a .csv file:
Note: The GDXVIEWER can also export to CSV files. It is possible to spawn Excel automatically from GAMS to view the
result by using the ShellExecute utility :
3.4 gdx2xls
The gdx2xls tool dumps the contents of a gdx file into a spreadsheet or an xml-file. Please see GDX Utilities for more
details.
Sometimes a translation step is needed between the labels used in the model and the ones used in the spreadsheet. One way
to do this is to use a mapping set in GAMS. Consider the following case. The spreadsheet looks like:
4 Mapping Index Label Names 407
set ssi /
new york, washington dc, los angeles, san francisco
/;
parameter ssdata(ssi) /
$call =d:\util\xls2gms I="c:\my documents\test2.xls" B O=d:\tmp\x.inc
$include d:\tmp\x.inc
/;
display ssdata;
Notice the B parameter, which is needed as there are embedded blanks in the labels. Now suppose the rest of the model is
defined in terms of the set I which is defined as:
set i /NY,DC,LA,SF/;
To calculate a parameter data defined over this set, the following simple GAMS fragment can be used:
parameter data(i);
data(i) = sum(map(i,ssi), ssdata(ssi));
display data;
408 Data Exchange with Excel
Translation of index labels can be done inside GAMS (see the previous paragraph), but also very conveniently inside the
database. Consider again the following data to import:
set ssi /
new york, washington dc, los angeles, san francisco
/;
parameter ssdata(ssi) /
$call =mdb2gms I="test.mdb" Q="select city,value from [example table]" B O=x.inc
$include x.inc
/;
display ssdata;
set i /NY,DC,LA,SF/;
set map(i,ssi) /
ny.new york
dc.washington dc
la.los angeles
sf.san francisco
/;
display map;
parameter data(i);
5 Execute GAMS from Excel 409
Notice that the B parameter is used to protect spaces inside label names. Square brackets are used inside the SQL statement
to protect spaces embedded in the table name.
Another way would be to add a table to the Access database:
set i /NY,DC,LA,SF/;
parameter data(i) /
$call =mdb2gms I="test.mdb" Q="select [GAMS City], value from [example table],CityMapper where [Access C
$include x.inc
/;
display data;
Note that this is a very long command line. It is better to move the command Line parameters to a separate file and use the @
notation to instruct mdb2gms to read command line parameters from that file.
3 record(s) selected.
6 record(s) selected.
412 Data Exchange with Databases
"seattle","new-york",+2.50000000000000E+000
"seattle","chicago",+1.70000000000000E+000
"seattle","topeka",+1.80000000000000E+000
"san-diego","new-york",+2.50000000000000E+000
"san-diego","chicago",+1.80000000000000E+000
"san-diego","topeka",+1.40000000000000E+000
"seattle","new-york",50.00
"seattle","chicago",300.00
"seattle","topeka",0.00
"san-diego","new-york",275.00
"san-diego","chicago",0.00
"san-diego","topeka",275.00
SQL3110N The utility has completed processing. "6" rows were read from the
input file.
SQL3149N "6" rows were processed from the input file. "6" rows were
successfully inserted into the table. "0" rows were rejected.
For very large data sets it is advised to use the LOAD command:
SQL3110N The utility has completed processing. "6" rows were read from the
input file.
SQL3515W The utility has finished the "LOAD" phase at time "03-20-2000
18:11:50.337092".
For smaller data sets one can also generate a series of INSERT statements using the PUT facility.
MDB2GMS is a tool to convert data from an Microsoft Access database into GAMS readable format. The source is an MS
Access database file (.MDB) and the target is a GAMS Include File or a GAMS GDX File. MDB2GMS is part of the GDX
Utilites, please consult the documentation for more information.
SQL2GMS
SQL2GMS is a tool to convert data from an SQL database into GAMS readable format. The source is any data source accessible
through Microsoft's Data Access components including ADO, ODBC and OLEDB. The target is a GAMS Include File or a
GAMS GDX File. SQL2GMS is part of the GDX Utilites, please consult the documentation for more information.
CSV Files
Microsoft Access can export tables into comma delimited text files using its Save As/Export menu. Suppose we have the
following table:
After choosing Save As/Export and selecting Text Files we get the following window:
2 Data Exchange with MS Access 415
"seattle","new-york",2.50
"seattle","chicago",1.70
"seattle","topeka",1.80
"san-diego","new-york",2.50
"san-diego","chicago",1.80
"san-diego","topeka",1.40
GAMS dates are one day off when importing from MS Access. Suppose we have an MS Access table with one single date
column:
datefield
----------
3/12/2007
416 Data Exchange with Databases
3/13/2007 10:00:00 AM
3/14/2007 8:30:00 PM
Note that the Cdbl() function converts the date to a floating point number (double precision). The generated include file
looks like:
* -----------------------------------------------------
* MDB2GMS Version 2.8, January 2007
* Erwin Kalvelagen, GAMS Development Corp
* -----------------------------------------------------
* DAO version: 3.6
* Jet version: 4.0
* Database: D:\mdb2gms\examples\sample.mdb
* Query: select datefield,Cdbl(datefield) from datetable
* -----------------------------------------------------
3/12/2007 39153
3/13/2007 10:00:00 AM 39154.4166666667
3/14/2007 8:30:00 PM 39155.8541666667
* -----------------------------------------------------
which looks o.k. However, when we look at the GAMS results in the listing file we see:
---- 28 PARAMETER p
3/12/2007 39153.000, 3/13/2007 10:00:00 AM 39154.417, 3/14/2007 8:30:00 PM 39155.854
---- 39 PARAMETER q
Clearly the dates are off by one day: see the column day. We can fix this problem in different places, e.g. in the query or in
the GAMS model by subtracting 1.0 from an imported date. This problem occurs not only in MS Access but also with other
software packages.
2 Data Exchange with MS Access 417
GDX2ACCESS is a tool to dump the whole contents of a GDX file to a new MS Access file (.mdb file). GDX2ACCESS is part of
the GDX Utilites, please consult the documentation for more information.
GDXVIEWER
Access tables in MDB files can be directly generated by the GDXVIEWER utility. The GDXVIEWER tool uses OLE automation
to export data to an MS Access database. This means that MS Access needs to be installed for the Access Export facility to
work. The GDXVIEWER is part of the GDX Utilites, please consult the documentation for more information.
VBScript
VBScript is a scripting tool that can be used to talk to COM objects. In this case we use it to tell Access to import a CSV
file.
$ontext
Import a table into MS Access using VBscript
$offtext
$if exist new.mdb $call del new.mdb
set i /i1*i10/;
alias (i,j);
parameter p(i,j);
p(i,j) = uniform(-100,100);
display p;
file f /data.csv/;
f.pc=5;
put f,i,j,p/;
loop((i,j),
put i.tl, j.tl, p(i,j):12:8/
);
putclose;
The CSV file contains a header row with the names of the fields:
418 Data Exchange with Databases
"i","j","p"
"i1","i1",-65.65057360
"i1","i2",68.65334160
"i1","i3",10.07507120
"i1","i4",-39.77241920
"i1","i5",-41.55757660
....
The text driver specification HDR=Yes makes sure the first row in the CSV file is treated specially. The log will look like:
U:\temp>gams vbaccess.gms
--- Job vbaccess.gms Start 01/28/08 16:57:37
GAMS Rev 149 Copyright (C) 1987-2007 GAMS Development. All rights reserved
...
--- Starting compilation
--- vbaccess.gms(4) 2 Mb
--- call del new.mdb
--- vbaccess.gms(38) 3 Mb
--- Starting execution: elapsed 0:00:00.109
--- vbaccess.gms(18) 4 Mb
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Please note that although the $onecho/$offecho is at the bottom of the GAMS file, the file access.vbs is created at compile
time. I.e. before the executable statements like PUT, EXECUTE are executed.
JScript
The same script using JScript is similar to the one with VScript. We only price the script itself.
$ontext
Import a table into MS Access using JScript
$offtext
$if exist new.mdb $call del new.mdb
set i /i1*i10/;
alias (i,j);
parameter p(i,j);
p(i,j) = uniform(-100,100);
display p;
file f /data.csv/;
f.pc=5;
2 Data Exchange with MS Access 419
put f,i,j,p/;
loop((i,j),
put i.tl, j.tl, p(i,j):12:8/
);
putclose;
dbLangGeneral = ";LANGID=0x0409;CP=1252;COUNTRY=0";
strSQL = "SELECT * INTO mytable FROM [Text;HDR=Yes;Database=.;FMT=Delimited].[data#csv]";
WScript.Echo("Query : ",strSQL);
oDB = oJet.createDatabase("new.mdb",dbLangGeneral);
WScript.Echo("Created : ",oDB.name);
oDB.Execute(strSQL);
TableDef = oDB.TableDefs("mytable");
WScript.Echo("Rows inserted in mytable : ",TableDef.RecordCount);
oDB.Close();
WScript.Echo("Done");
$offecho
Data in a gdx file do not contain domain information. I.e. a parameter c(i,j) is really stored as c(,). As a result
GDX2ACCESS will invent field names like dim1, dim2, Value. In some cases this may not be convenient, e.g. when more
descriptive field names are required. We will show how a small script in VBscript can handle this task. The script will rename
the fields dim1, dim2, Value in table c to i, j, and transportcost.
rename fields
oTable.Fields.Item("dim1").name = "i"
oTable.Fields.Item("dim2").name = "j"
oTable.Fields.Item("Value").name = "transportcost"
Wscript.Echo "Renamed fields"
oDB.Close
Wscript.Echo "Done"
$offecho
The above VBscript fragment needs to be adapted according to the DAO Data Access Objects version available on the
client machine. This can be implemented in a more robust fashion by letting MS Access find the DAO engine:
set oa = CreateObject("Access.Application")
set oDAO = oa.DBEngine
Wscript.Echo "DAO Version: " & oDAO.version
rename fields
oTable.Fields.Item("dim1").name = "i"
oTable.Fields.Item("dim2").name = "j"
oTable.Fields.Item("Value").name = "transportcost"
Wscript.Echo "Renamed fields"
oDB.Close
Wscript.Echo "Done"
Please note that the macro %system.fp% is replaced by GAMS by the working directory (this is the project directory when
running GAMS from the IDE).
"seattle","new-york",50
"seattle","chicago",300
"seattle","topeka",0
"san-diego","new-york",275
"san-diego","chicago",0
"san-diego","topeka",275
which can be read by GAMS directly. This approach can be automated as follows:
--- x.gms(5) 1 Mb
--- call mysql -u root < myscript
--- .data.csv(6) 1 Mb
--- x.gms(15) 1 Mb
--- Starting execution
--- x.gms(18) 1 Mb
*** Status: Normal completion
[erwin@localhost erwin]$
1
2 set i /seattle, san-diego/;
3 set j /new-york, chicago, topeka/;
4
6 parameter dist(i,j) /
INCLUDE /tmp/data.csv
9 "seattle","new-york",50
10 "seattle","chicago",300
11 "seattle","topeka",0
12 "san-diego","new-york",275
13 "san-diego","chicago",0
14 "san-diego","topeka",275
16 /;
17
18 display dist;
19
20
21
1 1 INPUT 0 0 /home/erwin/x.gms
2 5 CALL 1 5 mysql -u root < myscript
3 8 INCLUDE 1 8 ./tmp/data.csv
Instead of maintaining the MySQL script in a separate file, it can also be written by GAMS using a statement like:
"seattle","new-york",50.00
"seattle","chicago",300.00
"seattle","topeka",0.00
"san-diego","new-york",275.00
"san-diego","chicago",0.00
"san-diego","topeka",275.00
myql> create table dist(loca varchar(10), locb varchar(10), distance double precision);
Query OK, 0 rows affected (0.00 sec)
Note that we used no keys in our table definition. In practice it is of course highly recommended to define proper keys.
To export an Oracle table a simple solution is to write an SQLPlus script. E.g. if our table looks like:
6 rows selected.
SQL>
set pagesize 0
set pause off
set heading off
spool data
select loca||,||locb||,||distance from dist;
spool off
seattle,new-york,2.5
seattle,chicago,1.7
4 Data Exchange with Oracle 425
seattle,topeka,1.8
san-diego,new-york,2.5
san-diego,chicago,1.8
san-diego,topeka,1.4
This almost looks like our data initialization syntax for parameters:
SEATTLE.NEW-YORK 2.5
SAN-DIEGO.NEW-YORK 2.5
SEATTLE.CHICAGO 1.7
SAN-DIEGO.CHICAGO 1.8
SEATTLE.TOPEKA 1.8
SAN-DIEGO.TOPEKA 1.4
The only differences are in the delimiters that are being used. These differences are easily digested by GAMS once it is in
ondelim mode. I.e. the following syntax can be used to read the data.lst file:
SQL2GMS
An alternative way to import data from Oracle is to use the tool SQL2GMS which can talk to any database with an ADO or
ODBC interface.
Import dates from Oracle databases and converting them to GAMS dates
For most softwares it is easy to generate dates that GAMS can import and understand. The most common issue is that GAMS
is one day off compared to Excel, Delphi, Access, ODBC etc. Oracle is somewhat more involved. First it is useful to have the
date/time exported as a Julian date. This can be done with the following stored procedure:
This function can be used to export dates as simple floating point numbers. In GAMS we need just a simple adjustment by
adding a constant ''DATEDIFF'' defined by:
scalar
refdategams "march 16, 2006, 00:00"
refdateoracle "march 16, 2006, 00:00" /2453811/
datediff "difference between GAMS and Oracle date"
;
refdategams = jdate(2006,3,16);
datediff = refdategams-refdateoracle;
This trick has been applied in a complex scheduling application where dates are important data types that must be exchanged
between the application logic and database tier and the optimization engine.
426 Data Exchange with Databases
A familiar way of moving data into Oracle is to generate standard SQL INSERT statements. The PUT facility is flexible
enough to handle this. For instance the following code:
The .lw and .nw attributes for the put file indicate that no extra spaces around the labels and the numeric values are needed.
These field width attributes have a default value of 12 which would cause the values to look like:
If the amount of data is large the utility SQLLoader can be used to import comma delimited input. I.e. the GAMS code:
"seattle","new-york",50.00
"seattle","chicago",300.00
"seattle","topeka",0.00
"san-diego","new-york",275.00
"san-diego","chicago",0.00
"san-diego","topeka",275.00
LOAD DATA
INFILE results.txt
INTO TABLE result
FIELDS TERMINATED BY , OPTIONALLY ENCLOSED BY "
(loca,locb,shipment)
5 Data Exchange with SQL Server 427
GDX to Oracle
Database tables in an SQL RDBMS can be directly generated by the GDXViewer utility. The GDXViewer tool can use three
methods to export to Oracle and other RDBMS:
1. The direct ADO/ODBC link can create a new table and populate it.
2. The SQL INSERT script generator can create a script with a number of INSERT statements.
3. The SQL UPDATE script generator can create a script with a number of UPDATE statements.
Using SQL2GMS
A good way to import SQL server data into GAMS is using the SQL2GMS tool. Below is an example of its use:
To export SQL Server data to CSV files we can use the BCP utility.
Starting copy...
6 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 10 Average : (600.00 rows per sec.)
It is somewhat more difficult to create a proper CSV file. A format specification file can help here. For an example see the
next section on Data Exchange with Sybase . Other tools to export files include DTS (Data Transformation Services) and
linked ODBC data sources.
A direct interface between SQL server tables and GAMS GDX files
Finally we can program directly an interface between SQL server tables and GAMS GDX files. A small example in C# can
look like:
//
// read a data table
//
gdxio.gdxdatawritestrstart(ap, "data", "from db", 2, csharpclient.dt_par, 0);
q = "select location, capacity, cost exporttable";
cmd = new SqlCommand(q, conn);
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
astrelements[0] = myReader.GetString(0);
astrelements[1] = "capacity";
avals[0] = myReader.GetInt32(1);
Boolean ok = gdxio.gdxdatawritestr(ap, astrelements, avals);
if (!myReader.IsDBNull(2)) {
astrelements[1] = "cost";
avals[0] = myReader.GetDouble(2);
ok = gdxio.gdxdatawritestr(ap, astrelements, avals);
}
}
gdxio.gdxdatawritedone(ap);
myReader.Close();
gdxio.gdxclose(ref ap);
5 Data Exchange with SQL Server 429
Starting copy...
6 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 10 Average : (600.00 rows per sec.)
(6 rows affected)
1> quit
Unfortunately, dealing with quoted strings is not straightforward with this tool (an example using a format file is shown in the
next section on Data Exchange with Sybase . The same thing holds for BULK INSERT, which can read:
seattle,new-york,50.00
seattle,chicago,300.00
seattle,topeka,0.00
san-diego,new-york,275.00
san-diego,chicago,0.00
san-diego,topeka,275.00
(6 rows affected)
1> select * from x
2> go
loca locb shipment
---------- ---------- ------------------------
seattle new-york 50
seattle chicago 300
seattle topeka 0
san-diego new-york 275
san-diego chicago 0
san-diego topeka 275
(6 rows affected)
1> quit
A slower but flexible way to load CSV files is to use a linked server through the ODBC Text Driver. First create an ODBC
DSN using the Text Driver. This can be done through the ODBC Data Source Administrator Data Sources (ODBC) Then we
can use the system procedure SP AddLinkedServer.
--
-- create table in SQL server
--
create table results(loca varchar(10), locb varchar(10), ship float)
5 Data Exchange with SQL Server 431
GO
--
-- Create a linked server
--
EXEC sp_addlinkedserver txtsrv,Jet 4.0,Microsoft.Jet.OLEDB.4.0,c:\winnt\gamsdir,NULL,Text
GO
--
-- copy data from text file c:\winnt\gamsdir\results.csv
--
insert into results(loca,locb,ship)
select * from txtsrv...results#csv
go
--
-- check if all arrived
--
select * from results
go
--
-- release linked server
--
EXEC sp_dropserver txtsrv
GO
--
-- clean up
--
drop table results
go
(6 rows affected)
loca locb ship
---------- ---------- ------------------------
seattle new-york 50
seattle chicago 300
seattle topeka 0
san-diego new-york 275
san-diego chicago 0
san-diego topeka 275
(6 rows affected)
1> quit
2> go
1> insert into t
2> select * from
3> OpenRowSet(Microsoft.Jet.OLEDB.4.0,
4> Text;Database=c:\winnt\gamsdir\;HDR=NO,
5> select * from results.csv)
6> go
(6 rows affected)
1> select * from t
2> go
loca locb ship
---------- ---------- ------------------------
seattle new-york 50
seattle chicago 300
seattle topeka 0
san-diego new-york 275
san-diego chicago 0
san-diego topeka 275
(6 rows affected)
1> drop table t
2> go
1> quit
When using GDXViewer to export data to MS SQL server it is noted that MSSQL Server does not accept the default SQL
type double for double precision numbers. You will need to set this setting to float or double precision.
When we export variable x from the trnsport model, we see:
(6 rows affected)
1> quit
Sybase is largely the same as SQL Server. For exporting ASCII files from a Sybase table, the utility (Using the BCP utilty
and CSV files) can be used.
An example of use of this utility is shown below:
(6 rows affected)
1> quit
[erwin@fedora sybase]$ cat bcp.fmt
10.0
4
1 SYBCHAR 0 0 "\"" 1 loca
2 SYBCHAR 0 10 "\",\"" 1 loca
3 SYBCHAR 0 10 "\"," 2 locb
4 SYBCHAR 0 17 "\n" 3 shipment
[erwin@fedora sybase]$ bcp testdb..results out res.txt -S LOCALHOST -U sa -P sybase \
434 Data Exchange with Databases
-J iso_1 -f bcp.fmt
Starting copy...
6 rows copied.
Clock Time (ms.): total = 1 Avg = 0 (6000.00 rows per sec.)
[erwin@fedora sybase]$ cat res.txt
"seattle","new-york",50.0
"seattle","chicago",300.0
"seattle","topeka",0.0
"san-diego","new-york",275.0
"san-diego","chicago",0.0
"san-diego","topeka",275.0
[erwin@fedora sybase]$
Note: the first column in the format file is a dummy (it has length 0). This is in order to write the leading quote, as bcp only
allows for termination symbols.
This can be automated using the following GAMS code:
sets
i canning plants / seattle, san-diego /
j markets / new-york, chicago, topeka / ;
The SQL2GMS utility uses ADO or ActiveX Data Objects to extract data from relational databases. It can connect to almost
any database from any vendor as it supports standards like ODBC. For more information about the usage of SQL2GMS, please
visit the GDX Utilities for more information.
The following GAMS code will generate and execute a script written in VBScript. It mimics the behavior of SQL2GMS.EXE
and can be used for debugging or the script can be passed on to the IT support people in case there are problems with
accessing the database.
$ontext
This script mimics SQL2GMS.
7 Data Exchange with Sybase 435
Erwin Kalvelagen
November 2006
$offtext
parameters
t1 = 3 connection timeout
t2 = 0 command timeout
c = "Provider=MSDASQL;Driver={SQL Server};Server=DUOLAP\SQLEXPRESS;Database=testdata;
Uid=gams;Pwd=gams;" connection string
q = "select * from data" query
o = "output.inc" the output file to be generated
b = false whether to quote indices (e.g. because of embedded blanks)
make db connection
ADOConnection.ConnectionTimeout = t1
ADOConnection.ConnectionString = c
ADOConnection.Open
Open file
setup query
starttime = time
ADOConnection.CommandTimeout = t2
const adCmdText = 1
set RecordSet = ADOConnection.Execute(q,,adCmdText)
get results
NumberOfFields = RecordSet.Fields.Count
eof = RecordSet.EOF
if eof then
WScript.Echo "No records"
436 Data Exchange with Databases
Wscript.quit
end if
NumberOfRows = 0
do until eof
NumberOfRows = NumberOfRows + 1
Row = RecordSet.GetRows(1)
if NumberOfFields > 1 then
s = Row(0,0)
if b then
s = quotestring(s)
end if
Outputfile.Write s
end if
s = Row(NumberOfFields-1,0)
OutputFile.Write " "
OutputFile.Writeline s
eof = RecordSet.EOF
loop
OutputFile.Close
function quotestring(s)
has_single_quotes = false
has_double_quotes = false
needs_quoting = false
needs_quoting = true
case else
k = asc(ch)
if (k<=31) or (k>=127) then
needs_quoting = true
end if
end select
next
kw = array("ABORT","ACRONYM","ACRONYMS","ALIAS","BINARY","DISPLAY","ELSE", _
"EQUATION","EQUATIONS","EXECUTE","FILE","FILES","FOR","FREE", _
"IF","INTEGER","LOOP","MODEL","MODELS","NEGATIVE","OPTION", _
"OPTIONS","PARAMETER","PARAMETERS","POSITIVE","PROCEDURE", _
"PROCEDURES","PUT","PUTCLEAR","PUTCLOSE","PUTHD","PUTPAGE", _
"PUTTL","SCALAR","SCALARS","SEMICONT","SET","SETS","SOS1", _
"SOS2","TABLE","VARIABLE","VARIABLES","WHILE")
already quoted?
ch = left(s,1)
select case ch
case "", """"
quotestring = s
exit function
end select
end function
$offecho
438 Data Exchange with Databases
1 Exporting to HTML
As HTML is just ASCII text, the PUT facility can be used to write HTML file.
Furthermore automated export can be done through Excel which supports HTML export
2 Exporting to XML
XML is a format to store data. What HTML is for text, that is XML for data. As HTML, XML is pure ASCII text and thus
Exporting a GAMS model into LaTeX formula can be done with MODEL2TEX tool. MODEL2TEX is a tool to generate a
documentation from GAMS source code in LaTeX format. This LaTeX output can then be further processed in order to
generate pretty output files like PDF. The tool can be found in the root directory of GAMS. The tool allows to document one
specific model symbol inside of a GAMS program. See MODEL2TEX for more information.
Using the The Put Writing Facility and $baticlude Latex files can easily be generated. An example is the model [tsp2ltx]
from the GAMS Model Library. The solution is written to a .tex file, which can be processed by Latex directly and displayed
442 Data and Model Export to LaTeX
in various formats:
The piece of GAMS code, which generates the latex file is:
$onput
\documentclass{article}
\usepackage{amsmath}
\usepackage[all]{xy}
\begin{document}
$offput
$set plottour
$onechoV > plottour.gms
2 Data Export to LaTeX 443
put \end{document}/;
444 Data and Model Export to LaTeX
Chapter 36
which produces:
It is further noted that once can use the GAMSIDE to create graphs from a GDX file using the Charting Facilities. This can
either be done manually or automatically using the The Put Writing Facility .
Import from MPS: MPS2GMS creates an almost generic gms file and a gdx file with the matrix data. MPS2GMS
is part of the current GAMS distribution, please enter ''mps2gms'' at a command line or see MPS2GMS for more
information.
Export to MPS:
The solver Convert (with option CplexMPS) writes an MPS file with trivial names (x1,x2,...,e1,e2,...), but it can
also write a mapping file (use the Convert option'' dict'') that allows you to map the trivial names to your name
space.
Most LP/MIP solver have an option to write out an MPS file.
448 Data and Model Exchange with MPS files
Chapter 38
NETGEN is a well known generator for network problems. It can be downloaded from NETLIB at the following address:
http://www.netlib.org/lp/generators/netgen.
GNETGEN is a generator for Generalized Network problem instances based on the NETGEN generator. It can be downloaded
from http://www.netlib.org/lp/generators/.
Both formats can be translated into a format readable by GAMS using the POSIX tools, which are included in any GAMS
system. The model [netgen] from the GAMS Model Library shows this using the posix tool awk.
450 Data Exchange with NETGEN and GNETGEN
Chapter 39
1 Introduction
This chapter describes the stochastic programming (SP) extension of GAMS EMP. We build a stochastic model based on a
deterministic model by defining model parameters to be uncertain. Then GAMS EMP replaces these uncertain parameters by
random variables. The distribution of the random variables is controlled by the user. Note that these random variables are not
variables in the sense of mathematical optimization, but they can be understood as random parameters.
The chapter is organized as follows: In section The News Vendor the basic principles are introduced with the well known
news vendor problem, in section Multistage Models a multi-stage model is discussed, in section Chance Constraints a class
of models with chance constraints is presented, while how to model risk measures is the topic of section Risk Measures. In
section Summary of keywords and solver configurations a summary of keywords and possible solver configurations is given
and finally more details on scenarios and output extraction follow in section More on scenarios and output extraction.
Maxx,s,i,l z = vs cx hi pl
s.t. d = s+l
(39.1)
i = xs
x, s, l, i 0.
The objective is to maximize the profit z. Here x, s, i, l are the decision variables and the demand d is a known parameter.
The demand d equals the sum of the satisfied demand s (papers sold) and the unsatisfied demand l (lost sales). The inventory
i equals the difference between the number of papers bought x and those sold s. Note that x, s, l, i 0 .
This can easily be translated into GAMS. We assume that the values for c, p, h, v and d are given. Note that our mathematical
formulation is case-sensitive but the GAMS code is not.
Scalar
c Purchase costs per unit / 30 /
p Penalty shortage cost per unit / 5 /
452 Stochastic Programming (SP) with EMP
Variable Z Profit;
Positive Variables
X Units bought
I Inventory
L Lost sales
S Units sold;
* Profit, to be maximized
Profit.. Z =e= v*S - c*X - h*I - p*L;
* demand = UnitsSold + LostSales
Row1.. d =e= S + L;
* Inventory = UnitsBought - UnitsSold
Row2.. I =e= X - S;
Model nb / all /;
solve nb max Z use lp;
Since the demand d is known there is no uncertainty in this model and the optimal solution is obvious: the best decision
is to buy exactly as many newspapers as are demanded. Now we move to more realistic assumptions and consider several
examples where the demand is not known from the outset.
Each realization of D is called a scenario. So there is a finite set of scenarios, each associated with probability p j , where
j p j = 1. In our example, the random variable D takes the values d1 = 45, d2 = 40 and d3 = 50 with respective probabilities
p1 = 0.7, p2 = 0.2 and p3 = 0.1. The decision x has to be made before the realization of the demand D is known.
After the news vendor has made the decision of how many newspapers x to buy on a particular day the actual demand is
disclosed. He may have bought more that he can sell and may have to store the surplus in his inventory or he may not have
bought enough and some demand may remain unsatisfied. We can translate this situation into a model with two stages: in
stage 1 a decision x is made without knowing the future, then one realization of the future unfolds and in stage 2 a second
period decision s, i, l is made that attempts to react to the new situation. The action taken in stage 2 is called recourse. The
key idea in this approach is the evolution of information.
We express this two stage model mathematically in the following way :
Given the uncertainty of the demand we aim to maximize the expected value of the profit, denoted by E[Z(x, D)]. The
expected value of the profit is the profit on average. Note that since we have a finite number of scenarios and their probabilities
are known, the expected value of the profit E[Z(x, D)] can be expressed as a weighted sum:
Notice that we have separated the original optimization problem into two different problems that are solved at two stages.
The decision variable in the first problem (at stage 1) is x and it is the vector yD = (sD , iD , lD ) in the second problem (at stage
2). We introduce additional notation to explicitly represent the underlying structure of the problem. Let
v
I I I 0 0
qD = h , TD =
, WD = , hD = .
0 I 0 I D
p
Using this new notation the second stage optimization problem from (3) becomes:
Note that in our specific example TD T , WD W and qD q since they are independent of the demand D. The general two
stage optimization problem is given here:
where
and
= (q, h, T,W ),
the data of the second stage problem. Note that in our news vendor example there are no first stage equations Ax = b. Table 1
summarizes the two stages in our example.
Table 1: Two stages in news vendor problem
1st stage decision variable 2nd stage decision variable = {d1 , d2 , d3 } Probabilities
yd1 = (sd1 , ld1 , id1 ) Scenario 1: p1 = 0.7
x yd2 = (sd2 , ld2 , id2 ) Scenario 2: p2 = 0.2
yd3 = (sd3 , ld3 , id3 ) Scenario 3: p3 = 0.1
The problem as stated in (6), (7) can be converted to a single large scale optimization problem. The extended form is given
454 Stochastic Programming (SP) with EMP
below:
Finally, we present the problem in matrix form, a notation that has the advantage of explicitly displaying the structure of the
second stage:
Maxx,y cT x + i pi qTi y
A x b
T W y h
1 1 1 1 (9)
s.t. T2 W2 y h
= 2 , x, yi 0.
2
.. .. .. ..
. . . .
Tm Wm ym hm
To formulate this 2-stage-model in GAMS we introduce the notions of a core problem and annotations. The core problem
defines q, h, T , W as parameters instead of having them as random variables. It can be written as follows:
Maxx,y cT
x+ T
qy
A 0 x b (10)
s.t. = , x, y 0.
T W y h
The annotations give details about the various realizations of the random variable , the scenarios.
For our news vendor example the core model is precisely the model given in section The News Vendor. Then we add the
annotations: the distribution of the random variable (in our case the demand which is part of the variable h) has to be specified
as random and every variable and equation must be assigned to one of the two stages. This information is introduced by
writing a text file named %emp.info%. Here is the file for our model:
First, we define the parameter d to be a random variable (randvar) with a discrete distribution: with probability 0.7 it
takes a value of 45, with probability 0.2 it takesa value of 40, and with probability 0.1 it takes a value of 50. Then the
variables and equations of stage 2 are listed. The variables and equations not listed in the emp.info% file are automatically
assigned to a stage, with a default assumed to be stage 1. Note that the objective variable (in our case Z) and the profit
equation are thus assigned to the highest stage specified (stage 2 in this example). Observe that Z is in fact a random variable
since it is a function of the random variable D. As such it cannot be maximized, EMP implicitly maximizes the expected
value of Z. We believe this might lead to some confusion since the expected value f Z belongs to stage 1. We show later
how to specify more clearly the fact that we are maximizing E(Z). All keywords that can be used in the emp.info file are
introduced in subsequent examples and summarized in section Summary of keywords and solver configurations .
Given the probability distribution the solvers of stochastic programming models create various scenarios and evaluate them.
Where should the details of these scenarios be stored (or communicated to the modeler)? In deterministic models the modeler
does not need to specify how the output should be stored. Using EMP for stochastic programming the modeler can store the
results for each scenario in standard parameters. Here is how it is done:
The size of the set scen defines the maximal number of scenarios we are willing to store results for. The three dimensional
set dict contains mapping information between symbols in the model (in the first position) and symbols to store solution
information (in the third position), and the type of storing (in the second position). An exception to this rule is the tuple with
label scenario in the second position. This tuple determines the symbol (in the first position) that is used as the scenario
index. This scenario symbol can be a multidimensional set. A tuple in this set represents a single scenario. In our example,
we want to store the realization for each sceanrio for the random variable d in the parameter s d and the levels of the variables
s and x in the parameters s s and s x respectively. A more detailed description on scenarios and how this set works can be
found in section More on scenarios and output extraction .
Finally, the solve statement needs to be adjusted: we use emp instead of lp and add scenario dict to indicate that a
stochastic problem should be solved.
randvar d normal 45 10
Note that currently only the solver LINDO has implemented a sampling procedure for parametric distributions. More details
about sampling are given in the next section. In Table 2 all parametric distributions that can be modeled are listed.
Table 2: Parametric distributions supported by LINDO
We have to inform GAMS that we want the solver LINDO to be used. There are two ways to do this: we either state in the
command line emp=lindo or we insert the following statement before the solve statement in the GAMS file :
2.3 Sampling
Currently only the solver LINDO has the ability to perform sampling for continuous distributions. It generates 6 samples by
default. There are three ways to customize sampling: 1) adding additional information to the emp.info file, 2) generating a
sample with the LINDO library lsadclib and then using this sample in any solver with EMP capabilities and 3) setting
various options in the solver LINDO. We will discuss each method in more detail in the remainder of this section.
Observe that customizing sampling with EMP is currently experimental, feedback is requested, and possible changes might
occur when its notation becomes fixed. Currently, EMP provides two keywords to enable users to customize sampling:
sample and setSeed. The keyword sample allows the user to customize the size of the sample in the emp.info file. Consider
the following example:
randvar d normal 45 10
sample d 9
The second line determines the size of the sample of the distribution of the random variable D to be 9. Note that currently the
LINDO Sampling library is used for this sampling. Users who don't have a valid LINDO license are limited to the Normal
and Binomial distributions with a maximum sample size of 10.
The keyword sample also offers the possibility to determine a mathematical variance reduction method to be applied.
Variance reduction is a procedure used to increase the precision of the estimated values from the distribution. LINDO
provides three methods for reducing the variance: Monte Carlo sampling, Latin Square sampling and Antithetic sampling.
Consider a stochastic model with four random variables: E, F, G and H. Assume that E follows a Normal distribution with
mean 23 and standard deviation 5, F follows a Normal distribution with mean 37 and standard deviation 8, G is uniformly
distributed on the interval [0, 1] and H is binomially distributed with n = 100 and p = 0.55. We want for each random
variable a sample size of 10 and we want to apply the three variance reduction methods in the following way: LINDO shall
use Antithetic sampling for E and F, Monte Carlo sampling for G and Latin Square sampling for H. To model this we insert
the following lines in the emp.info file:
randvar e normal 23 5
randvar f normal 37 8
randvar g uniform 0 1
randvar h binomial 100 55
sample e f 10 method1
sample g 12 method2
sample h 8 method3
First, the random variables and their distributions are defined. Next, details about the sampling procedures are given. Note
that the keyword sample can take more than one random variable if the sample size and the variance reduction method for
these random variables are the same. We need to add the following lines before the solve statement to specify the content of
method1 , method2 and method3 (we assume that the name of the model is nb):
2 The News Vendor 457
If the Latin Square sampling should also be used for E and F, we would simply change the emp.info file to replace the label
method 1 with the label method 3. For more details on variance reduction methods please consult the LINDO manual.
A further way to customize the sampling procedure is the keyword setSeed:
setSeed <seed>
This sets the seed for the random number generator of the sampling routines called using the sample keyword. If setSeed
is used in the emp.info file, the seed is set once before we generate all samples. Please note that setSeed only works with a
valid LINDO license.
A user may want to sample from a distribution with the LINDO system and solve the model with another solver, say DE.
This is possible with the sampling routines from the LINDO library lsadclib. We could solve the news vendor model by
first drawing a sample from a Normal distribution with mean 45 and standard deviation 10 and then using the sample in the
emp.info file. Here is the GAMS code for sampling from a Normal distribution where the sample size is 9:
scalar k;
k = sampleNormal(45,10,9);
The directive in the first line makes the LINDO sampling library available, msllib is the internal library name. For further
details and a list of the available distributions please consult the LINDO manual.
In the following lines we demonstrate how the sample is used in the emp.info file:
The second line states that the random variable D follows a discrete distribution and the probabilites and values are taken
from the previously generated sample. The other lines of the emp.info file remained unchanged.
There are some customizable sampling options in LINDO. The user could control the number of sampled scenarios by setting
any of the following LINDO/SP options in the lindo.opt file:
For example, we could insert the following three lines before the solve statement:
The first line tells GAMS to solve the emp modeltype using the LINDO solver, the second line writes STOC NSAMPLE STAGE
= 100 to the lindo.opt file, which indicates the solver to generate 100 samples per stage, and the third line informs GAMS to
use the solver option file (i.e. lindo.opt). For more details about LINDO options please consult the user manual.
3 Multistage Models
In models with more than two stages the same principle applies as in 2-stage models: new information is revealed at the
beginning of the stage and recourse decisions or adjustments are made after this information is available. At the point
where decisions are made only outcomes of the current stage and previous stages are available. In (11) this logic is pictured
schematically.
Make
| decision} Random
{z | Variable is realized
{z Make decision}
Stage 1 Stage 2
(11)
|Random Variable is realized
{z Make decision}
Stage n
Observe that random variables which are realized in stage k are fixed parameters in stage k + 1; stage 1 random variables are
in fact simply given deterministic values.
Consider an inventory problem where the decision must be made at the end of each week how many hats should be bought
in order to satisfy the stochastic demand in the following week with the aim to maximize the profit. We assume that the
stochastic demand can be modeled using a Gamma distribution. The planning horizon is 3 weeks. Before the first week starts
an initial purchase decision has to be made and the goods are stored in the inventory for use in week 1. At this point only the
distribution of the demand of the first week is known. During the first week the actual demand is revealed and some items
that were stored in the inventory are sold. Some items may be left over; they are stored as the inventory for the second week.
In addition, a purchase decision for the second week has to be made given the size of the inventory and the distribution of the
demand in the second week. Again, the actual demand is revealed in the course of the second week. The same holds for the
third week.
We will model the problem with 4 stages, where the first stage corresponds to the preparation time before the first week, the
second stage corresponds to decisions made in the first week, the third stage corresponds to decisions made the second week
and the fourth stage corresponds to decisions made in the third week. Let t denote the stages. Note that while the stages
range from t = 1 to t = 4, demand variables are realized only at t = 2 to t = 4. Let yt be the amount bought and it the amount
stored at the end of each stage and let Dt denote the demand in each week and st the amount sold each week. Note that we
denote the demand with a capital D since it is a random variable. Let = 10 be the cost per hat bought, = 20 the revenue
per hat sold and = 4 the storage cost per unit. Further, in the storage facility a maximum of = 5000 hats can be stored.
As discussed in section Uncertain demand: continuous distribution above the solvers use a sampling procedure to approximate
a problem with a continuous random variable such as a Gamma distributed random variable by a problem with a discrete
distribution. Figure 1 illustrates the stages assuming a sample size of 6.
3 Multistage Models 459
where t = 2, . . . , 4 and Dt follows a Gamma distribution. Note that st , yt and it depend on the realization of Dt .
The GAMS code follows.
scalars
kappa capacity of storage building
alpha cost per unit bought
beta revenue per unit sold
delta cost per unit stored at the end of time period;
parameters
k "shape of demand (1st parameter of gamma distribution)"
d theta(st) "scale of demand (2nd parameter of gamma distribution)"
d(st) "demand";
positive variables
y(t) units to be bought in time period t
i(t) ending inventory in period t
s(t) units sold in time period t;
free variable profit;
k = 16;
parameter d theta(st) / 2 208.3125, 3 312.5, 4 125 /;
d(st) = k * d theta(st);
display d;
kappa = 5000;
alpha = 10;
beta = 20;
delta = 4;
equations
profit eq profit to be max
Bal eq(t) balance equation
Sales eq1(st) sales cannot exceed demand
Sales eq2(t) sales cannot exceed inventory of previous time period;
profit eq.. profit =e= sum(t, beta * s(t)$st(t) - alpha * y(t) - delta * i(t));
i.up(t) = kappa;
model inventory /all/;
Set dict /
scen .scenario.
d .randvar .s d
s .level .s s
y .level .s y
i .level .s i /;
display s d, s s, s y, s i;
Observe that in the core problem the values of the demand d(t) are replsced by the expected values of the random variable
Dt which follows a Gamma distribution. Note that as expected, in stage 1 we have only the variables y and i, but no variables
s and d. Note that currently only the solver LINDO can solve models with parametric distributions (see sections Uncertain
demand: continuous distribution and Sampling ).
As discussed in section Sampling above the user could use the LINDO system to generate samples and then solve the
optimization problem with another solver. Here is the GAMS code that allows the user to draw samples for the inventory
model (the sample size is 10). In this code we generate samples from 3 different distributions f, g and h and store the samples
in the parameters sv1, sv2 and sv3.
set j /1*%ss%/;
parameter sv1(j),sv2(j), sv3(j);
loop(j,
sv1(j) = getSampleValues(f); );
display sv1;
loop(j,
sv2(j) = getSampleValues(g); );
display sv2;
loop(j,
sv3(j) = getSampleValues(h); );
display sv3;
1
The user has to modify the emp.info file to use the generated samples sv1, sv2 and sv3) with probabilites |J| to solve the
model:
Note that lines 3-5 are newly inserted in order to use the generated samples; the stages remain unchanged.
In case the modeler wants to use large samples with limited computing capability, LINDO offers the option to approximate
the solution with a Benders decompostion algorithm. The following lines can be inserted to achieve this:
In the second line we ensure that the maximum number of scenarios is large enough. The options in the following lines state
the sample size and determine the stochastic method to be used (1 means Nested Benders decomposition). For further details
on LINDO options please consult the LINDO user manual. We add the last line to ensure that the gap between the true
solution and the approximation is reasonably small.
4 Chance Constraints
A major class of problems in stochastic modeling involves chance constraints. The goal in these problems is to make an
optimal decision prior to the realization of random data while allowing the constraints to be violated with a certain probability.
Let A Rm Rn be a random matrix and let b Rm be a random vector. Then a general stochastic linear program can be
written as:
Minx cT x
s.t. Ax b (13)
x 0.
All feasible solutions satisfy all constraints simultaneously. The distinctive feature of a program with chance constraints is
that we require Ax b to be satisfied not in all cases but only with some prescribed probability p, where 0 < p 1. Note
that often we are interested in the risk tolerance , being the probability that a constraint is not satisfied. So p = 1 .
462 Stochastic Programming (SP) with EMP
Throughout this chapter we use p and 1 interchangeably.A general stochastic linear problem with chance constraints can
be written as follows:
Minx cT x
s.t. P(Ax b) p (14)
x 0.
Solvers convert a problem like (14) into a mixed-integer problem (MIP) first and then solve the MIP equivalent. They
introduce a vector with binary variables, say yk Rm , for each scenario k S. The binary variables take value 1 if the
corresponding constraint is satisfied in a scenario and 0 otherwise. A scenario-based formulation of the chance-constrained
stochastic linear program (14) can be written as:
Minx cT x
s.t. Ak x bk + M k (1 yk )
(15)
kS yk p |S|
x 0, y (0, 1)|S| ,
where M k Rm is a chosen big-M vector. The entries of the vector M k should be chosen such that it does not cut off any
feasible solution if an entry of yk = 0.
We will first discuss the special case where the random matrix A is a one-row vector a Rn , the random vector b is a single
random variable b and we have only one chance constraint. Then we will move on to the two ways to model problems with
multiple chance constraints: using joint chance constraints and using individual chance constraints. Joint chance constraints
require all constraints to be satisfied simultaneously with a given probability. Individual chance constraints require each
constraint to be satisfied with a given probability independent of other constraints. We discuss joint chance constraints in
section Joint Chance Constraints, individual chance constraints in section Individual Chance Constraints and compare them
in section Joint chance constraints vs. individual chance constraints. Finally, in section Penalizing violations of chance
constraints the option to penalize violation of constraints is introduced.
Minx cT x
s.t. P(ax b) p (16)
x 0,
where a is a random row vector and b is a random variable. Given a set of scenarios S let each scenario k S be realized with
probability k . The corresponding realizations of a and b are denoted by ak and bk respectively. The inequalities of the |S|
scenarios may be expressed as follows:
a1 x b1
a2 x b2
.. (17)
.
a|S| x b|S|
If each scenario is equally likely to be realized then the decision variable x must be chosen such that the inequality is satisfied
in at least p |S| scenarios.
Here is an example with two decision variables and 4 scenarios where each scenario is equally likely to be realized (i.e.
k = 14 ) :
Min x1 + x2
s.t. P(x1 + x2 7) 0.75, = {1, 2, 3, 4} (18)
x1 , x2 0.
4 Chance Constraints 463
Note that in this example b is fixed at 7. Note further that there are four scenarios since there are four possible realizations of
. Since p = 0.75 and each scenario is equally likely to be realized we need to choose x1 and x2 such that the inequality is
satisfied in at least 3 scenarios. The inequalities for the four scenarios are given below:
k=1: 1 = 1 1 x1 + x2 7
k=2: 2 = 2 2 x1 + x2 7
(19)
k=3: 3 = 3 3 x1 + x2 7
k=4: 4 = 4 4 x1 + x2 7.
Min x1 + x2
s.t. 1x1 + x2 7 M(1 y1 )
2x1 + x2 7 M(1 y2 )
3x1 + x2 7 M(1 y3 )
4x1 + x2 7 M(1 y4 )
(20)
1
cc1 = 1 k k yk , k = 1, . . . , 4, k = 4
x1 , x2 0
0 cc1 (1 0.75)
yk (0, 1).
Observe that the first four constraints cover the four possible scenarios with taking the values 1, 2, 3 and 4 respectively.
On the right handside we introduce a big- M factor and yk , a binary indicator variable. yk takes the value 1 if the constraint
is satisfied and 0 otherwise. A new variable, cc1 , is introduced in the fifth constraint representing the probability that the
constraint is violated. If cc1 = 0 the sum equals 1, indicating that the constraint is satisfied in all four scenarios. If cc1 = 0.25
the constraint remains unsatisfied in one scenario out of four (for this scenario yk = 0).
The problem can be modeled in GAMS as follows:
Scalar
om / 1 /;
Variable Z Objective;
Positive Variables X1, X2;
Model sc / all /;
As introduced before we start with a core model and then add annotations and output handling information. Currently, there
are no stages unlike in the problems with recourse. Observe that we introduced the new keyword chance. The line chance
E1 0.75 specifies that the constraint E1 must hold for at least 75% of all scenarios. We can verify that this requirement has
been enforced by checking in the output file the level value of the constraint e1 l, and seeing the first scenario constraint is
violated at the solution of the chance constrained problem.
Note that the default value of M in the solvers Lindo and DE is 10000. Currently it can only be customized in DE. We could
insert the following five lines before the solve statement to set the value of M to 1000:
Alternatively, the first line could be replaced by placing emp=de on the command line. Note that it is important that optca
and optcr are assigned the appropriate values. The GAMS default for the absolute gap optca is 0 and the default for the
relative gap optcr is 0.1.
Observe that in addition to converting the chance-constraint problem to a MIP using M the solver DE offers two further
options to solve chance-constraint problems: a reformulation using a convex hull and a reformulation using indicator variables
and indicator constraints. The following line indicates that a convex hull with M = 1000 and = 0.00001 is to be used:
ccreform indic
Note that currently only the solver CPLEX supports indicator variables, so the resulting reformulated problem has to be
solved with CPLEX.
Minx cT x
s.t. P(Ax b) p (21)
x 0.
Consider the example (18) from the previous section extended by one constraint, so that we have two decision variables and
two constraints. The random data follow discrete uniform distributions so each scenario is equally likely.
Min x1 + x2
s.t. P(1 x1 + x2 7; 2 x1 + 3x2 12) 0.6, (1 , 2 ) (22)
x1 , x2 0,
where
= {(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3), (4, 1), (4, 2), (4, 3)} (23)
and
1
k = (1 , 2 ) = for all (1 , 2 ) . (24)
12
4 Chance Constraints 465
Note that in this example b is not random and we have 12 scenarios that are all equally likely. The MIP equivalent is given
below:
Min x1 + x2
1
cc1 = 1 k k yk , k = 1, . . . , 12, k = 12
x1 , x2 0
0 cc1 (1 0.6)
yk (0, 1).
Note that the first set of constraints cover the 12 scenarios, where each scenario has two constraints. The other constraints are
similar to those introduced in (20).
The corresponding GAMS model follows.
Scalar
om1 / 1 /
om2 / 1 /;
Variable Z Objective;
Positive Variables X1,X2;
Model sc / all /;
The line chance E1 E2 0.6 specifies that in at least 60% of all scenarios both E1 and E2 must be satisfied at the same time.
There are a total of 12 scenarios, so both constraints must be satisfied in at least 8 (12 0.6 = 8) scenarios. We can verify
466 Stochastic Programming (SP) with EMP
that this requirement has been enforced by checking in the output file the level values of the constraints, i.e. e1 l and e2 l.
Indeed, in the optimal solution both constraints hold in scenarios 4 to 12, so there are 9 scenarios that satisfy both inequalities.
In this section we discuss the general stochastic linear problem with chance constraints assuming that there is no correlation
between the probabilities of the rows of the matrix A:
Minx cT x
s.t. P(Ai x bi ) pi , i = 1, . . . , m (26)
x 0.
Consider the example from the previous section, this time with individual chance constraints and extended by one constraint:
Min x1 + x2
s.t. P(1 x1 + x2 7) 0.75, 1 1 = {1, 2, 3, 4}
P(2 x1 + 3x2 12) 0.6, 2 2 = {1, 2, 3} (27)
P(1 x1 + 2 x2 10) 0.5, (1 , 2 ) 1 2 =
x1 , x2 0.
1
Note that is defined as in (23) above, we have again 12 scenarios each with probability k = 12 . However, in this example
the first inequality must hold in 9 out of 12 scenarios ( 0.75 12 = 9), the second inequality must hold in 8 out of 12
inequalities ( 0.6 12 = 8) and the third inequality must hold in 6 out of 12 scenarios. Note further that we may have four
types of scenarios: scenarios where all constraints are violated, scenarios where two constraints are violated, scenarios where
one constraint is violated and scenarios where all three constraints are satisfied. The only condition is that for each constraint
there is the respective number of scenarios where the constraint is satisfied. Note further that the random data in the third
inequality is a combination of the random data of the first two inequalities. The inequalities for the scenarios are given below:
k=1: 11 = 1, 21 = 1 11 x1 + x2 7
21 x1 + 3x2 12
11 x1 + 21 x2 10
k=2: 12 = 1, 22 = 2 12 x1 + x2 7
22 x1 + 3x2 12
12 x1 + 22 x2 10 (28)
..
.
k = 12 : 112 = 4, 212 = 3 112 x1 + x2 7
212 x1 + 3x2 12
112 x1 + 212 x2 10
4 Chance Constraints 467
Min x1 + x2
1
cc1 = 1 k k y1k , k = 1, . . . , 12, k = 12
1
cc2 = 1 k k y2k , k = 1, . . . , 12, k = 12
1
cc3 = 1 k k y3k , k = 1, . . . , 12, k = 12
x1 , x2 0
0 cc1 (1 0.75)
0 cc2 (1 0.6)
0 cc3 (1 0.5)
ykj (0, 1).
As expected, there are three constraints for every scenario. Note that we introduce three new variables, cc1 , cc2 and cc3 and
three corresponding constraints. Each of the variables has a different range mirroring the different probabilities with which a
constraint may be violated.
The core model of the GAMS code is very similar to the core model with joint chance constraints. We just add the third
inequality:
Observe that every constraint is listed separately with its respective probability. Note that in case one constraint has to be
satisfied in all scenarios (so it is strictly speaking not a chance constraint), then it has to be listed with probability 1.0.
Here is a summary of which constraints are satisfied in which scenarios in the optimal solution:
Observe that all constraints are satisfied in as many scenarios as required. Note that as predicted there are scenarios where all
three constraints are satisfied ( k = 6, 8, 9, 11, 12), scenarios where only two constraints are satisfied ( k = 5, 7, 10), scenarios
where only one constraint is satisfied ( k = 2, 3, 4) and one scenario where all constraints are violated ( k = 1).
Note that in the specification of the chance constraint we added the penalty factor 3. Recall the MIP equivalent (25) of the
problem:
Min z = x1 + x2
s.t. 1x1 + x2 7 M(1 y1 )
1x1 + 3x2 12 M(1 y1 )
..
.
4x1 + x2 7 M(1 y12 ) (31)
3x1 + 3x2 12 M(1 y12 )
1
cc1 = 1 k k yk , k = 1, . . . , 12, k = 12
x1 , x2 0
0 cc1 (1 0.6)
yk (0, 1).
The probability with which the constraints were violated is stored in the variable cc1 . The introduction of the penalty factor
causes cc1 multiplied by the penalty factor to be added to the objective function:
z = x1 + x2 + 3cc1 . (32)
chance E1 0.75 5
chance E2 0.6 6
chance E3 0.5 7
in the emp.info file of the GAMS code for the problem with individual chance constraints (26) trigger the objective function
in the MIP equivalent to become:
Then we replace the chance constraint specification in the emp.info file of the GAMS code as follows:
This addition causes cc1 to be replaced by viol in the MIP equivalent. Thus we have:
1
viol = 1 k yk , k = 1, . . . , 12, k = , viol [0, 0.4]. (35)
k 12
This model is equivalent to the joint chance constraints model with penalty factor 3 with which we started this section.
5 Risk Measures
Risk measures are mechanisms to evaluate the effects of uncertainty in the underlying system on the outcomes of interest.
They can be used to modify the distribution of outcomes. In this section we explore how optimization problems involving
risk measures can be modeled using stochastic programming in GAMS EMP. Specifically, we examine how an investor might
seek to balance expected rewards and the risk of loss when she decides how to allocate assets in a portfolio.
First, we will discuss maximizing the expected value of a portfolio with uncertain returns, then we will introduce the notion
of Value at Risk and consider optimization problems involving this risk measure and finally we will examine optimization
problems involving Conditional Value at Risk and a combination of expected value and Conditional Value at Risk. Other
risk measures could be implemented in future versions of EMP SP. For simplicity of exposition we only describe two-stage
models here. In the examples introduced below the period (0, T ) is the period between investing in a portfolio of assets and
return from this portfolio.
Max E[R]
s.t R = j w jv j
(36)
j wj = 1
w j 0,
where the variable R is the return (and is a function of the random variable v), E[R] the expected return, w j the weight
associated with each asset j and v j is the (random variable) return of each asset j. The weights can also be interpreted as
proportions of the amount to be invested, their sum must be 1. Note that the w j 's are the decision variables in this problem.
We present two different ways to model this problem in GAMS using EMP SP. Both models have two stages: in the first
stage the weights are chosen without knowing which scenario will be realized, in the second stage the 12 scenarios are taken
into account. We start with the part of the code where the data is given. It is named data.inc and incorporated in all models
in this section.
Alias (j,jj);
Parameter
mean(j) mean return
dev(s,j) deviations
covar(j,jj) covariance matrix of returns
totmean total mean return;
Parameter
p(s) probability / #s [1/card(s)] /
v(j) return from assets; v(j) = mean(j);
In the first model we introduce a new variable for the expected return, EV r, and the new keyword ExpectedValue:
$include data.inc
Variables
r value of portfolio under each scenario
w(j) portfolio selection
EV r expected value of r
objective objective variable;
Positive variables w;
Equations
defr return of portfolio
budget budget constraint
obj eq objective eqn;
/ ExpectedValue r EV r
/ stage 2 v defr r
/ stage 1 objective obj eq EV r
/ "jrandvar v(att) v(gmc) v(usx)"
loop(s,
put / p(s) vs(s,"att") vs(s,"gmc") vs(s,"usx"));
putclose emp;
Parameter
s v(s,j) return from assets by scenario /s1.att 1/
s r(s) return from portfolio by scenario;
In the emp file EV r is declared as the ExpectedValueof the random variable r, the objective to be maximized is the expected
return EV r. Note that the new variables EV r and objbelong to stage 1. Since the expected value of r is not scenario
dependent, its value is known in the preceding stage to the resolution of r, namely stage 1. Note that in a 3-stage-problem
with r in the third stage, the expected value of r+will be known with certainty in the second stage.
In the second model the fact that the expected return is being maximized is not stated explicitly but is only implied:
$include data.inc
Variables
r value of portfolio under each scenario
w(j) portfolio selection;
Positive variables w;
Equations
defr return of portfolio
budget budget constraint;
Parameter
s v(s,j) return from assets by scenario /s1.att 1/
s r(s) return from portfolio by scenario;
Observe that the syntax suggests that the return r is maximized (last line). However, r is a random variable so in fact the
expected return is maximized. Note that the statement emp.nd=4 ensures that 4 decimal places are used for the values of
vs in the emp file, the default is 2. Note further that the solver renormalizes the sum of the probabilities to 1 if some input
rounding has occurred.
Both models have the same solution. We prefer the first model since the syntax is more explicit and clearer.
Suppose G(x, ) is a real valued function of the decision vector x and a random data vector and that it denotes the loss
function of a portfolio of assets. We aim to restrict potential losses and so we choose a portfolio composition such that the
loss does exceed a certain threshold ( R) with a probability smaller or equal to , (0, 1), where is small. This
condition can be modeled as a chance constraint (compare section Chance Constraints on chance constraints) and has the
472 Stochastic Programming (SP) with EMP
form
or equivalently,
P(G(x, ) 0) 1 . (38)
Consider the random variable Zx := G(x, ) . For a given value of x, let FZ (z) := P(Z z) be the cumulative distribution
function of Z. Now, the point x satisfies the constraint (37) if and only if FZ (0) 1 . This is equivalent to saying that x
satisfies the constraint (38) if and only if FZ1 (1 ) 0.
The (left-side) quantile FZ1 ( ) is called Value at Risk. It is denoted by VaR (Z), i.e.
Value at Risk as introduced in equation (39) refers to a percentile on the left tail of a distribution. From now on it will be
denoted by VaR (Z). When considering the Value at Risk at the right tail of the distribution typically equals 0.9 or 0.95, it
is denoted by VaR (Z).
Figure 2 illustrates VaR0.05 (Z) where Z is normally distributed with mean = 0.645 and standard deviation = 1.
5 Risk Measures 473
GAMS EMP SP provides the keywords varlo and varup as a convenient alternative to chance constraints to model Value at
Risk. In the example above, the investor might be interested in a strategy that maximizes the threshold at a certain cutoff, say
10% on the left tail of the return curve. Mathematically, the problem can be expressed as follows:
$include data.inc
Scalar
theta relative volume / 0.1 /;
Variables
r value of portfolio under each scenario
w(j) portfolio selection
VaR r value at risk of r
objective objective variable;
Positive variables w;
Equations
defr return of portfolio
budget budget constraint
obj eq objective function;
Parameter
s v(s,j) return from assets by scenario /s1.att 1/
s r(s) return from portfolio by scenario;
Note that the objective equals the Value at Risk at the left tail, denoted by VaR. The line varlo r VaR r theta specifies
that the variable VaR r is the Value at Risk, r is the random variable and the scalar theta is the percentile (in range 0 to 1)
we consider. As in the previous section, the objective, the objective equation and the variable of the objective belong to the
first stage while the equation that handles the random data and all its variables belong to the second stage.
Note that the keyword varlo specifies that we are looking at the left tail of the probability distribution. For the right tail
of the distribution the keyword to be used is varup. The keyword var is identical to varup. Note further that it is only
appropriate to maximize VaR and minimize VaR .
The implementation of the keywords varlo and varup is based on a mixed integer program similar to that described in Section
Single Chance Constraints. Note that these implementations are likely to be hard and/or time consuming to solve. There is an
option that allows the user to customize the big M value in the same manner that was outlined in Section Single Chance
Constraints :
VaRBigM = 500
$offecho
portfolio.optfile=1;
Note that the default value of M is 1000 and currently only the solver DE supports the keywords for VaR.
In another variation on the example above we consider an investor who aims to take into account both, the expected return
and the Value at Risk of the return at a certain threshold . She combines the two risk measures and uses a scalar ( ) as
weight. A mathematical formulation of the problem reads as follows:
where E[R] is the expected value of the return and VaR is VaR at the th percentile.
The GAMS model follows.
$include data.inc
Scalar
theta relative volume / 0.1 /
lambda weight EV versus VaR / 0.2 /;
Variables
r value of portfolio under each scenario
w(j) portfolio selection
VaR r value at risk of r
EV r expected value of r
obj objective variable;
Positive variables w;
Equations
defr return of portfolio
budget budget constraint
defobj convex combination for both risk measures;
The scalar lambda is introduced as a weight in the sum in the objective function and in the emp file both keywords
ExpectedValue and varlo are used.
Concluding this section we present an alternative way to model VaR. The code is identical to the code of the first model on
the model first EV except for the scalar theta and the emp.info file. The modification of the code for this alternative way of
modeling VaR is given below.
Scalar
theta relative volume / 0.1 /;
/ varlo theta
/ stage 2 r defr v
/ "jrandvar v(att) v(gmc) v(usx)"
loop(s, put / p(s) vs(s,"att") vs(s,"gmc") vs(s,"usx"));
putclose emp;
Observe that there is no additional variable for VaR, but the risk measure is simply applied to the objective function.
Z VaR
1
CVaR (G( )) = G( ) p( )d , (43)
where E[R] is the expected value of the return and CVaR is the CVaR at the confidence level .
This problem can be modeled in GAMS by introducing in the emp file a new variable for the conditional value at risk
(CVar r), a scalar to specify the percentage of the worst cases we are interested in (theta) and cvarlo, a new keyword.
$include data.inc
Scalar
theta relative volume / 0.1 /;
Variables
r value of portfolio under each scenario
w(j) portfolio selection
CVaR r conditional value at risk of r
objective objective variable;
Positive variables w;
Equations
defr return of portfolio
budget budget constraint
obj eq objective function;
Parameter
s v(s,j) return from assets by scenario /s1.att 1/
s r(s) return from portfolio by scenario;
Observe that the objective equals the Conditional Value at Risk (the conditional expectation of the left tail, denoted by CVaR).
The line cvarlog r CVaR r theta specifies that the variable CVaR r is the Conditional Value at Risk, r is the random
variable and the scalar theta is the fraction (in range 0 to 1) we consider. As in the previous section, the objective, the
objective equation and the variable of the objective belong to the first stage while the equation that handles the random data
and all its variables belong to the second stage.
Note that the keyword cvarlo specifies that we are looking at the left tail of the probability distribution. For the right tail of
the distribution the keyword to be used is cvarup. The keyword cvar is identical to cvarup. The conditional value of risk
denoting the mean of the right tail of the distribution can be denoted by CVaR and is defined as:
1
Z
CVaR (G( )) = G( ) p( )d . (45)
1 VaR
Note that it is only appropriate to maximize CVaR and minimize CVaR . Furthermore, CVaR is a concave function and so
should only be constrained using e.g.
CVaR
and CVaR is convex, so should only appear in constraints like
CVaR .
In a final variation on the example above we consider an investor who aims to take into account both, the expected return and
the Conditional Value at Risk of the return at a certain threshold . She combines the two risk measures and uses a scalar ( )
to weigh the two summands. A mathematical formulation of the problem reads as follows:
$include data.inc
Scalar
theta relative volume / [1-0.9] /
lambda weight EV versus CVaR / 0.2 /;
Variables
r value of portfolio under each scenario
w(j) portfolio selection
CVaR r conditional value at risk of r
EV r expected value of r
obj objective variable;
Positive variables w;
Equations
defr return of portfolio
budget budget constraint
defobj convex combination for both risk measures;
The scalar lambda is introduced as a weight in the sum in the objective function and in the emp file both keywords
ExpectedValue and cvarlo are used. By decreasing the value of from 1 to 0 we can make the investor increasingly risk
averse.
Concluding this section we present an alternative way to model CVaR. The code is identical to the code of the first model on
page the model first EV except for the scalar theta and the emp.info file. The modification of the code for this alternative
way of modeling CVaR is given below.
Scalar
theta relative volume / 0.1 /;
Observe that there is no additional variable for CVaR, but the risk measure is simply applied to the objective function.
value CVaR . is a scalar that represents the confidence level for the Conditional Value at Risk. There are two
options for the syntax:
cvarup scalar
and
cvarup rv var scalar
In the first option the objective function variable is used, whereas in the second option the random variable used
is named explicitly (rv) and a variable for the value of CVaR is added (var), and scalar is the value of . Note
that the keyword cvar is identical to cvarup which refers to the right tail of the distribution.
ExpectedValue: This keyword is used to state that a variable is the expected
value of a random variable. The syntax is as follows:
ExpectedValue rv var
jrandvar: Jrandvar can be used to define discrete random variables and their joint distribution:
jrandvar rv rv {rv} prob val val {val} {prob val val {val}}
At least two random variables rv are defined and the outcome of those is coupled. The probability of the
outcomes is defined by prob and the corresponding realization for each random variable by val.
randvar: This defines both discrete and parametric random variables:
randvar rv discrete prob val {prob val}
The distribution of discrete random variables is defined by pairs of the probability prob of an outcome and the
corresponding realization val.
randvar rv distr par {par}
A list of all supported parametric distributions can be found in Table Table 2. All possible values for distr and
the related parameters par are listed there.
sample: This allows the user to customize the size of the sample of a random variable from
a continuous distribution and there is also the option to determine the variance reduction method to be used:
sample rv1 [rv2 ... rvn] sampleSize [varRedMethod]
In rv the name of the random variable is given. The sample size of more than one random variable can be
customized simultaneously. In this case the names of the random variables are listed. sampleSize is a number,
namely the desired size of the sample and varRedGroup is optional. For more details about variance reduction
methods see section Sampling and in addition, please consult the LINDO manual.
Note: Without a valid LINDO license this is limited to the Normal and Binomial distributions with a maximum
sample size of 10.
setSeed: This sets the seed for the random number generator of the sampling routines called
using the sample keyword. If setSeed is used in the emp.info file, the seed is set once before we generate all
samples.
setSeed seed
Note: A valid LINDO license is required to use this.
stage: Random variables (rv), equations (equ) and variables (var) are assigned to non-default stages like this:
stage stageNo rv | equ | var {rv | equ | var}
StageNo defines the stage number. The default stage for all random variables, equations and variables not
mentioned with the stage keyword is 1, except for the objective equation. The default for the objective equation
is the highest stage mentioned. Note that the objective variable is in stage 1.
varlo: This keyword assigns a variable to have the value VaR ,
where is a scalar that represents the percentile of the Value at Risk. There are two options for the syntax:
7 More on scenarios and output extraction 479
varlo scalar
and
varlo rv var scalar
In the first option the objective function variable is used, whereas in the second option the random variable used
is named explicitly rv and a variable for the value of VaR is added (var), and the scalar is the value of .
varup: This keyword assigns a variable to have the value VaR ,
where is a scalar that represents the percentile of the Value at Risk. For VaR typically equals 0.95 or 0.9.
There are two options for the syntax:
varup scalar and varup rv var scalar
In the first option the objective function variable is used, whereas in the second option the random variable used
is named explicitly (rv) and a variable for the value of VaR is added (var), and the scalar is the value of . Note
that the keyword var is identical to varup which refers to the right tail of the distribution.
At the moment four GAMS solvers can be used to solve SP models in the way descibed in this document: DE, DECIS,
LINDO and JAMS. Further information about these solvers can be found in the corresponding solver manuals.
Not all keywords mentioned above are supported by all four solvers. The following table specifies which keywords can be
used with which solvers. The keywords not mentioned in the table are supported by all four solvers.
Table 4: Solver Capabilities
The SP options available for the LINDO solver are documented in the LINDO/LINDOGlobal manual.
In the news vendor model from section Uncertain demand: discrete distribution we can use the following:
The size of the set scen defines the number of scenarios we are willing to store results for. X is a variable for which we want
to access the level and s x is the parameter the levels of x are stored in. Note that s x needs to have the same indices
as x plus the additional index scen in the first position. In the parameter s rep we store the probabilities of the different
scenarios solved.
Chapter 40
MPSGE is a mathematical programming system for general equilibrium analysis which operates as a subsystem within
GAMS. MPSGE is essentially a library of function and Jacobian evaluation routines which facilitates the formulation and
analysis of AGE models. MPSGE simplifies the modeling process and makes AGE modeling accessible to any economist
who is interested in the application of these models. In addition to solving specific modeling problems, the system serves a
didactic role as a structured framework in which to think about general equilibrium systems.
MPSGE requires the GAMS/BASE Module including the MILES MCP solver. Optionally it can use the PATH MCP solver.
1 Introduction
This paper introduces a programming language for economic equilibrium modeling. The paper presents the motivation for the
system, the programming syntax, and three small scale examples. A library of larger models are provided with the program.
The purpose of the paper is to provide a concise introduction to the modeling environment.
MPSGE is a modeling language specially designed for solving Arrow-Debreu economic equilibrium models. (See Rutherford
(1987, 1989).) The name stands for mathematical programming system for general equilibrium. The idea of the MPSGE
program is to provide a transparent and relatively painless way to write down and analyze complicated systems of nonlinear
inequalities. The language is based on nested constant elasticity of substitution utility functions and production functions.
The data requirements for a model include share and elasticity parameters for all the consumers and production sectors
included in the model. These may or may not be calibrated from a consistent benchmark equilibrium dataset.
GAMS, the Generalized Algebraic Modeling System, is a modeling language which was originally developed for linear,
nonlinear and integer programming. This language was developed over 15 years ago by Alex Meeraus when he was working
at the World Bank. (See Brooke, Kendrick and Meeraus (1988).) Since that time, GAMS has been widely applied for
large-scale economic and operations research modeling projects.
MPSGE and GAMS embody different philosophies in their designs. MPSGE is appropriate for a specific class of nonlinear
equations, while GAMS is capable of representing any system of algebraic equations. While GAMS is applicable in several
disciplines, MPSGE is only applicable in the analysis of economic models within a particular domain. The expert knowledge
embodied in MPSGE is of particular use to economists who are interested in the insights provided by formal models but who
are unable to devote many hours to programming. MPSGE provides a structured framework for novice modellers. When used
by experts, MPSGE reduces the setup cost of producing an operational model and the cost of testing alternative specifications.
Prior to the connection with GAMS, the achilles heel of MPSGE had been the process by which input data was translated
into the tabular format of the MPSGE input file. For small models, this translation was not difficult. Given a calibrated
benchmark equilibrium dataset, a couple of hours with a word processor is usually enough time to generate and investigate
a moderately large model. If, however, a model involves several classes of sectors and agents, a wide range of tax instruments
and large tables of input data, the word- processor approach is impossible. When there are many numbers, there are many
opportunities for oversights and typographical errors.
In contrast, the GAMS modeling language is designed for managing large datasets. The use of sets and detached-coefficient
matrix notation makes the GAMS environment very nice for both developing balanced benchmark datasets and for writing
482 MPSGE Models in GAMS
solution reports. For large complicated models, a shortcoming of the GAMS modeling environment lies in the specification of
the nonlinear equations. Economic equilibrium models, particularly those based on complicated functions such as nested
CES, are easier to understand at an abstract level than they are to specify in detail, and the translation of a model from input
data into algebraic relations can be a tedious and error- prone undertaking.
The interface between GAMS and MPSGE combines the strengths of both programs. The system uses GAMS as the front end
and back end to MPSGE facilitating data handling and report writing. The language employs an extended MPSGE syntax
based on GAMS sets, so that model specification is very concise. In addition, the system includes two large-scale solvers,
MILES (Rutherford (1993)) and PATH (Ferris and Dirkse (1993)), which may be used interchangeably. The availability of
two algorithms greatly enhances robustness and reliability.
The remainder of this paper is organized as follows. Section 2 introduces MPSGE input syntax and the GAMS interface using
a small two-sector model of taxation. Section 3 extends the 2x2 model to illustrate how the software is used to perform
equal-yield (differential) tax policy analysis and to analyze tax reform in a model with endogenous taxation. Section 4
provides a brief summary and conclusion. The paper introduces language features largely through example. Details on
language syntax and program structure are provided in two appendices. Appendix A provides a complete statement of
MPSGE syntax and a summary of differences with the original (1989) language. Appendix B provides an overview of the
modeling environment and the structure of GAMS input files which employ MPSGE.
Before proceeding, both to placate impatient readers and to provide some hands-on experience for novices, I recommend that
readers install the GAMS system, then retrieve and process the library file THREEMGE which contains three MPSGE models
(HARBERGER, SHOVEN and SAMUELSON). Two commands to retrieve and run these models:
gamslib threemge
gams threemge
After having processed this file, print the listing files (THREEMGE.LST) for reference.
2 A Mathematical Introduction
Mathiesen (1985) demonstrated that an Arrow-Debreu general economic equilibrium model could be formulated and
efficiently solved as a complementarity problem. Mathiesen's formulation may be posed in terms of three sets of central
variables:
p = a non-negative n-vector of commodity prices including all final goods, intermediate goods and primary
factors of production;
y = a non-negative m-vector of activity levels for constant returns to scale production sectors in the economy;
and
M = an h-vector of income levels, one for each household in the model, including any government entities.
An equilibrium in these variables satisfies a system of three classes of nonlinear inequalities.
Zero Profit
The first class of constraint requires that in equilibrium no producer earns an excess profit, i.e. the value of inputs per unit
activity must be equal to or greater than the value of outputs. This can be written in compact form as:
and
where f and g are the associated production functions characterizing feasible input and output. For example, if we have:
f (x) = i xii i i = 1, i 0
and
g(y) = maxi yii i 0
Market Clearance
The second class of equilibrium conditions is that at equilibrium prices and activity levels, the supply of any commodity must
balance or exceed excess demand by consumers. We can express these conditions as:
j (p)
yi + ih dih (p, Mh )
j pi h h
in which the first sum, by Shepard's lemma, represents the net supply of good i by the constant-returns to scale production
sectors, the second sum represents the aggregate initial endowment of good i by households, and the sum on the right-hand-
side represents aggregate final demand for good i by households, given market prices p and household income levels M.
Final demand are derived from budget-constrained utility maximization:
Mh = pi ih
i
We always work with utility functions which exhibit non-satiation, so Walras' law will always hold:
pi dih = Mh = pi ih
i i
Aggregating market clearance conditions using equilibrium prices and the zero profit conditions using equilibrium activity
levels, it then follows that:
y j j (p) = 0
j
or
y j j (p) = 0 j
Furthermore, it follows that:
j (p)
pi j yi pi + h ih h dih (p, Mh ) = 0 i
In other words, complementary slackness is a feature of the equilibrium allocation even though it is not imposed as an
equilibrium condition, per-se. This means that in equilibrium, an production activity which is operated makes zero profit and
any production activity which earns a negative net return is idle. Likewise, any commodity which commands a positive price
has a balance between aggregate supply and demand, and any commodity in excess supply has an equilibrium price of zero.
484 MPSGE Models in GAMS
Sectors Consumers
------------------------------------
X Y OWNERS WORKERS GOVT
------------------------------------
PX 100 -20 -30 -50
PY -10 80 -40 -30
PK -20 -40 60
PL -50 -10 100 -40
------------------------------------
TRNS 10 20 -30
TK -20 -10 30
------------------------------------
The input data is presented in the form of a balanced matrix, the entries in which represent the value of economic transactions
in a given period (typically one year). Social accounting matrices (SAMs) can be quite detailed in their representation of an
economy, and they are also quite flexible. All sorts of inter-account taxes, subsidies and transfers can be represented through
an appropriate definition of the accounts.
Traditionally, a SAM is square with an exact correspondence between rows and columns. (For an introduction, see Pyatt
and Round, Social Accounting Matrices: A Basis for Planning, The World Bank, 1985.) The numbers which appear in a
conventional SAM are typically positive, apart from very special circumstances, whereas the rectangular SAM displayed in
Table 1 follows a sign convention wherein supplies or receipts are represented by positive numbers and demands or payments
are represented by negative numbers. Internal consistency of a rectangular SAM implies that row sums and column sums are
zero. This means that supply equals demand for all goods and factors, tax payments equal tax receipts, there are no excess
profits in production, the value of each household expenditure equals the value of factor income plus transfers, and the value
of government tax revenue equals the value of transfers to households.
With simple MPSGE models, it is convenient to use a rectangular SAM format. This format emphasizes how the MPSGE
program structure is connected to the benchmark data. In the rectangular SAM, we have one row for every market (traded
commodity). In the present model, there are four markets, for goods X and Y and factors L and K.
There are two types of columns in the rectangular SAM, corresponding to production sectors and consumers. In the present
model, there are two production sectors ( X and Y ) and three consumers (OWNERS, WORKERS and GOVT).
Data Entry in GAMS
3 A small example: Harberger 485
Consider a generalized version of the model in which the set of production sectors be denoted S (here, S = {X,Y } ). Let the set
of goods be G. Production sectors are mapped one-to-one with the goods, so we see that sets S and G are in fact the same set.
Let F denote the set of primary factors (here, F = L, K), and let H denote the set of households (here H={OWNER,WORKER}).
Now that we have identified the underlying sets, we may interpret the input matrix as a set of parameters with which we can
easily specify the benchmark equilibrium. (See Table 2.) It is quite common to begin a general equilibrium modeling project
with a large input-output table or social accounting matrix which may then be mapped onto a number of submatrices, each of
which is dimensioned according to the underlying sets used in the model.
Sectors Consumers
------------------------------------------
(S) Households(H) Government
------------------------------------------
Goods Markets (G): A(G,S)-B(G,S) -C(G,H)
Factor Markets (F): -FD(F,S) E(F,H)-D(F,H)
Capital taxes: -T("K",S) GREV
Transfers: TRN(H) -GREV
The GAMS specification of benchmark data is presented in Table 3 which begins with a statement of the underlying sets
(G, F, H). The statement "ALIAS (S,G)"; simply says that S and G both reference X,Y . Thereafter follows the social
accounting data table and declarations for the various submatrices. The parameters ELAS() and ESUB() are elasticities (free
parameters) which can be chosen independently from the benchmark accounts. The parameters T Fand PF are calibrated
tax and reference price arrays which are computed given benchmark factor and tax payments. (In this model, average and
marginal tax rates are not distinguished, so the benchmark marginal tax rate is simply the tax payment divided by the net
factor income.)
A general equilibrium model determines only relative prices. For purposes of reporting or constructing value-indices, we use
Laspeyres quantity index, THETA(G), the elements of which correspond to shares of aggregate consumer expenditure in the
benchmark period.
Table 3: Data Specification in GAMS for the 2x2 Model Harberger
ALIAS (S,G);
PARAMETER
A(S) BENCHMARK OUTPUT
B(G,S) USE MATRIX (GOODS INPUTS BY SECTOR)
C(G,H) HOUSEHOLD DEMAND
FD(F,S) FACTOR DEMAND BY SECTOR
E(F,H) FACTOR ENDOWMENTS
D(F,H) FACTOR DEMAND BY HOUSEHOLDS
T(F,S) TAX PAYMENT BY FACTOR BY SECTOR
TRN(H) TRANSFER REVENUE
486 MPSGE Models in GAMS
A(S) = SAM(S,S);
B(G,S) = MAX(0, -SAM(G,S));
C(G,H) = -SAM(G,H);
FD(F,S) = -SAM(F,S);
E(F,H) = SAM(F,H);
D(F,H) = 0;
TRN(H) = SAM("TRN",H);
T("K",S) = -SAM("TK",S);
E("L","WORKER") = 100;
D("L","WORKER") = 40;
ELAS(S) = 1;
ESUB(H) = 0.5;
Model Specification
The MPSGE description of this model is shown in Table 4. Declarations following the $MODEL statement indicate that the
model involves one class of production activities ( AL(S)), three classes of commodities ( P(G), W (F) and PT ), and two
types of consumers, private consumers ( RA(H)), and a government consumer (GOVT).
One $PROD: block describes the single class of production activities, and two $DEMAND: blocks characterize endowments
and preferences for the two classes of consumers.
Consider the records associated with production sector AL(S). The entries on the first line of a $PROD: block are elasticity
values. The s:0 field indicates that the top-level elasticity of substitution between inputs is zero (Leontief). The entry
"a:ELAS(S)" indicates that inputs identified as belonging to the "a:" aggregate trade off with an elasticity of substitution
ELAS(S) (at the second level of the production function). In these production functions, the primary factors (W (F)) are
identified as entering in the a : aggregate.
TABLE 4: MPSGE Model Specification and Benchmark Replication
$ONTEXT
$MODEL:HARBERGER
$SECTORS:
3 A small example: Harberger 487
AL(S)
$COMMODITIES:
P(G) W(F) PT
$CONSUMERS:
RA(H) GOVT
$DEMAND:GOVT
D:PT Q:GREV
$REPORT:
V:CD(G,H) D:P(G) DEMAND:RA(H)
V:DF(F,H) D:W(F) DEMAND:RA(H)
V:EMPLOY(S) I:W("L") PROD:AL(S)
V:WLF(H) W:RA(H)
$OFFTEXT
* ------------------------------------------------------------------
* SECTION (iii) BENCHMARK REPLICATION
HARBERGER.ITERLIM = 0;
$INCLUDE HARBERGER.GEN
SOLVE HARBERGER USING MCP;
ABORT$(ABS(HARBERGER.OBJVAL) GT 1.E-4)
"*** HARBERGER benchmark does not calibrate.";
HARBERGER.ITERLIM = 1000;
The records within a $PROD: block begin with "O:" or "I:". An "O:" indicates an output and an "I:" represents an input.
In both types of records, "Q:" is a quantity field indicating a reference input or output level of the named commodity. A
"P:" signifies a reference price field. This price is measured as a user cost, gross of applicable taxes. The default values for
reference price and reference quantity are both unity (i.e., a value of 1 is installed if a P: or Q: field is missing).
The A: and T: fields in a $PROD: block indicate tax agent and ad-valorem tax rate, respectively. The tax agent is specified
before the tax rate. A single input or output coefficient may have two or more taxes applied. Consumers are treated
symmetrically, and there is thus no restriction on the consumer to whom the tax is paid. Typically, however, one consumer is
associated with the government.
To better understand the relationship between reference prices and tax rate specification, consider inputs of W.K to sector
AL.X in this model. The benchmark payment to capital in the X sector is 20 and the tax payment is 20. Hence the ad-valorem
488 MPSGE Models in GAMS
tax rate in the benchmark equilibrium is 100% ( T : 1), and the reference price of capital, market price of unity times
(1 + 100%), is 2 (P : 2). If in a counterfactual experiment the tax rate on capital inputs to sector X is altered, this will change
the T : field but it will not change the P : field. Q : and P : characterize a reference equilibrium point, and these are therefore
unaffected by subsequent changes in the exogenous parameters.
It is important to remember that the $PROD:AL(S) block represents as many individual production functions as there are
elements in set S (two in this case). Within the $PROD:AL(S) block, inputs refer to sets G and F , while the output coefficient,
O : P(S), refers only to set S. Sets referenced within a commodity name in an I : or O : field may be sets which are controlled
by the sets referenced in the function itself, in which case only a scalar entry is produced. In $PROD:AL(S) there are only
outputs of commodity S in sector S.
The first line of a $DEMAND block also contains fields (e.g.,s:, a:, b: etc.) which represent elasticities of substitution.
The subsequent records may begin with either an E : field or a D : field. These, respectively, represent commodity endowments
and demands. In the demand fields, the P : and Q : entries are interpreted as reference price and reference quantity, analogous
to the input fields in a $PROD block. Ad-valorem taxes may not be applied on final demands, so that if consumption taxes are
to be applied in a model they must be levied on production activities upstream of the final demand.
The benchmark values for all activity levels and prices are equal to the default value of unity, and therefore we are able
to specify values in the Q : fields directly from the benchmark data. An equivalent model could be specified in which the
benchmark activity levels for AL(S) equal, for example, A(S,S). This would then require rescaling the input and output
coefficients for those sectors, and it would not necessarily be helpful, because in a scaled model it is more difficult to verify
consistency of the benchmark accounts and MPSGE input file. Furthermore, for numerical reasons it is advisable to scale
equilibrium values for the central variables to be close to unity.
Government transfers to households are accomplished through the use of an artificial commodity (PT). The government
is identified as the agent who receives all tax revenue (see the A:GOVT entry in both of the $PROD: blocks). Commodity
PT is the only commodity on which GOVT spends this income, hence government tax revenue is divided between the two
households in proportion to their endowments of the artificial good. In order to scale units so that the benchmark price of PT
is unity, the $30 of government tax revenue chases 10 units of PT assigned to OWNER and 20 units assigned to WORKER.
(See values for TRN(H) in Table 3.)
The $REPORT section of the input file requests the solution system to return values for inputs, outputs, final demands or
welfare indices at the equilibrium. Only those items which are requested will be written to the solution file. Each record in
the report block begins with a V : (variable name) field. These names must be distinct from all other names in the model. The
second field of the report record must have one of the labels I :, O : or D : followed by a commodity name, or the label W :
followed by a consumer name. The third field's label must be "PROD:" in an I : or O : record, and it must be "DEMAND:" if it
is a D: record.
An algebraic formulation of the Harberger model is provided for the interested reader.
MPSGE Formulation: Key Ideas
There are two points regarding the MPSGE function format which are important yet easily misunderstood by new users:
1. The elasticities together with the reference quantities and reference prices of inputs and outputs completely characterize
the underlying nested CES functions. No other data fields in the $PROD: block alters the technology. If, for example, a
tax rate changes as part of a counter-factual experiment, this has no effect on the reference price. The value in the P :
field depends on the benchmark value of the T : field if the model has been calibrated, but subsequent changes in T :
do not change the underlying technology.
2. Tax rates are interpreted differently for inputs and outputs. The tax rate on inputs is specified on a net basis, while the
tax rate on outputs is specified on a gross basis. That is, the user cost of an input with market price p subject to an
ad-valorem tax at rate t is p(1 + t), while the user cost of an output subject to an ad-valorem tax at rate t is p(1 t). (A
tax increases the producer cost of inputs and decreases the producer value of outputs.)
MPSGE provides a limited number of economic components with which complex models can be constructed. There are some
models which lie outside the MPSGE domain, but in many cases it is possible to recast the equilibrium structure in order to
produce an MPSGE model which is logically equivalent to the original model - usually after having introduced some sort of
artificial commodity or consumer. In the present model, the use of commodity PT to allocate government revenue between
households provides a fairly typical example of how this can be done. In the process of making such a transformation, one
often gains a meaningful economic insight.
3 A small example: Harberger 489
---- VAR AL
---- VAR P
---- VAR W
---- VAR RA
---- VAR CD
---- VAR DF
* ------------------------------------------------------------------
* SECTION (iv) COUNTER-FACTUAL SPECIFICATION AND SOLUTION:
LOOP(SC,
TF(F,S) = TAXRATE(F,S,SC);
$INCLUDE HARBERGER.GEN
4 Alternative models: Shoven and Samuelson 491
* ------------------------------------------------------------------
* SECTION (v) REPORT WRITING:
0 $MODEL: SHOVEN
1
2 $SECTORS:
3 AL(S)
4
5 $COMMODITIES:
6 P(G) W(F) PT
7
8 $CONSUMERS:
9 RA(H) GOVT
10
11 $AUXILIARY:
12 TAU
13
14 $REPORT:
15 V:CD(G,H) D:P(G) DEMAND:RA(H)
16 V:DF(F,H) D:W(F) DEMAND:RA(H)
17 V:EMPLOY(S) I:W("L") PROD:AL(S)
18 V:WLF(H) W:RA(H)
19
20 $PROD:AL(S) s:0 a:ELAS(S)
21 O:P(G) Q:A(G,S)
22 I:P(G) Q:B(G,S)
23 I:W(F) Q:FD(F,S) P:PF(F,S)
24 + A:GOVT N:TAU$TF(F,S) M:TF(F,S)$TF(F,S) a:
25
26 $DEMAND:RA(H) s:1 a:ESUB(H)
27 D:P(G) Q:C(G,H) a:
28 D:W(F) Q:D(F,H)
29 E:W(F) Q:E(F,H)
30 E:PT Q:TRN(H)
31
32 $DEMAND:GOVT
33 D:PT Q:GREV
34
35 $CONSTRAINT:TAU
36 PT =G= SUM(G, THETA(G) * P(G));
37
38 $OFFTEXT
An algebraic formulation of the Shoven model is provided for the interested reader.
Public Goods and Endogenous Taxation
Consider a final extension of the 2x2 model in which tax revenue funds a pure public good. Model SAMUELSON presented
in Table 8. This model illustrates one of several ways that public goods can be modelled in MPSGE. Here the level of
public provision is determined by a Samuelson-condition equating the sum of individual marginal rates of substitution
(marginal benefit) with the marginal rate of transformation (marginal cost). Unlike the equal yield formulation, the tax
revenues collected by GOVTare not returned lump-sum but are instead used to finance provision of a pure public good. This
representation of government has not been widely adopted in the CGE literature, perhaps because of the difficulties involved
in specifying preferences for public goods.
The relevant characteristic of a pure public good entering final demand is that each consumer owns the same quantity.
Agents' attitudes toward public goods differ, and because there is no market, agents' valuations of the public good will also
differ. In an MPSGE model, the separate valuations are accommodated through the introduction of personalized markets
for public good - one market for each consumer. In the model, consumer expenditure encompasses both private and public
purchases, and consumer income encompasses both private and public endowments. An individual is endowed with a
4 Alternative models: Shoven and Samuelson 493
quantity of her own version of the public good determined by the level of public expenditures. An increase in taxes, to the
extent that it increases tax revenue, will increase the level of public provision.
In this model, the structure of relative factor taxes is exogenous but the aggregate level of taxes is not. Tax rates are scaled up
or down so that the sum of individual valuations of the public good (the marginal benefit) equals the cost of supply of the
public good (the direct marginal cost).
Consider features of model SAMUELSON which do not appear in SHOVEN:
1. There are new commodities PG and VG(H). The first of these represents the direct marginal cost of public output
from sector GP, a Leontief technology which converts private goods inputs into the public good. For the SAMUELSON
structure, all government revenues apply to purchases of the public good (observe that the only good demanded by
consumer GOVTis PG ). The prices VG(H) represent the individual consumer valuations of the public good. Commodity
VG(H) appears only in the endowments and demands of consumer RA(H). The endowment record for VG(H) includes
a quantity V(H) which is the benchmark valuation of the public good by agent H.
2. There are two auxiliary variables. TAU has the same interpretation as in the SHOVEN, determining the aggregate tax
level. Auxiliary variable LGP is a rationing instrument representing an index of the level of public goods provision,
scale to equal 1 in the benchmark. Consumer RA(H) thus is endowed with a quantity of VG(H) given by V(H) LGP .
3. The constraint for TAU in SAMUELSON differs from the TAU constraint in SHOVEN. Here the constraint repre-
sents the Samuelson condition, equating the marginal cost (PGGREV) and the sum of individuals' marginal benefit
(SUM(H,VG(H)V(H))). The constraint for LGP simply assigns LGP equal to the sector GP activity level. (The LGP
variable and constraint are only needed because the R: field only accepts auxiliary variables.)
0 $MODEL: SAMUELSON
1
2 $SECTORS:
3 AL(S) GP
4
5 $COMMODITIES:
6 P(G) W(F) PG VG(H)
7
8 $CONSUMERS:
9 RA(H) GOVT
10
11 $AUXILIARY:
12 TAU LGP
13
14 $REPORT:
15 V:CD(G,H) D:P(G) DEMAND:RA(H)
16 V:DF(F,H) D:W(F) DEMAND:RA(H)
17 V:EMPLOY(S) I:W("L") PROD:AL(S)
18 V:WLF(H) W:RA(H)
19
20 $PROD:AL(S) s:0 a:ELAS(S)
21 O:P(G) Q:A(G,S)
22 I:P(G) Q:B(G,S)
23 I:W(F) Q:FD(F,S) P:PF(F,S)
24 + A:GOVT N:TAU$TF(F,S) M:TF(F,S)$TF(F,S) a:
25
26 $PROD:GP s:0
27 O:PG Q:GREV
28 I:P(G) Q:GD(G)
494 MPSGE Models in GAMS
29
30 $DEMAND:RA(H) s:1 a:ESUB(H)
31 D:P(G) Q:C(G,H) a:
32 D:W(F) Q:D(F,H)
33 D:VG(H) Q:V(H)
34 E:VG(H) Q:V(H) R:LGP
35 E:W(F) Q:E(F,H)
36
37 $DEMAND:GOVT
38 D:PG Q:GREV
39
40 $CONSTRAINT:TAU
41 GREV * PG =G= SUM(H, V(H) * VG(H));
42
43 $CONSTRAINT:LGP
44 LGP =G= GP;
45
46 $OFFTEXT
An algebraic formulation of the Samuelson model is provided for the interested reader.
Comparing Model Results
Although the foregoing discussion has focused on the nuances of MPSGE model syntax, but there are many interesting
economic questions which can be addressed using even small-scale models such as tho ones described here. Consider the
output listing from parameter REPORT is displayed in Table 9. It is perhaps surprising to note that none of the uniform tax
structures represents a Pareto-superior choice compared to the benchmark tax structure. Furthermore, from the standpoint of
aggregate welfare ("WELFARE.TOTAL" = income-weighted sum of individual EV's), only the uniform capital tax represents
an improvement.
Table 9: Numerical Results from Alternative Models
INDEX 1 = HARBERGER
K L VA
REVENUE._ 3.9 -38.9 -0.8
TAXRATE._ 50.0 50.0 25.0
WELFARE.OWNER 1.9 42.4 18.5
WELFARE.WORKER -0.1 -26.8 -10.9
WELFARE.TOTAL 0.6 -1.3 -3.48143E-2
EMPLOY .X -5.3 -6.9 -8.4
EMPLOY .Y 20.5 34.4 22.1
PRICE .X -10.4 -11.2 -10.3
PRICE .Y 11.8 12.8 11.8
PRICE .K 3.9 59.5 24.5
PRICE .L -4.7 -38.9 -23.5
OUTPUT .X 3.6 -1.0 0.4
OUTPUT .Y -3.7 2.0 -2.0
INDEX 1 = SHOVEN
K L VA
TAXRATE._ 47.1 134.2 25.3
WELFARE.OWNER 3.3 40.2 18.3
WELFARE.WORKER -1.0 -29.2 -10.8
WELFARE.TOTAL 0.6 -3.6 -3.51710E-2
EMPLOY .X -5.0 -19.7 -8.5
EMPLOY .Y 21.5 12.1 21.9
PRICE .X -10.4 -9.0 -10.3
PRICE .Y 11.9 10.2 11.8
5 Summary 495
INDEX 1 = SAMUELSON
K L VA
REVENUE ._ -1.4 -14.5 -6.7
TAXRATE ._ 45.7 88.8 22.8
WELFARE .OWNER 4.7 43.9 21.1
WELFARE .WORKER -2.0 -31.4 -12.9
WELFARE .TOTAL 0.5 -3.7 -0.4
EMPLOY .X -4.9 -7.5 -5.9
EMPLOY .Y 24.5 37.5 29.7
PRICE .X -10.7 -11.3 -10.9
PRICE .Y 12.2 13.0 12.5
PRICE .K 7.8 60.3 29.0
PRICE .L -6.0 -51.8 -24.5
OUTPUT .X 3.0 -2.2 0.9
OUTPUT .Y -2.3 3.3 -2.58148E-2
PROVISION._ -0.8 -13.9 -6.1
5 Summary
This paper has provided an introduction to a new GAMS subsystem for applied general modeling. This extension of GAMS
accomodates a tabular representation of highly nonlinear cost and expenditure functions through which model specification is
concise and transparent. The paper has presented three small examples which illustrate the programming environment and
its application to traditional economic issues in public finance for which applied general equilibrium analysis is a standard
tool. Further work is underway in the development and evaluation of solution algorithms for applied general equilibrium
models implemented within GAMS/MPSGE. In addition to providing a convenient framework for model- builders, the
new GAMS/MPSGE system also simplifies the implementation and testing of algorithms for complementarity problems.
Information on the relative effectiveness of different solution strategies should prove quite helpful to users who are using the
system to solve very large systems of nonlinear equations.
6 References
Ballard and Fullerton (1992) Distortionary Taxes and the Provision of Public Goods, Journal of Economic Perspec-
tives 6(3).
Brooke, T., D. Kendrick and A. Meeraus (1988) GAMS: A User's Guide, The Scientific Press, Redwood City,
California.
Rutherford, T. (1993) MILES: A Mixed Inequality and nonLinear Equation Solver, Working Paper, Department of
Economics, University of Colorado.
Rutherford, T. (1987) Applied General Equilibrium Modeling, Ph.D. thesis, Department of Operations Research,
Stanford University.
Rutherford, T.F. (1989) General Equilibrium Modeling with <cite>MPSGE</cite>, The University of Western
Ontario.
Shoven, J. and J. Whalley (1984) Applied General Equilibrium Models of Taxation and International Trade: Introduc-
tion and Survey, Journal of Economic Literature 22, 1007-1051.
Thompson, G. and S. Thore (1992) Computational Economics , Scientific Press, Redwood City, California.
496 MPSGE Models in GAMS
Keywords Description
$ONTEXT Indicate the beginning of a GAMS comment block contain-
ing an MPSGE model.
$MODEL:model name model name must be a legitimate file name. This name
is subsequently used to form MODEL NAME.GEN (this file
name must be upper case when running under UNIX).
$SECTORS:, $COMMODITIES:, $AUXILIARY:, Four keywords define variables which are used in the
$CONSUMERS: model. Entries in these blocks share the same syntax. The
$AUXILIARY block is only used in models with side con-
straints and endogenous taxes or rationed endowments.
$PROD:sector Production functions must be specified for each production
sector in the model.
$DEMAND:consumer Demand functions must be specified for every consumer in
the model. General structure is the same as for production
functions above.
$CONSTRAINT:auxiliary Specifies a side constraint to be associated with a specified
auxiliary variable.
$REPORT: Identifies the set of additional variables to be calculated.
These include outputs and inputs by sector and demands by
individual consumers.
$OFFTEXT Indicates the end of model specification.
Variable Declarations
There are four classes of variables within an MPSGE model: activity levels for production sectors, prices for commodities,
income levels for consumers and level values for auxiliary variables. These classes of variables are distinguished in order to
permit additional semantic checking by the MPSGE preprocessor. For example, if P has been declared as a price (within the
$COMMODITIES: block), then the preprocessor would report an error if it encountered "$PROD:P". |
The $SECTORS:, $COMMODITIES:, $CONSUMERS: and $AUXILIARY: blocks contain implicit GAMS variable declarations in
which the index sets must be specified in the GAMS program above and the variable names must be distinct from all other
symbols in the GAMS program. One or more variables may be declared per line separated by one or more spaces.
$SECTORS:
Y(R,T) ! Output in region R in period T
K(T) ! "Aggregate capital stock, period T"
In these declarations, the trailing comments (signified by !) are interpreted as variable name descriptors which subsequently
appear in the solution listing.
The equivalent GAMS declaration for these variables would be:
7 Appendix A: Language Syntax 497
As with the usual GAMS syntax, when a variable descriptor contains a punctuation symbol such as ,, it is required to
enclosed in quotes.
$SECTORS:
X(R,T)$(X0(R) GT 0)
Here, the GAMS conditional operator $ is used to restrict the domain of the variable X. The expression following the dollar
sign is passed through to the GAMS compiler and must conform to GAMS syntax rules.
$SECTORS:
X Y(R)$Y0(R) Z ! Descriptor for Z
W(G,R,T) ! Descriptor for W
More than one symbol may appear on a single line. The descriptor only applies to the last one.
All MPSGE variables must be declared. When multidimensional variables are specified, they must be declared explicitly -
declarations like X() are not permitted. Two further restrictions are that the sets used in the declaration must be static rather
than dynamic, and any variable which is declared must be used in the model. There is a simple way to work around these
restrictions. Let me illustrate with an example. Suppose that in a model the set of production sectors AL is employed for all
elements of a static set S which satisfy a particular condition, for example BMX(S) not equal to 0. This would require that AL
be declared as follows:
$SECTORS:
AL(S)$BMX(S)
In this context, the symbol $ is used as an exception operator which should be read as such that. In this case, we have
generated one AL sector for each element of the set S for which BMX(S) is nonzero.
Function Declarations
Functional declarations characterize nested CES functions which characterize both preferences and technology. The former
are written within a $DEMAND: block and the latter within a $PROD: block. Tax entries may appear within a $PROD: block but
not within a $DEMAND: block, otherwise the syntax is nearly identical. The syntax for these blocks will be described through
a sequence of examples:
$PROD:Y(R) s:1
O:P(R) Q:Y0(R)
I:W(F,R) Q:FD0(F,R)
This block characterizes a Cobb-Douglas production function in which the elasticity of substitution between inputs is one -
"s:1" in the first line which sets a top level substitution elasticity equal to unity. Variable Y(R) is an activity level declared
within the $SECTORS: block. Variables P(R) and W(F,R) are prices declared within the $COMMODITIES: block. The O:
label indicates an output, and the I: prefix indicates an input. The Q: fields in both records represent reference quantities.
Y0(R) and FD0(F,R) must be GAMS parameters defined previously in the program.
The keyword line specifies three separate elasticities related to this function. ESUB(R) is the top level elasticity of substitution.
There are two sub-nests in the function. Nest a: is a Leontief nest (in which the compensated elasticity is zero). The elasticity
of subtitution in nest b: is one-fifth of the top level elasticity.
498 MPSGE Models in GAMS
In the function specification, commodities PY(G) (one input for each element of set G) enter in fixed proportions. Commodities
PL and PK enter in nest b.
If this function has been specified using a balance benchmark dataset with reference prices equal to unity, then the following
identity should be satisfied:
In this function, we have two new ideas. The first is the use of a reference price denoted by "P:". This entry indicates that
the function should be calibrate to a reference point where individual input prices (gross of tax) equal PF(F,S). If P: does
not appear, prices of one are assumed.
The second new idea here is that taxes may be levied on production inputs. The A: label identifies the name of the tax agent
(a $CONSUMER:). The T: label identifies the ad-valorem tax rate.
$DEMAND:RA(R)$RA0(R) s:1
E:PL Q:LE(R)
D:P(G)$DG(G) Q:D0(G,R)$DD(G,R) P:P0(G,R)
This function specification demonstrates the use of conditionals. This function is only generated when RA0(R) is nonzero.
The demands D: for a particular element of set G are suppressed entirely when DG(G) equals 0. The Q: field also has an
exception operator, so that the default value for Q: (unity) is applied when DD(G,R) equals zero.
This example is somewhat artificial, but it illustrates the distinction between how exception operators affect lead entries
(I:, O:, D: and E:) and subsequent entries. When an exception is encountered on the lead entry, the entire record may be
suppressed. Exceptions on subsequent entries only applied to a single field.
The valid labels in a function declaration ($PROD: or $DEMAND:) line include:
s: Top level elasticity of substitution between inputs or demands.
t: Elasticity of transformation between outputs in production. (valid only in $PROD blocks)
a:,b:,... Elasticities of substitution in individual input nests.
The recognized labels in an I: or O: line include:
Q: Reference quantity. Default value is 1. When specified, it must be the second entry.
P: Reference price. Default value is 1.
A: Tax revenue agent. Must be followed by a consumer name.
T: Tax rate field identifier. (More than one tax may apply to a single entry.)
N: Endogenous tax. This label must be followed by the name of an auxiliary variable.
M: Endogenous tax multiplier. The advalorem tax rate is the product of the value of the endogenous tax and
this multiplier.
a:,b:,.. Nesting assignments. Only one such label may appear per line.
The valid labels in an E: line include:
Q: Reference quantity
R: Rationing instrument indicating an auxiliary variable.
The valid labels in a D: line include:
Q: Reference quantity
P: Reference price
7 Appendix A: Language Syntax 499
$CONSTRAINT:TAU
G =G= X * Y;
$CONSTRAINT:MU(I)$MU0(I)
The exception applied in this example restricts the equation only to those elements of set I for which MU0(I) is not zero.
Report Declaration
The GAMS interface to MPSGE normally returns level values only for the central variables - those declared within $SECTORS:,
$COMMODITIES:, $CONSUMERS: and $AUXILIARY: sections. An equilibrium determines not only these values, but also levels
of demand and supply by individual sectors and consumers. Given benchmark information, elasticities and the equilibrium
values, all such demands can be computed, but this can be tedious to do by hand. In order to have these values returned by
MPSGE, it is necessary to indicate the name of the variable into which the value is to be returned. The general form is as
follows:
$REPORT:
V:variable name I:commodity PROD:sector
V:variable name O:commodity PROD:sector
V:variable name D:commodity DEMAND:consumer
V:variable name W:consumer
The first row returns an input quantity, the second row returns an output quantity, the third returns a demand quantity, and the
fourth row returns a consumer welfare index. (Note: the level value returned for a consumer variable is an income level,
not a welfare index.)
$REPORT:
V:DL(S) I:PF("L") PROD:Y(S)
V:DK(S) I:PF("K") PROD:Y(S)
V:SX(G,S)$SX0(G,S) O:PX(G) PROD:X(S)
V:D(G,H) D:P(G) DEMAND:RA(H)
V:W(H) W:RA(H)
Note that the $ exception is only meaningful on the first entry. Also notice that the domain of the report variable must
conform to the domain of the subsequent two entries.
Differences between Scalar and Vector MPSGE Syntax
1. $MODEL: statement The $MODEL statement is required in the vector format and it must precede all other statements. A
name which is an acceptable file name prefix must be used. The preprocessor does not begin translation of anMPSGE
model until it encounters a $MODEL statement following an $ONTEXT record. The preprocessor continues to translate
until it reaches an $OFFTEXT statement, skipping blank lines and comment lines identified by a in column 1.
2. Case folding: In the vector syntax, upper and lower case letters are not distinguished. The entire file is processed as
though it were written in upper case. This is not compatible with the earlier version ofMPSGE in which "P" and "p"
were distinct.
500 MPSGE Models in GAMS
3. Distinct names: Names used for variables in theMPSGE model must be distinct from each other as well as from all
other symbols in the GAMS program. If there is a GAMS set or parameter or model named X, then X may not be used to
identify anMPSGE sector or commodity.
4. Tabs:MPSGE fields are free format and tabs are translated to spaces by the preprocessor. Tabs are permitted in GAMS
provided that the compiler is properly configured (under DOS, "TABIN 8" must be inserted in file GAMSPARM.TXT
in the GAMS system directory).
Exception Handling
The GAMS exception operator can be used on virtually any entry in theMPSGE input file. For example, if you want to have
sector X(S) have one production structure for elements S in a subset T(S), you can provide separate production function
declarations as follows:
$PROD:X(S)$T(S)
... ! sector X described for S in T
$PROD:X(S)$(NOT T(S))
... ! sector X described for S not in T.
The preprocessor does not require one and exactly one declaration for each sector. If multiple declarations appear, the later
set of coefficients overwrites the earlier set.
Switches and Debug Output
Run-time tolerances and output switches may be specified within the vector-syntax model specification or using the PUT
facility, they can be written directly to the MPS input file. Output switches control the level of debug output written
by theMPSGE subsystem to the solver status file. Reports provided by $ECHOP, $FUNLOG and $DATECH can be returned
to the listing file by specifying "OPTION SYSOUT=ON;" within the GAMS program prior to the SOLVE statement. The
recognizedMPSGE parameters are:
is a switch for returning all or part of the scalarMPSGE file to the solver status file. In order to have this output printed in the
listing file, enter the GAMS statement "OPTION SYSOUT=ON;" prior to solving the model.
is the smallest price for which price-responsive demand and supply functions are evaluated. If a price is below PEPS, it is
perturbed (set equal to PEPS) prior to the evaluation.
is a switch for evaluating Euler's identity for homogeneous equations. The output is useful for monitoring the numerical
precision of a Jacobian evaluation. When a price or income level is perturbed in a function, the Euler check may fail.
is a switch for checking Walras's law. Like EULCHK, this switch is provided primarily to monitor numerical precision.
When an income level is perturbed, the Walras check may fail.
is a switch to generate a detailed listing of function evaluations for all production sectors and consumers.
FUNLOG triggers a function evaluation report which provides detailed output describing the evaluation of supply and
demand coefficients. The information provide is sufficient that an industrious graduate student should be able to reproduce
the results (given a pencil, paper and slide rule).
The evaluation report has the following headings:
7 Appendix A: Language Syntax 501
Heading Description
T Coefficient type with the following interpretation:
IA Input aggregate
OA Output aggregate
I Input
O Output
D Demand
E Endowment
When $FUNLOG:.TRUE is specified, a complete report of demand and supply coefficients for every production and demand
function in every iteration. Be warned that with large models this can produce an enrmous amount of output!
The following two function evaluation reports are generated in the first iteration in solving case "L" for model HARBERGER:
is a switch to generate a annotated listing of the function and Jacobian evaluation including a complete listing of all the
nonzero coefficients.
MPSGE generates an analytic full first-order Taylor series expansion of the nonlinear equations in every iteration. Nonzero
elements of the Jacobian matrix are passed to the system solver (MILES or PATH) which uses this information in the
direction-finding step of the Newton algorithm. Coefficients are produced with codes which help interpret where they came
from. The following codes are used:
502 MPSGE Models in GAMS
2. Every SOLVE statement for a particular model is preceded by $INCLUDE MODEL.GEN. The GEN file is written by the
preprocessor based on the model structure.
3. Solution values for the cental variables in the MPSGE model and any declared report variables are returned in GAMS
variable level values. Level values for slacks are returned as marginals for the associated variables.
504 MPSGE Models in GAMS
4. The model description follows a format which is a direct extension of the scalar data format. Certain aspects of the
new language, such as case folding, are incompatible with the original MPSGE syntax.
This research supported by the GAMS Applied General Equilibrium Research Fund. The software described here operates
only with GAMS 2.25.085 or later on the PC, shipped in July, 1995. The author remains responsible for any bugs which exist
in this software.
Thomas F. Rutherford, rutherford@colorado.edu Department of Economics University of Colorado
1995 :
1 An Overview
This document describes a mathematical programming system for general equilibrium analysis named MPSGE which
operates as a subsystem to the mathematical programming language GAMS. MPSGE is library of function and Jacobian
evaluation routines which facilitates the formulation and analysis of AGE models. MPSGE simplifies the modeling process
and makes AGE modeling accessible to any economist who is interested in the application of these models. In addition to
solving specific modeling problems, the system serves a didactic role as a structured framework in which to think about
general equilibrium systems.
MPSGE separates the tasks of model formulation and model solution, thereby freeing model builders from the tedious
task of writing model-specific function evaluation subroutines. All features of a particular model are communicated to
GAMS/MPSGE through a tabular input format. To use MPSGE, a user must learn the syntax and conventions of this model
definition language.
The present paper is intended for students who have completed two semesters of study in microeconomics. The purpose of
this presentation is to give students a practical perspective on microeconomic theory. The diligent student who works through
all of the examples provided here should be capable of building small models from scratch to illustrate basic theory. This is
a first step to acquiring a set of useable tools for applied work.
The remainder of this paper is organized as follows. Section The Theory of Consumer Demand review the theory of consumer
demand; section Getting Started provides guidance on the mechanics of numerical modeling, including instructions on how to
install and test the GAMS/MPSGE software; section Modeling Consumer Demand introduces the modeling framework with
three models illustrating the representation of consumer demand within the MPSGE language. Section The Pure Exchange
Model reviews the pure exchange model, and section Modeling Pure Exchange with MPSGE presents two MPSGE models of
exchange. Each of the model- oriented sections present exercises based on the models which give students a chance to work
through the material on their own. Additional introductory examples for self-study can be found in the Markusen library
as well as in the GAMS model library (look for models with names ending in MGE).
The level of presentation and diagrammatic exposition adopted here is based on Hal Varian's undergraduate microeconomics
506 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
textbook ( Intermediate Microeconomics: A Modern Approach, Third Edition, W. W. Norton & Company, Inc., 1993).
The ultimate objective of this piece is to remind students of some theory which they have already seen and illustrate how
these ideas can be used to build numerical models using GAMS with MPSGE. It is not my intention to provide a graduate
level presentation of this material. So far as possible, I have avoided calculus and even algebra. The objective here is to
demonstrate that what matters are economic ideas. With the proper tools, it is possible to do concrete economic modeling
without a lot of mathematical formalism.
Preferences are relationships between alternative consumption bundles. These can be represented graphically using
indifference curves, as illustrated in Figure 1. Focusing now on the preferences of a single consumer, the indifference curve
is a line which connects all combinations of two goods x and y between which our consumer is indifferent. As this curve is
drawn, we have represented an agent with well-behaved preferences: at any allocation, more is better (monotonicity), and
averages are preferred to extremes (convexity). Exactly one such indifference curve goes through each positive combination
of x and y. Higher indifference curves lie to the north-east.
If we wish to characterize an agent's preferences, the marginal rate of substitution (MRS) is a useful point of reference. At
a given combination of x and y, the marginal rate of substitution is the slope of the associated indifference curve. As drawn,
the MRS increases in magnitude as we move to the northwest and the MRS decreases as we move to the south east. The
intuitive understanding is that the MRS measures the willingness of the consumer to trade off one good for the other. As the
consumer has greater amounts of x, she will be willing to trade more units of x for each additional unit of y this results
from convexity.
An ordinal utility function U(x, y) provides a helpful tool for representing preferences. This is a function which associates a
number with each indifference curve. These numbers increase as we move to the northeast, with each successive indifference
curve representing bundles which are preferred over the last. The particular number assigned to an indifference curve has no
intrinsic meaning. All we know is that if U(x1, y1) > U(x2, y2) , then the consumer prefers bundle 1 to bundle 2.
Figure 2 illustrates how it is possible to use a utility function to generate a diagram with the associated indifference curves.
This figure illustrates Cobb-Douglas well-behaved preferences which are commonly employed in applied work.
Up to this point, we have we have focused exclusively on the characterization of preferences. Let us now consider the other
side of the consumer model the budget constraint. The simplest approach to characterizing consumer income is to assume
that the consumer has a fixed money income which she may spend on any goods. The only constraint on this choice is that
the value of the expenditure may not exceed the money income. This is the standard budget constraint:
Px x + Py y = M.
Graphically, this equation defines the line depicted in Figure 3. All points inside the budget line are affordable. The consumer
faces a choice of which affordable bundle to select.
2 The Theory of Consumer Demand 507
508 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
2 The Theory of Consumer Demand 509
510 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
Within the framework of our theory, the answer is straightforward the consumer will choose the one combination of x and y
from the set of affordable bundles which maximizes her utility. This combination of x and y will be at the point where the
indifference curve is tangent the budget line. This point is called the optimal choice. We see this illustrated in Figure 4.
The standard model of consumer behavior provides a starting point for learning MPSGE. This introduction is hands on I
will discuss issues as they arise, assuming that you have access to a computer and can invoke the program and read the output
file. You may wish to learn the rudiments of GAMS syntax before starting out, although you may be able to pick up these
ideas as they come, depending on your aptitude for computer languages.
3 Getting Started
1. You need to know how to generate a standard text file. There are several methods for doing this. One approach is to
use EDIT, the standard DOS text editor. Another approach favored by many people who have used text processors like
WordPerfect or Microsoft Word is to use the word processor as a text editor. A disadvantage of this approach is that
you will need to remember to always save the edited file in a text format. A final approach, one which I suggest to
3 Getting Started 511
graduate students who are interested in numerical modeling, is that you develop facility with a real programmer's
editor like Emacs, Epsilon or Brief. These editors are far more powerful than the DOS Edit, and they are far better
suited to computational work than a word processor.
2. You need to have a copy of GAMS with MPSGE to run on your computer. There are versions of this program for
386/486/586 PCs as well as for most widely-used workstations (SUN,DEC,HP,IBM,etc.). Copies of the program can be
obtained directly from GAMS (gams@gams.com), or you may take a copy from someone who already has the program.
(Copyright restrictions apply only to GAMS license files.) You may copy the GAMS programs without the license
files and the program will only operate in student/demonstration mode. The student version is perfectly adequate for
learning about modeling in fact, it may be better because it's dimensionality restrictions prevent the novice model
builder from adding unnecessary details.
3. You need to install GAMS with MPSGE on your computer. To do this, follow the standard installation procedure:
(a) Make a GAMS system directory, e.g.
c:\>mkdir gams
(b) Copy all the files from the GAMS distribution diskette(s) into the GAMS system directory; e.g.
c:\>copy a:*.* c:\gams
(c) Connect to the GAMS system directory and run the GAMS installation program e.g.
c:\>cd gams
c:\gams>gamsinst
The installation program gives you choices regarding which solver you wish to use for various problem classes. For
MPSGE models, the key choice is the MCP solver. I recommend that you select MPSGE if you have this solver on your
computer. It is the most efficient and robust solver currently available for this class of models. (MPSGE by Michael
Ferris and Steve Dirkse of the University of Wisconsin at Madison.)
You complete the installation by adding the GAMS system directory to your DOS environment variable, MPSGE.
Normally, MPSGE is initialized at startup in the file C:>AUTOEXEC.BAT. Look for a line which looks like "PATH
C:\DOS" and modify this to read something like: "PATH C:\DOS;C:\GAMS" using a text editor.
4. You should verify that the system is operational. Connect to a working directory (never run models from the GAMS
system directory!). Then, extract and run one of the library models, e.g.
C:\>MKDIR WORK
C:\>CD WORK
C:\WORK>GAMSLIB SCARFMGE
C:\WORK>GAMS SCARFMGE
If the GAMS system is properly installed, these commands will cause GAMS to solve a sequence of models from the
SCARFMGE sample problem. The output from this process is written to file SCARFMGE.LST . If you search for the word
STATUS, you can verify that all the cases are processed.
There are a number of MPSGE models included in the GAMS library. If you are using a student version of GAMS, you
will be able to process some but not all of the library models. The student version of the program limits the number of
variables in the model to 100. (I believe that GAMS imposes other limits on use of the student version, but the variable
limitation is the most severe constraint.)
Assuming that you have successfully installed the software, let us now proceed to some examples which illustrate both
the computing syntax and the underlying economics.
512 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
A utility function is represented in MPSGE by the specification of: (i) benchmark demand quantities, (ii) benchmark demand
prices (iii) an elasticity of substitution at the benchmark point. Benchmark quantities determine an anchor point for the set of
indifference curves. Benchmark prices fix the slope of the indifference curve at that point, and the elasticity describes the
curvature of the indifference curve. Speaking formally, elasticities provide a second order approximation of the utility
function. To understand the importance of the benchmark elasticity of substitution, consider Figure 6. This figure shows
three indifference curves all of which share the same benchmark quantities and benchmark prices. They differ only in the
elasticities of substitution. The least convex (flattest) curve has the highest elasticity, the most convex curve has the lowest
elasticity. (When the elasticity of substitution is 0, the indifference curve is L-shaped with the corner at the benchmark point.)
Let us now consider how the consumer optimization problem can be cast as a general equilibrium model. We do this by
adding a single factor of production and two production sectors. For concreteness, let the factor of production be called
labor with a price PL. One production function converts one unit of labor into one unit of x, the other sector converts 2 units
of labor into one unit ofy. Setting the labor endowment equal 120, the market clearance condition for labor reads:
1x + 2y = 120
$ONTEXT
514 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
$MODEL:DEMAND
The model specification begins by declaring variables for the model. In a standard model, there are three types of variables:
commodity prices, sectoral activity levels, and consumer incomes. The end of each line may include ! variable description .
N.B. The variables associated with commodities are prices, not quantities. (In this and subsequent models, I use P as the first
letter for each of the commodity variables to remind us that these variables are prices.)
N.B. The variable associated with a consumer is an income level, not a welfare index.
$SECTORS:
X ! ACTIVITY LEVEL FOR X = DEMAND FOR GOOD X
Y ! ACTIVITY LEVEL FOR Y = DEMAND FOR GOOD Y
$COMMODITIES:
PX ! PRICE OF X WHICH WILL EQUAL PL
PY ! PRICE OF Y WHICH WILL EQUAL 2 PL
PL ! PRICE OF THE ARTIFICIAL FACTOR L
$CONSUMERS:
RA ! REPRESENTATIVE AGENT INCOME
Function specifications follow the variable declarations. In this model, our first declarations correspond to the two production
sectors. In this model, the production structures are particularly simple. Each of the sectors has one input and one output.
In the MPSGE syntax, I: denotes an input and O: denotes an output. The output quantity coefficients for both sectors are
unity (Q:1). This means that the level values for x and y correspond to the actual quantities produced. The final function
specified in the model represents the utility function and endowments for our single consumer. In this function, the E:
entries correspond to endowments and the D: entries are demands. Reference demands, reference prices and the substitution
elasticity (s:1) characterize preferences.
The demand entries shown here are consistent with a Cobb-Douglas utility function in which the budget share for y is twice
the budget share for x (i.e. the MRS at (1,1) equals 1/2):
$PROD:X
O:PX Q:1
I:PL Q:1
$PROD:Y
O:PY Q:1
I:PL Q:2
$DEMAND:RA s:1
E:PL Q:120
D:PX Q:1 P:(1/2)
D:PY Q:1 P:1
$OFFTEXT
The final three statements in this file invoke the MPSGE preprocessor, generate and solve the model:
$INCLUDE DEMAND.GEN
SOLVE DEMAND USING MCP;
The preprocessor invocation ($SYSINCLUDE mpsgeset") should be placed immediately following the $OFFTEXT block
containing the model description. The model generator code, DEMAND.GEN, is produced by the previous statement and must
be referenced immediately before each subsequent SOLVE statement.
4 Modeling Consumer Demand 515
At this point, the reader should take the time to type the example into a file and execute the program with GAMS/MPSGE.
This is possibly the first GAMS model which some readers have solved, so it is worth looking through the listing file in
some detail. After running the solver, we examine the listing file. I typically begin my assessment of a model's solution by
searching for STATUS. For this model, we have the following:
S O L V E S U M M A R Y
MODEL DEMAND
TYPE MCP
SOLVER PATH FROM LINE 263
This information is largely self-explanatory. The most important items are the SOLVER STATUS and MODEL STATUS
indicators. When the solver status is 1 and the model status is 1, the system has returned an equilibrium.
For small models such as this, the limits on resource usage (time) and solver iterations have no effect. (You can modify these
values with the statements:
model.WORKSPACE = xx ;
PX.FX = 1;
entered following the model declaration ($SYSINCLUDE mpsgeset) but prior to the solver invocation. When any price or
income level is fixed, MPSGE recognizes that a numeraire has been specified and does no automatic normalization.
Following some output from the solver (PATH in this case), the listing file provides a complete report of equilibrium values.
With MPSGE models, the equation listings are superfluous. The variable listings provide all the relevant information.
For this model, the solution listing appears as follows:
516 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
The LOWER and UPPER columns report variable bounds applied in the model. In these columns, zero is represented by .
and infinity is represented by "+INF". The LEVEL column reports the solution value returned by the algorithm. Here we see
that the equilibrium price of x is 1 and the price of y is 2, as determined by the specification of labor inputs.
4.2 Exercises 1
(a) The utility function calibration point is arbitrary. Here, we have selected x = y = 1 as the reference quantity. Revise the
program to use a different calibration point where x = 2 and y = 1, where MRS(2, 1) = 1/4. (Remember to modify both the
Q : and P : fields.) Rerun the model to demonstrate that this does not change the result.
(b) Increase the price of x from 1 to 2 by changing the Q: coefficient for PL in sector X from 1 to 2. What happens to the
demand for x? Explain why a change in the price of x is represented by a change in the Q: field for sector X.
(c) Compute an equilibrium in which commodity y is defined as the numeraire.
This example further explores the representation of demand functions with MPSGE. It sets up a trivial equilibrium model
with two goods and one consumer which returns the marginal rate of substitution of good x for good y at a given level of
demand. The underlying utility function is:
When x = y = 1, the marginal rate of substitution of x for y is 1/4. We use this information to calibrate the demand function,
specifying the ratio of the reference prices of x to y equal to 1/4.
In an equilibrium, final demand always equals endowments for both goods, because these are the only sources of demand and
supply. The model as parameterized demonstrates that if we set endowments for this model equal to the demand function
calibration point, the model equilibrium price ratio equals the benchmark MRS.
This program begins with some GAMS statements in which three scalar parameters are declared. These parameters will be
used in the place of numbers within the MPSGE model. The syntax for these GAMS statements is introduced in Chapter 2 of
the GAMS manual. In short, we declare x, y and MRS as scalar parameters and initialize the first two of these to unity. The
MRS parameter is assigned a value following the solution of the model.
SCALAR
X QUANTITY OF X FOR WHICH THE MRS IS TO BE EVALUATED /1/
Y QUANTITY OF Y FOR WHICH THE MRS IS TO BE EVALUATED /1/
MRS COMPUTED MARGINAL RATE OF SUBSTITUTION;
The remainder of the <em>MPSGE</em> program is, in fact, simpler than Example 1.
4 Modeling Consumer Demand 517
$ONTEXT
$MODEL:MRSCAL
$COMMODITIES:
PX ! PRICE INDEX FOR GOOD X
PY ! PRICE INDEX FOR GOOD Y
$CONSUMERS:
RA ! REPRESENTATIVE AGENT
$DEMAND:RA s:1
D:PX Q:1 P:(1/4)
D:PY Q:1 P:1
E:PX Q:X
E:PY Q:Y
$OFFTEXT
$SYSINCLUDE mpsgeset MRSCAL
$INCLUDE MRSCAL.GEN
SOLVE MRSCAL USING MCP;
Following the solution, we compute a function of the solution values, the ratio of the price of x to the price of y. We do this
using the GAMS syntax which references the equilibrium level values of the PX and PY and storing this result in the scalar
MRS. This scalar value is then displayed in the listing file with 8 digits:
4.4 Exercises 2
(a) Show that the demand function is homothetic by uniform scaling of the x and y endowments. The resulting MRS should
remain unchanged.
(b)Modify the demand function calibration point so that the reference prices of both x and y equal unity (hint: the marginal
rate of substitution is:
MRS = x/(4y).
x + y = LPROD LS
where goods x and y both have a price of unity at base year productivity and LPROD is an index of labor productivity. An
increase in productivity is equivalent to a proportional decrease in the prices of x and y.
518 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
$MODEL:LSUPPLY
$SECTORS:
X ! SUPPLY=DEMAND FOR X
Y ! SUPPLY=DEMAND FOR Y
LS ! LABOR SUPPLY
$COMMODITIES:
PX ! MARKET PRICE OF GOOD X
PY ! MARKET PRICE OF GOOD Y
PL ! MARKET WAGE
PLS ! CONSUMER VALUE OF LEISURE
$CONSUMERS:
RA ! REPRESENTATIVE AGENT
$PROD:LS
O:PL Q:LPROD
I:PLS Q:1
$PROD:X
O:PX Q:1
I:PL Q:CX
$PROD:Y
O:PY Q:1
I:PL Q:CY
$DEMAND:RA s:1
E:PLS Q:120
D:PLS Q:1 P:1
D:PX Q:1 P:1
D:PY Q:1 P:1
$OFFTEXT
$SYSINCLUDE mpsgeset LSUPPLY
$INCLUDE LSUPPLY.GEN
SOLVE LSUPPLY USING MCP;
We can use this model to evaluate the wage elasticity of labor supply. In the initial equilibrium (computed in the last
statement) the demands for x, y and L all equal 40. A subsequent assignment to LPROD (below) increases labor productivity.
After computing a new equilibrium, we can use the change in labor supply to determine the wage elasticity of labor supply,
an important parameter in labor market studies. It should be emphasized that the elasticity of labor supply should be an input
rather than an output of a general equilibrium model this is a parameter for which econometric estimates can be obtained.
Here is how the programming works. First, we declare some scalar parameters which we will use for reporting, then save the
benchmark labor supply in LS0:
SCALAR
5 The Pure Exchange Model 519
LS0 = LS.L;
Next, we modify the value of scalar LPROD, increasing labor productivity by 1%. Because this is a neoclassical model, this
change is equivalent to increasing the real wage by 1%. We need to recompute equilibrium prices after having changed the
LPROD value:
LPROD = 1.01;
$INCLUDE LSUPPLY.GEN
SOLVE LSUPPLY USING MCP;
We use this solution to compute and report the elasticity of labor supply as the percentage change in the LS activity:
As the model is currently constructed, the wage elasticity of labor supply equals zero. This is because the utility function
is Cobb-Douglas over goods and leisure, and the consumer's only source of income is labor. As the real wage rises, this
increases both the demand for goods (labor supply) and the demand for leisure. These effect exactly balance out and the
supply of labor is unchanged.
4.6 Exercises 3
(a) One way in which the labor supply elasticity might differ from zero in a model with Cobb-Douglas final demand is if there
were income from some other source. Let the consumer be endowed with good x in addition to labor. What x endowment is
consistent with a labor supply elasticity equal to 0.15?
(b) A second way to calibrate the labor supply elasticity is to change the utility function. We can do this by changing the
s:1 to s:SIGMA, where SIGMA is a scalar value representing the benchmark elasticity of substitution between x, y and L in
final demand. Modify the program to include SIGMA as a scalar, and find the value for SIGMA consistent with a labor supply
elasticity equal to 0.15.
Two types of consumers, denoted A and B. We consider A and B to each represent multiple consumers,
each with the same endowments and preferences. This assumption is helpful for justifying our assumption
of perfectly competitive, price-taking behavior.
Two commodities, denoted x and y
520 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
Fixed endowments of both goods. The horizontal axis measures the total world endowment of good X.
The vertical axis measure the total world endowment of good Y . Any point in the box then represents an
allocation of goods between the two agents. The agent H allocation is measured with respect to the lower
left origin. The agent F allocation is measured with respect to the upper right origin.
Each agent has a given initial endowment, here denoted point E. Furthermore, we assume that there is no possibility for trade.
The indifference curves through point E therefore represent autarchy welfare levels.
The key idea in this model is that trade can improve both agents' welfare. One agent gives some amount good x to the other
in return for an amount of good y. The terms of trade, the rate of exchange between x and y, is determined by the model.
The model illustrates a number of important properties of market economies:
Trade is mutually beneficial. So long as the transactions are voluntary, neither H nor F will be hurt by
engaging in trade.
Market prices can be used to guide the economy to a Pareto-efficient allocation, a state of affairs in which
further mutually-beneficial trades are not possible.
There is no guarantee that the gains from trade will be fairly distributed across consumers. A competitive
equilibrium may produce a significant welfare increase for one consumer while have negligible impact on
the other.
There are multiple Pareto-efficient allocations, typically only one of which is a competitive equilibrium.
We can use this model to demonstrate that the issues of efficiency and equity can be separated when there
is the possibility of lump-sum income transfers between agents.
This model is actually simpler than the models presented above because we have no need for production. There are simply
two commodities and two consumers. The consumers differ in terms of commodity endowments and preferences. The
competitive equilibrium prices are such that supply equals demand for both goods and both agents spend an amount equal to
their endowment income.
This model illustrates how to use computed function coefficients. See, for example, Q:(1-THETA A) in the $DEMAND:A
block. Any numeric input field in an MPSGE model may be computed, provided that the algebraic expression is enclosed
within parentheses and legitimate GAMS code.
This model specification uses the default values for reference prices in the demand function blocks. When P:value is not
specified in a D:,I: or O: record, P:1 is assumed.
This model uses the more general constant-elasticity-of-substitution utility function.
$ONTEXT
$MODEL:EXCHANGE
$COMMODITIES:
PX ! EXCHANGE PRICE OF GOOD X
PY ! EXCHANGE PRICE OF GOOD Y
$CONSUMERS:
A ! CONSUMER A
B ! CONSUMER B
$DEMAND:A s:SIGMA_A
E:PX Q:XA
E:PY Q:YA
D:PX Q:THETA_A
D:PY Q:(1-THETA_A)
$DEMAND:B s:SIGMA_B
E:PX Q:(1-XA)
E:PY Q:(1-YA)
D:PX Q:THETA_B
D:PY Q:(1-THETA_B)
$OFFTEXT
$SYSINCLUDE mpsgeset EXCHANGE
$INCLUDE EXCHANGE.GEN
SOLVE EXCHANGE USING MCP;
SCALAR
PRATIO EQUILIBRIUM PRICE OF X IN TERMS OF Y,
IRATIO EQUILIBRIUM RATIO OF CONSUMER A INCOME TO CONSUMER B INCOME;
The foregoing sets up the model and computes the competitive equilibrium. After GAMS returns from the solver, we declare
and compute some report values.
Absolute levels of income and price returned from a general equilibrium model are not meaningful because a model
determines only relative prices. For this reason, we report equilibrium income and price levels in relative terms.
In the final step, we compute an alternative efficient equilibrium, one in which the income levels for A and B are equal. The
purpose of this exercise is to demonstrate the second welfare theorem. When incomes are both fixed, the equilibrium remains
efficient, but the connection between market prices and endowment income is eliminated.
In GAMS/MPSGE, a variable may be fixed using the GAMS syntax
variable.fx= value;
A.FX = 1;
B.FX = 1;
$INCLUDE EXCHANGE.GEN
SOLVE EXCHANGE USING MCP;
6.2 Exercises 4
(a) Set up a separate models which computes the autarchy price ratios for consumers A and B. (You can use one of the earlier
models as a starting point.)
(b) Determine parameter values for which the endowment point is the equilibrium point.
(c) Set up a series of computations from which you can sketch the efficiency locus. Draw the Edgeworth box diagram which
is consistent with these values.
The program differs from the previous example in several respects. First, we introduce a separate commodity price for each
agent. In the absence of tariffs, these prices are identical.
A second difference is that in this model trade activities deliver goods from one agent to the other. These are denoted
M{good}{agent} for imports of {good} to {agent}. There are four flows which may be operated in only one direction (the
activity levels are non-negative). In terms of initial endowments and preferences, this model has exactly the same economic
structure as the previous model.
$ONTEXT
$MODEL:TARIFFS
$SECTORS:
MXA ! TRADE IN X FROM B TO A
MXB ! TRADE IN X FROM A TO B
MYA ! TRADE IN Y FROM B TO A
MYB ! TRADE IN Y FROM A TO B
$COMMODITIES:
PXA ! PRICE OF GOOD X FOR AGENT A
PYA ! PRICE OF GOOD Y FOR AGENT A
PXB ! PRICE OF GOOD X FOR AGENT B
PYB ! PRICE OF GOOD Y FOR AGENT B
$CONSUMERS:
A ! CONSUMER A
B ! CONSUMER B
$DEMAND:A s:SIGMA_A
E:PXA Q:XA
E:PYA Q:YA
D:PXA Q:THETA_A
D:PYA Q:(1-THETA_A)
$DEMAND:B s:SIGMA_B
E:PXB Q:(1-XA)
E:PYB Q:(1-YA)
D:PXB Q:THETA_B
D:PYB Q:(1-THETA_B)
The trade activities each have one input and one output. They simply deliver a good ( X or Y ) from one agent to the other.
The new syntax presented here is specification of an ad-valorem tax. Adding a tax requires two new fields. The first is "A:"
which specifies the tax agent, a consumer who collects the tax revenue as part of income. The second is "T:" which specifies
the ad- valorem tax rate.
MPSGE permits taxes to applied on production inputs and outputs but it does not permit taxes on final demand.
The tax applies on a net basis on inputs. For example, if we consider the MXA sector, the price of one unit of input is given
by:
Px B (1 + Ta)
where Px B is the net of tax price of a unit of x in the agent B market and Ta is the ad-valorem tariff rate.
524 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
$PROD:MXA
O:PXA Q:1
I:PXB Q:1 A:A T:T_A
$PROD:MXB
O:PXB Q:1
I:PXA Q:1 A:B T:T_B
$PROD:MYA
O:PYA Q:1
I:PYB Q:1 A:A T:T_A
$PROD:MYB
O:PYB Q:1
I:PYA Q:1 A:B T:T_B
The final portions of the file introduces one use of MPSGE report variables. In this case, report variables are used to recover
a Hicksian money-metric welfare index for each of the agents. We compute the initial, tariff-ridden equilibrium in order to
compute the benchmark welfare levels. We then set all tariffs to zero and compute the free-trade equilibrium. Using the
final welfare indices and the saved values of the benchmark welfare levels, we are able to report the change in welfare from
removing tariff distortions.
$REPORT:
V:WA W:A
V:WB W:B
$OFFTEXT
$SYSINCLUDE mpsgeset TARIFFS
$INCLUDE TARIFFS.GEN
SOLVE TARIFFS USING MCP;
SCALAR
WA0 BENCHMARK WELFARE INDEX FOR AGENT A
WB0 BENCHMARK WELFARE INDEX FOR AGENT B;
WA0 = WA.L;
WB0 = WB.L;
T_A = 0;
T_B = 0;
$INCLUDE TARIFFS.GEN
SOLVE TARIFFS USING MCP;
SCALAR
EVA HICKSIAN EQUIVALENT VARIATION FOR AGENT A
EVB HICKSIAN EQUIVALENT VARIATION FOR AGENT B;
6.4 Exercises 5
(a) Find the optimal tariff in this model for agent A, assuming that agent B does not retaliate and leaves her tariff rate at the
benchmark level.
6 Modeling Pure Exchange with MPSGE 525
(b) Insert the endowment and preference parameters from the previous problem, retaining the same benchmark tariff rates.
Does free trade benefit both countries? If not, why not?
526 Intermediate Demand Theory and General Equilibrium: An Intermediate Level Introduction to MPSGE
Chapter 42
Notes prepared for GAMS General Equilibrium Workshop held December, 1995 in Boulder Colorado
Thomas F. Rutherford, Department of Economics, University of Colorado
December, 1995 :
1 The Basics
In many economic textbooks the constant elasticity of substitution (CES) utility function is defined as:
1
U(x, y) = (x + (1 )y ) ,
It is a fairly routine but tedious calculus excercise to demonstrate that the associated demand functions are:
M
x(px , py , M) = = ,
px p1
x + (1 ) py1
and
1 M
y(px , py , M) = ,
py px1 + (1 ) p1
y
The corresponding indirect utility function has is:
1
1
1 1
V (px , py , M) = M px + (1 ) py ,
U(x , y ) = U(x, y)
This is a convenient cardinalization of utility, because percentage changes in U are equivalent to percentage Hicksian
equivalent variations in income.
Because U is linearly homogeneous, V is homogeneous of degree one in M and degree 1 in p.
In the representation of technology, we have an analogous set of relationships, based on the cost and compensated demand
functions. If we have a CES production function of the form:
528 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
1
y(K, L) = K + (1 )L
,
and
(1 )c(pK , pL )
y
L(pK , pL ) = .
pL
In most large-scale applied general equilibrium models, we have many function parameters to specify with relative ly few
observations. The conventional approach is to calibrate functional parameters to a single benchmark equilibrium. For
example, if we have benchmark estimates for output, labor, capital inputs and factor prices , we calibrate function coefficients
by inverting the factor demand functions:
1
pk K 1
= pk K+PL L
, = , = K ,
and
1
= y K + (1 )L .
1
K L
y = y + (1 )
K L
The only calibrated parameter, , represents the value share of capital at the benchmark point. The corresponding cost
functions in the calibrated form is written:
1 1 1
pK pL 1
c(pK , pL ) = c + (1 )
pk pL
3 Excercises 529
y c pL
L(pK , pL , y) = L .
y c pK
Normalizing the benchmark utility index to unity, the utility function in calibrated share form is written:
1
x y
U(x, y) = + (1 )
x y
1 1
px py 1
e(px , py ) = + (1 )
px py
M
V (px , py , M) =
Me(px , py )
and the demand functions are:
e(px , py ) px
x(px , py , M) = x V (px , py , M)
px
and
e(px , py ) py
y(px , py , M) = y V (px , py , M)
py
The calibrated form extends directly to the n-factor case. An n-factor production function is written:
1
xi
y = f (x) = y i
i xi
1 1
pi 1
C(p) = C i
i pi
and compensated factor demands:
y C pi
xi = xi
y Cpi
3 Excercises
(i) Show that given a generic CES utility function:
1
U(x, y) = ( + (1 )y ) p
530 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
x = 1, y = 1, px = t, py = t(1 ), M = t.
U(x, y) = (x a) (y b)1
A benchmark demand point with both prices equal and demand for y equal to twice the demand for x. Find values for which
are consistent with optimal choice at the benchmark. Select these parameters so that the income elasticity of demand for x at
the benchmark point equals 1.1.
(iii) Consider the utility function:
1
U(x, L) = (L + (1 )x )
in which M is interpreted as non-wage income, is the market wage rate. Assume a benchmark equilibrium in which prices
for x and L are equal, demands for x and L are equal, and non-wage income equals one-half of expenditure on x. Find values
of and consistent with these choices and for which the price elasticity of labor supply equals 0.2.
(iv) Consider a consumer with CES preferences over two goods. A price change makes the benchmark consumption bundle
unaffordable, yet the consumer is indifferent. Graph the choice. Find an equation which determines the elasticity of
substitution as a function of the benchmark value shares. (You can write down the equation, but it cannot be solved in closed
form.)
(v) Consider a model with three commodities, x, y, and z. Preferences are CES. Benchmark demands and prices are equal for
all goods. Find demands for x, y and z for a doubling in the price of x as a function of the elasticity of substitution.
(iv) Consider the same model in the immediately preceeding question, except assume that preferences are instead given by:
1
U(x, y, z) = ( min(x, y) + (1 )z )
Determine from the benchmark, and find demands for x, y and z if the price of x doubles.
and
i xi
i .
C
The single-level constant elasticity of substitution cost function in calibrated share form is written:
1
i 1 1
C() = C i
i i
4 Flexibility and Non-Separable CES functions 531
C() i
C
xi () = Ci = xi
i C i
Ci jC
i j
CiC j
where
2C() xi xj
Ci j = = =
i j j i
or, equivalently:
i j ( j ) = 0
j
The Euler condition provides a simple formula for the diagonal AUES values:
j6=i i j j
ii =
i
As an aside, note that convexity of the cost function implies that all minors of order 1 are negative, i.e. ii < 0 i . Hence,
there must be at least one positive off-diagonal element in each row of the AUES or Slutsky matrices. When there are only
two factors, then the off-diagonals must be negative. When there are three factors, then only one pair of negative goods may
be complements.
Let:
k be the reference the index of second-level nest
sik denote the fraction of good i inputs assigned to the kth nest
k denote the benchmark value share of total cost which enters through the kth nest
denote the top-level elasticity of substitution
k denote the elasticity of substitution in the kth aggregate
pk () denote the price index associated with aggregate k, normalized to equal unity in the benchmark, i.e.:
1
i sik i 1 k
pk () =
i 1 k
k i
The two-level nested, nonseparable constant-elasticity-of-substitution (NNCES) cost function is then defined as:
1
1
1
C() = C k pk ()
k
Demand indices for second-level aggregates are needed to express demand functions in a compact form. Let zk () denote the
demand index for aggregate k, normalized to unity in the benchmark; i.e.
532 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
C() 1
zk () =
C pk ()
Compensated demand functions are obtained by differentiating C() . In this derivative, one term arise for each nest in which
the commodity enters, so:
k k
pk ()i
pk ()i
C() 1
xi () = xi zk () = xi
K i k C pk () i
Simple differentiation shows that benchmark cross-elasticities of substitution have the form:
( k )sik s jk
i j = +
k k
Given the benchmark value shares i and the benchmark cross-price elasticities of substitution, i j , we can solve for values
of , sik , k , k and . We compute these parameters using a constrained nonlinear programming algorithm, CONOPT, which
is available through GAMS, the same programming environment in which the equilibrium model is specified. Perroni and
Rutherford (EER, 1994) prove that calibration of the NNCES form is possible for arbitrary dimensions whenever the given
Slutsky matrix is negative semi-definite. The two-level (NxN) function is flexible for three inputs; and although we have not
proven that it is flexible for 4 inputs, the only difficulties we have encountered have resulted from indefinite calibration data
points.
Two GAMS programs are listed below. The first illustrates two analytic calibrations of the three-factor cost function. The
second illustrates the use of numerical methods to calibrate a four-factor cost function.
PARAMETER
* Fill in off-diagonals:
AUES(I,J)$AUES(J,I) = AUES(J,I);
PARAMETER
ESUB(*,*) Alternative calibrated elasticities
SHR(*,I,N) Alternative calibrated shares
SIGMA(N) Second level elasticities
S(I,N) Nesting assignments (in model)
GAMMA Top level elasticity (in model);
(AUES(I1,I3)-AUES(I1,I1));
SHR("CES",I3,"N1") =
(AUES(I1,I2)-AUES(I1,I3)) / (AUES(I1,I2)-AUES(I1,I1));
SHR("CES",I3,"N2") = 1 - SHR("CES",I3,"N1");
);
ABORT$(SMIN(N, ESUB("CES",N)) LT 0) "Benchmark AUES is indefinite?";
ABORT$(SMIN((I,N), SHR("CES",I,N)) LT 0) "Benchmark AUES is indefinite?";
PRICE(I) = 1;
$ontext
$MODEL:CHKCALIB
$SECTORS:
Y ! PRODUCTION FUNCTION
D(I)
$COMMODITIES:
PY ! PRODUCTION FUNCTION OUTPUT
P(I) ! FACTORS OF PRODUCTION
PFX ! AGGREGATE PRICE LEVEL
$CONSUMERS:
RA
$PROD:D(I)
O:P(I) Q:THETA(I)
I:PFX Q:(THETA(I)*PRICE(I))
$DEMAND:RA
D:PFX
E:PFX Q:2
E:PY Q:-1
$OFFTEXT
$SYSINCLUDE mpsgeset CHKCALIB
ALIAS (I,II);
LOOP(FUNCTION,
S(I,K) = SHR(FUNCTION,I,K);
LOOP(II,
$INCLUDE CHKCALIB.GEN
SOLVE CHKCALIB USING MCP;
));
$LIBINCLUDE qadplot
SET PR Alternative price levels /PR0*PR10/;
PARAMETER
DEMAND(FUNCTION,I,PR) Demand functions
DPLOT(PR,FUNCTION) Plotting output array;
LOOP(II,
LOOP(FUNCTION,
K(N) = YES$SUM(I, SHR(FUNCTION,I,N));
GAMMA = ESUB(FUNCTION,"GAMMA");
SIGMA(K) = ESUB(FUNCTION,K);
S(I,K) = SHR(FUNCTION,I,K);
LOOP(PR,
PRICE(J) = 1;
PRICE(II) = 0.2 * ORD(PR);
$INCLUDE CHKCALIB.GEN
SOLVE CHKCALIB USING MCP;
DEMAND(FUNCTION,II,PR) = D.L(II);
DPLOT(PR,FUNCTION) = D.L(II);
);
);
);
DISPLAY DEMAND;
* ========================================================================
* Model-specific data defined here:
PARAMETER
THETA(I) Benchmark value shares /K 0.2, L 0.4, E 0.05, M 0.35/
* Fill in off-diagonals:
AUES(I,J)$AUES(J,I) = AUES(J,I);
538 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
* ========================================================================
VARIABLES
S(I,N) Fraction of good I which enters through nest N,
SHARE(N) Value share of nest N,
SIGMA(N) Elasticity of substitution within nest N,
GAMMA Elasticity of substitution at the top level,
OBJ Objective function;
EQUATIONS
SDEF(I) Nest shares must sum to one,
TDEF(N) Nest share in total cost,
ELAST(I,J) Consistency with given AUES values,
OBJDEF Maximize concentration;
ELAST(I,J)$(ORD(I) GT ORD(J))..
SUM(K, (SIGMA(K)-GAMMA)*S(I,K)*S(J,K)/SHARE(K));
SHARE.LO(N) = EPSILON;
SCALAR SOLVED Flag for having solved the calibration problem /0/
MINSHR Minimum share in candidate calibration;
OPTION SEED=0;
LOOP(TRIES$(NOT SOLVED),
K(N) = YES;
S.LO(I,N) = 0; S.UP(I,N) = 1;
SHARE.LO(N) = EPSILON; SHARE.UP(N) = 1;
SIGMA.LO(N) = 0; SIGMA.UP(N) = +INF;
IF (SOLVED,
IF (MINSHR EQ 0,
S.FX(I,N)$(NOT K(N)) = 0;
SHARE.FX(N)$(NOT K(N)) = 0;
SIGMA.FX(N)$(NOT K(N)) = 0;
IF (SOLVED,
DISPLAY "Function calibrated:",GAMMA.L,SIGMA.L,SHARE.L,S.L;
ELSE
DISPLAY "Function calibration fails!";
);
$ONTEXT
*==========================================================================
N3 7.804
N1 N2 N3 N4
*==========================================================================
The following solution is obtained by CONOPT on the second try, following a LOCALLY INFEASIBLE termination on the
first problem. Notice that it is identical to the MINOS5 solution except that the nesting assigments have been permuted:
7 Numerical calibration of NNCES given KLEM elasticities 541
N4 7.804
N1 N2 N3 N4
*==========================================================================
$OFFTEXT
PRICE(I) = 1;
$ontext
$MODEL:CHKCALIB
$SECTORS:
Y ! PRODUCTION FUNCTION
D(I)
$COMMODITIES:
PY ! PRODUCTION FUNCTION OUTPUT
P(I) ! FACTORS OF PRODUCTION
PFX ! AGGREGATE PRICE LEVEL
$CONSUMERS:
RA
$PROD:D(I)
O:P(I) Q:THETA(I)
I:PFX Q:(THETA(I)*PRICE(I))
$DEMAND:RA
D:PFX
E:PFX Q:2
E:PY Q:-1
$OFFTEXT
$SYSINCLUDE mpsgeset CHKCALIB
CHKCALIB.ITERLIM = 0;
$INCLUDE CHKCALIB.GEN
SOLVE CHKCALIB USING MCP;
CHKCALIB.ITERLIM = 2000;
ALIAS (I,II);
LOOP(II,
$INCLUDE CHKCALIB.GEN
SOLVE CHKCALIB USING MCP;
);
DISPLAY AUES, AUESCHK;
PI PC
PS =
PK
The price index for savings is unity in the benchmark period. In a counter-factual equilibrium, however, we would expect
generally that PS 6= PI . When these price indices are not equal, there is a virtual tax payment associated with savings
demand.
8 Calibrating Labor Supply and Savings Demand 543
Following BFSW, we adopt a nested constant-elasticity-of-substitution function to represent preferences. In this function,
at the top level demand for savings (future consumption) trades off with a second CES aggregate of leisure and current
consumption. These preferences can be summarized with the following expenditure function:
1 1 1
PU = PH S + (1 )PH S 1S
Preferences are homothetic, so we have defined PU as a linearly homogeneous cost index for a unit of utility. We conveniently
scale this price index to equal unity in the benchmark. In this definition, is the benchmark value share for current
consumption (goods and leisure). PH is a compositive price for current consumption defined as:
1
PH = Pl1L + (1 )PC1L 1L
in which is the benchmark value share for leisure within current consumption. Demand functions can be written as follows:
S
PU I
S = S0 PF I0 PU ,
L S
PH PU I
C = C0 PC PH I0 PU ,
and
L S
PH PU I
` = `0 PL PH I0 PU ,
Demands are written here in terms of their benchmark values ( S0 , C0 and `0 ) and current and benchmark income ( I and I0 ).
There are four components in income. The first is the value of labor endowment ( E), defined inclusive of leisure. The second
is the value of capital endowment ( K). The third is all other income ( M). The fourth is the value of virtual tax revenue
associated with differences between the shadow price of savings and the cost of investment.
I = PL E + PK K + M + (PS PI )S
`0 = L0 ( 1)
2. = 0.15 is the uncompensated elasticity of labor supply with respect to the net of tax wage, i.e.
L PL (E `) PL ` PL
= = =
PL L PL L PL L
S S
PK PK
Shephard's lemma applied at benchmark prices provides the following identities which are helpful in deriving
expressions for and :
PU PU PH PH
= , = 1 , = , = 1,
PH PS PL PC
544 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
IK0
S =
and
1
S (1 ) + IE0
L =
1
* Benchmark data:
* Calibrated parameters:
* Leisure demand:
9 A Maquette Illustrating Labor Supply and Savings Demand Calibration 545
L0 = EL0 - LS0;
M0 = C0 + S0 - LS0 - K0;
I = L0 + C0 + S0;
* Calibrated elasticity:
SIGMA_L = (XI*(LS0/L0)-SIGMA_S*BETA*(1-ALPHA)-ALPHA*BETA+EL0/I)/(1-BETA);
XIMIN = -(L0/LS0) * (- SIGMA_S * BETA * (1-ALPHA) - ALPHA*BETA + EL0/I);
ABORT$(SIGMA_L LT 0) " Error: cannot calibrate SIGMA_L", XIMIN;
$ONTEXT
$MODEL:CHKCAL
$COMMODITIES:
PL
PK
PC
PS
$SECTORS:
Y
S
$CONSUMERS:
RA
$PROD:Y
O:PC Q:(K0+LS0-S0)
I:PL Q:(LS0-S0)
I:PK Q:K0
$PROD:S
546 CES Constant Elasticity of Substitution Functions: Some Hints and Useful Formulae
S.L = S0;
TS = 0;
CHKCAL.ITERLIM = 0;
$INCLUDE CHKCAL.GEN
SOLVE CHKCAL USING MCP;
PL.L = 1.001;
CHKCAL.ITERLIM = 0;
$INCLUDE CHKCAL.GEN
SOLVE CHKCAL USING MCP;
* Compute induced changes in labor supply using the labor market
* "marginal", PL.M. This marginal returns the net excess supply of
* labor at the given prices. We started from a balanced benchmark,
* with no change in labor demand (the iteration limit was zero).
* Hence, PL.M returns the magnitude of the change in labor supply.
* We multiply by the benchmark wage (1) and divide by the benchmark
* labor supply (LS0) to produce a finite difference approximation
* of the elasticity:
PL.L = 1.0;
PK.L = 1.001;
PS.L = 1 / 1.001;
TS = 1 / 1.001 - 1;
CHKCAL.ITERLIM = 0;
PS.M = 1;
LOOP(ITER$(ABS(PS.M) GT 1.0E-8),
$INCLUDE CHKCAL.GEN
SOLVE CHKCAL USING MCP;
S.L = S.L - PS.M;
);
Installation Notes
Chapter 43
1.1 Installation
1. Run windows x86 32.exe (Windows 32bit) or windows x64 64.exe (Windows 64bit): Both files are available from
http://www.gams.com/download. The 32 bit version works both on a 32bit and on a 64bit operating system. Please
note that the installation may require administrative privileges on your machine.
You have two options to run the installer: In default or advanced mode. In the default mode, the installer will prompt
you for the name of the directory in which to install GAMS. We call this directory the GAMS directory. You may
accept the default choice or pick another directory. Please remember: if you want to install two different versions of
GAMS, they must be in separate directories.
If you choose to use the advanced mode, the installer will also ask you for a name of a start menu folder, if GAMS
should be installed for all users, if the GAMS directory should be added to the PATH environment variable and if
a desktop icon should be created. For automating the installation of GAMS, it is possible to provide the command
line parameters /SP- /SILENT. This will install GAMS in a non-interactive manner using default settings. Note that
depending on the security settings, the User Account Control asking for permission might still be active.
2. Copy the GAMS license file: You will be asked for the GAMS license file (gamslice.txt) during the installation. If
you are not sure or you have no a license file, choose No license, demo only when asked for the GAMS license
options. You can always do this later. If no valid license file is found, GAMS will still function in the demonstration
mode, but will only solve small problems. All demonstration and student systems do not include a license file.
If you have a license file you wish to copy to the GAMS directory at this time, answer Copy license file. You will
now be given the opportunity to browse the file system and find the license file gamslice.txt. When you have found
the correct file, choose open to perform the copy. Instead of copying a license file you could also copy the content of
that file to the clipboard. If you have done this, select Copy license text from clipboard.
3. Create a project file: If this is the first installation of GAMS on your system, the installation program will create a
default GAMS project in a subdirectory of your documents folder. Otherwise, your existing GAMS projects will be
preserved.
4. Choose the default solvers: Run the GAMS IDE by double clicking gamside.exe from the GAMS directory. To view
or edit the default solvers, choose File Options Solvers from the IDE. You can accept the existing defaults if
you wish, but most users want to select new default solvers for each model type.
552 Installation and System Notes
5. Run a few models to test the GAMS system: The on-line help for the IDE (Help GAMS IDE Help Topics
Guided Tour) describes how to copy a model from the GAMS model library, run it, and view the solution. To test
your installation, run the following models from the GAMS model library:
Users wishing to use GAMS from the command line (aka the console mode) may want to perform the following steps. These
steps are not necessary to run GAMS via the IDE.
1. We recommend to add the GAMS directory to your environment path in order to avoid having to type in an absolute path
name each time you run GAMS. Run the installer in advanced mode and mark the check-box Add GAMS directory
to PATH environment variable.
2. Run the program gamsinst: gamsinst is a command line program used to configure GAMS. It prompts the user for
default solvers to be used for each model type. If possible, choose solvers you have licensed, since unlicensed solvers
will only run in demonstration mode. The solver defaults can be changed by:
a. rerunning gamsinst and resetting the default values
b. setting a command line default, e.g. gams trnsport lp=bdmlp
c. by an option statement in the GAMS model, e.g: option lp=bdmlp;
The system wide solver defaults are shared by the command line and the GAMS IDE, so you can also choose to set
these defaults using the GAMS IDE.
2.1 Installation
To install GAMS, please follow the steps below as closely as possible. We advise you to read this entire document
before beginning the installation procedure. Additionally, a video on how to install GAMS on Linux is available at
https://www.youtube.com/watch?v=Mx tYI3wyP4.
1. Obtain the GAMS distribution file, which is available from http://www.gams.com/download, in one large self-
extracting zip archive with a sfx.exe file extension, e.g., linux x64 64 sfx.exe on a Linux 64bit system. Check
that it has the execute permission set. If you are not sure how to do this, just type in the command, e.g., chmod 755
linux x64 64 sfx.exe.
2. Choose a location where you want to create the GAMS system directory (the GAMS system directory is the directory
where the GAMS system files should reside). At this location the GAMS installer will create a subdirectory with a
name that indicates the distribution of GAMS you are installing. For example, if you are installing the 24.3 distribution
in /opt/gams, the installer will create the GAMS system directory /opt/gams/gams24.3 linux x64 64 sfx. If
the directory where you want to install GAMS is not below your home directory, you may need to have root privileges
on the machine.
3. Create the directory that should contain the GAMS system directory, for instance /opt/gams. Change to this directory
(cd /opt/gams). Make sure pwd returns the name of this directory correctly.
2 GAMS Installation Notes for Unix 553
4. Run the distribution file, either from its current location or after transfering it to the directory that should contain the
GAMS system directory. By executing the distribution file, the GAMS distribution should be extracted. For example,
if you downloaded the distribution file into your home directory, you might execute the following commands:
mkdir /opt/gams
cd /opt/gams
~/linux_x64_64_sfx.exe
5. Optionally, create the license file gamslice.txt in the GAMS system directory. The license file is nowadays sent via
email, with instructions. If no license file is present, GAMS will still function in the demonstration mode but can only
solve small problems. Student and demonstration systems do not include a license file. A license file can easily be
added later, so if you cannot find a license file, you can safely proceed without one.
6. Change to the GAMS system directory and run the program ./gamsinst. It will prompt you for default solvers to be
used for each class of models. If possible, choose solvers you have licensed since unlicensed solvers will only run in
demonstration mode. These solver defaults can be changed or overridden by:
a. rerunning ./gamsinst and resetting the default values
b. setting a command line default, e.g., gams trnsport lp=bdmlp
c. an option statement in the GAMS model, e.g: option lp=bdmlp;
8. To test the installation, log in as a normal user and run a few models from your home directory, but not the GAMS
system directory:
9. If you move the GAMS system to another directory, remember to rerun ./gamsinst. It is also good practice to rerun
./gamsinst when you add or change your license file if this has changed the set of licensed solvers.
1. If you are using the C shell (csh) and its variants you can modify your .cshrc file by adding the line
2. Those of you using the Bourne (sh) or Korn (ksh) shells and their variants can modify their .profile or .bashrc
file by adding the line
PATH=$PATH:/opt/gams/gams24.3_linux_x64_64_sfx
If neither .profile nor .bashrc exist yet, .profile needs to be created. You should log out and log in again after
you have made any changes to your path.
3. You may prefer to use an alias for the names of the programs instead of modifying the path as described above. C shell
users can use the following commands on the command line or in their .cshrc file:
554 Installation and System Notes
The correct Bourne or Korn shell syntax (either command line or .profile) is:
alias gams=/opt/gams/gams24.3_linux_x64_64_sfx/gams
alias gamslib=/opt/gams/gams24.3_linux_x64_64_sfx/gamslib
Again, you should log out and log in in order to put the alias settings in .cshrc or .profile into effect.
4. Casual users can always type the absolute path names of the GAMS programs, e.g.:
/opt/gams/gams24.3_linux_x64_64_sfx/gams trnsport
The 32-bit Windows version of the GAMS system can be installed and used under 32-bit Wine. However, note that using
GAMS for Windows under Wine is neither tested nor officially supported by GAMS. Nevertheless, for experience Linux
users, we here provide some instructions on how to install a Windows GAMS system under Wine.
Many components of the GAMS system, including the IDE and solvers, should work under Wine. When running under Wine
on Linux, the GAMS distribution accepts GAMS licenses for Windows, Linux, or generic platforms. See here for a list of
known compatibility issues.
We encourage here the use of the 32-bit GAMS system instead of the 64-bit system, as also the 64-bit GAMS distribution
includes certain components, including the IDE, as 32-bit version only. Using these 32-bit components with a 64-bit Wine
system may not work.
1. Install a 32-bit Wine system and the winetricks tool using the package manager your distribution. If winetricks is
not available via the package manager, follow the instructions on http://wiki.winehq.org/winetricks
winetricks allfonts
3. If you had a pure 64-bit Linux system, then some 32-bit support libraries might be needed to run the 32-bit GAMS
system. On a CentOS 7 system, these libraries were installed via
4. Download the GAMS distribution for 32-bit Windows (windows x86 32.exe) from http://www.gams.com/download
5. Start the GAMS Windows installer by executing the following command from the command line:
Follow the instructions from the GAMS installer, possibly also installing a GAMS license file (see also Windows
Installation Notes).
6. You should now be able to run the GAMS IDE by executing gamside.exe via wine. On a system where the
WINEPREFIX has not been changed (default: /.wine) and with GAMS installed in the default location, the command
to start the IDE is
wine /.wine/drive c/GAMS/win32/24.8/gamside.exe
3 GAMS Installation Notes for Mac OS X 555
Additionally, there are instructions on how to install the GAMS Windows version using Wine.
3. If the mounted device does not open automatically, open it manually by double clicking on the device.
4. Drag the GAMS icon onto the Applications folder in order to copy the files to your Applications.
5. Optionally, create the license file gamslice.txt in the GAMS system directory. The license file is nowadays sent via
email, with instructions. If no license file is present, GAMS will still function in the demonstration mode but can only
solve small problems. Student and demonstration systems do not include a license file. A license file can easily be
added later, so if you cannot find a license file, you can safely proceed without one.
6. In order to test the GAMS installation, go to Applications and open the GAMS Terminal application found in the
GAMS installation directory. This small application opens a new terminal, adds the GAMS system directory to the
PATH environment variable, and changes the current directory to the home directory. Execute the following commands
to see if everything works as expected:
gamslib trnsport
gams trnsport
--- Job trnsport Start 06/26/14 11:24:56 24.3.1 r46409 DEX-DEG Mac x86_64/Darwin
GAMS 24.3.1 Copyright (C) 1987-2014 GAMS Development. All rights reserved
Licensee: ...
--- Starting compilation
--- trnsport.gms(69) 3 Mb
--- Starting execution: elapsed 0:00:00.024
--- trnsport.gms(45) 4 Mb
--- Generating LP model transport
--- trnsport.gms(66) 4 Mb
--- 6 rows 7 columns 19 non-zeroes
--- Executing CPLEX: elapsed 0:00:00.114
Reading data...
Starting Cplex...
556 Installation and System Notes
1. Obtain the GAMS distribution file, which is available from http://www.gams.com/download, in one large self-
extracting zip archive with a sfx.exe file extension, e.g., osx x64 64 sfx.exe. Check that it has the execute
permission set. If you are not sure how to do this, just type in the command chmod 755 osx x64 64 sfx.exe .
2. Choose a location where you want to create the GAMS system directory (the GAMS system directory is the
directory where the GAMS system files should reside). At this location the GAMS installer will create a sub-
directory with a name that indicates the distribution of GAMS you are installing. For example, if you are
installing the 24.3 distribution in /Applications/GAMS, the installer will create the GAMS system directory
/Applications/GAMS/gams24.3 osx x64 64 sfx. If the directory where you want to install GAMS is not below
your home directory, you may need to have root privileges on the machine.
3. Create the directory that should contain the GAMS system directory, for instance /Applications/GAMS. Change to
this directory (cd /Applications/GAMS). Make sure pwd returns the name of this directory correctly.
4. Run the distribution file, either from its current location or after transfering it to the directory that should contain the
GAMS system directory. By executing the distribution file, the GAMS distribution should be extracted. For example,
if you downloaded the distribution file into your home directory, you might execute the following commands:
mkdir /Applications/GAMS
cd /Applications/GAMS
~/osx_x64_64_sfx.exe
5. Optionally, create the license file gamslice.txt in the GAMS system directory. The license file is nowadays sent via
email, with instructions. If no license file is present, GAMS will still function in the demonstration mode but can only
solve small problems. Student and demonstration systems do not include a license file. A license file can easily be
added later, so if you cannot find a license file, you can safely proceed without one.
3 GAMS Installation Notes for Mac OS X 557
6. Change to the GAMS system directory and run the program ./gamsinst. It will prompt you for default solvers to be
used for each class of models. If possible, choose solvers you have licensed since unlicensed solvers will only run in
demonstration mode. These solver defaults can be changed or overridden by:
a. rerunning ./gamsinst and resetting the default values
b. setting a command line default, e.g., gams trnsport lp=bdmlp
c. an option statement in the GAMS model, e.g: option lp=bdmlp;
7. Add the GAMS system directory to your path (see below).
8. To test the installation, log in as a normal user and run a few models from your home directory, but not the GAMS
system directory:
9. If you move the GAMS system to another directory, remember to rerun ./gamsinst. It is also good practice to rerun
./gamsinst when you add or change your license file if this has changed the set of licensed solvers.
Access to GAMS
To run GAMS you must be able to execute the GAMS programs located in the GAMS system directory. There are several
ways to do this. Remember that the GAMS system directory in the examples below may not correspond to the directory
where you have installed your GAMS system.
1. If you are using the C shell (csh) and its variants you can modify your .cshrc file by adding the second of the two
lines given below:
2. Those of you using the Bourne (sh) or Korn (ksh) shells and their variants can modify their .profile file by adding
the second of the three lines below:
PATH=/your/previous/path/setting
PATH=$PATH:/Applications/GAMS/gams24.3_osx_x64_64_sfx # new
export PATH
If the .profile file does not exist yet, it needs to be created. You should log out and log in again after you have made
any changes to your path.
3. You may prefer to use an alias for the names of the programs instead of modifying the path as described above. C shell
users can use the following commands on the command line or in their .cshrc file:
The correct Bourne or Korn shell syntax (either command line or .profile) is:
alias gams=/Applications/GAMS/gams24.3_osx_x64_64_sfx/gams
alias gamslib=/Applications/GAMS/gams24.3_osx_x64_64_sfx/gamslib
Again, you should log out and log in in order to put the alias settings in .cshrc or .profile into effect.
4. Casual users can always type the absolute path names of the GAMS programs, e.g.:
/Applications/GAMS/gams24.3_osx_x64_64_sfx/gams trnsport
558 Installation and System Notes
Example
The following shows the log of a session, where a user downloads a GAMS 24.3.1 system and installs it un-
der Applications/GAMS/gams24.3 osx x64 64 sfx. It is assumed that a GAMS license file has been stored as
/Users/doe/gamsinst.txt.
doe@mac:/Users/doe$ curl -L -k -O \
http://d37drm4t2jghv5.cloudfront.net/distributions/24.3.1/macosx/osx_x64_64_sfx.exe
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 148M 100 148M 0 0 4374k 0 0:00:34 0:00:34 --:--:-- 5906k
doe@mac:/Users/doe$cd /Applications/GAMS
doe@mac:/Applications/GAMS$ ~/osx_x64_64_sfx.exe
UnZipSFX 5.52 of 28 February 2005, by Info-ZIP (http://www.info-zip.org).
creating: gams24.3_osx_x64_64_sfx/
inflating: gams24.3_osx_x64_64_sfx/sp2full.m
inflating: gams24.3_osx_x64_64_sfx/optpathnlp.def
inflating: gams24.3_osx_x64_64_sfx/MessageReceiverWindow.exe
inflating: gams24.3_osx_x64_64_sfx/hexdump
inflating: gams24.3_osx_x64_64_sfx/datalib
inflating: gams24.3_osx_x64_64_sfx/empsyntax.txt
inflating: gams24.3_osx_x64_64_sfx/optlindoglobal.html
...
inflating: gams24.3_osx_x64_64_sfx/apifiles/CSharp/DomainChecking/DomainChecking.cs
inflating: gams24.3_osx_x64_64_sfx/apifiles/CSharp/DomainChecking/DomainChecking.csproj
inflating: gams24.3_osx_x64_64_sfx/apifiles/CSharp/xp_example2.cs
inflating: gams24.3_osx_x64_64_sfx/optdicopt.html
doe@mac:/Applications/GAMS$cd gams24.3_osx_x64_64_sfx
doe@mac:/Applications/GAMS/gams24.3_osx_x64_64_sfx$cp ~/gamslice.txt .
doe@mac:/Applications/GAMS/gams24.3_osx_x64_64_sfx$./gamsinst
-----------------------------------------------------
gamsinst run on Wed Jun 25 19:25:29 2014
GAMS sysdir is "/Applications/GAMS/gams24.3_osx_x64_64_sfx"
...
Installed defaults:
LP: CPLEX
MIP: CPLEX
RMIP: CPLEX
3 GAMS Installation Notes for Mac OS X 559
NLP: CONOPT
MCP: PATH
MPEC: NLPEC
RMPEC: NLPEC
CNS: CONOPT
DNLP: CONOPT
RMINLP: CONOPT
MINLP: DICOPT
QCP: CONOPT
MIQCP: SBB
RMIQCP: CONOPT
EMP: JAMS
doe@mac:/Applications/GAMS/gams24.3_osx_x64_64_sfx$cd
doe@mac:/Users/doe$/Applications/GAMS/gams24.3_osx_x64_64_sfx/gamslib trnsport
Copy ASCII: trnsport.gms
doe@mac:/Users/doe$/Applications/GAMS/gams24.3_osx_x64_64_sfx/gams trnsport.gms
--- Job trnsport Start 06/26/14 11:24:56 24.3.1 r46409 DEX-DEG Mac x86_64/Darwin
GAMS 24.3.1 Copyright (C) 1987-2014 GAMS Development. All rights reserved
Licensee: ...
--- Starting compilation
--- trnsport.gms(69) 3 Mb
--- Starting execution: elapsed 0:00:00.024
--- trnsport.gms(45) 4 Mb
--- Generating LP model transport
--- trnsport.gms(66) 4 Mb
--- 6 rows 7 columns 19 non-zeroes
--- Executing CPLEX: elapsed 0:00:00.114
Reading data...
Starting Cplex...
Space for names approximately 0.00 Mb
560 Installation and System Notes
1. Download WineBottler.
2. Open with a double-click the file WineBottlerCombo .dmg.
3. Drag Wine and WineBottler into the Applications folder.
4. Download the current GAMS System for Windows 32 bit.
5. Do a right-click on windows x86 32.exe, then select Open With and Wine (default).
6. Choose Run directly in Users/<your username>/Wine Files and click Go.
7. If you run Wine the first time, this will take a few minutes. Then, the Setup - GAMS 24.8.5 dialog should open.
Follow the installation instructions from the setup assistant.
8. After installation is complete, open Finder and navigate to Places <your username> Wine Files
drive c Program Files GAMS24.8 (the default installation location).
9. Right-click on gamside.exe Open With Wine (default).
10. Choose Run directly in Users/<your username>/Wine Files and click Go.
Index
functions heapSize, 70
abs, 66 ifThen, 69
arccos, 66 jdate, 69
arcsin, 66 jnow, 69
arctan, 66 jobHandle, 70
arctan2, 66 jobKill, 70
Beta, 66 jobStatus, 70
betaReg, 66 jobTerminate, 70
binomial, 66 jstart, 69
bool and, 69 jtime, 69
bool eqv, 69 licenseLevel, 70
bool imp, 69 licenseStatus, 70
bool not(x), 69 log, 66
bool or, 69 log10, 66
bool xor, 69 log2, 66
cdfBVN, 360 logBeta, 66
cdfTVN, 360 logGamma, 66
cdfUVN, 360 LogOption, 360
ceil, 66 mapVal, 66
centropy, 66 max, 66
cos, 66 maxExecError, 70
cosh, 66 min, 66
cosine, 359 mod, 66
cvPower, 66 ncpCM, 66
div, 66 ncpF, 66
div0, 66 ncpVUpow, 66
eDist, 66 ncpVUsin, 66
entropy, 66 normal, 66
errorf, 66 numCores, 70
errorLevel, 70 pdfBVN, 360
execError, 70 pdfTVN, 360
execSeed, 66 pdfUVN, 360
exp, 66 pi, 66, 359
fact, 66 poly, 66
fitFunc, 353 power, 66
fitParam, 353 pwpFunc, 354
floor, 66 randBinomial, 66
frac, 66 randLinear, 66
gamma, 66 randTriangle, 66
gammaReg, 66 rel eq, 69
gamsRelease, 70 rel ge, 69
gamsVersion, 70 rel gt, 69
gdow, 69 rel le, 69
ghour, 69 rel lt, 69
gleap, 69 rel ne, 69
gmillisec, 69 round, 66
gminute, 69 rPower, 66
gmonth, 69 setMode, 359
gsecond, 69 sigmoid, 66
gyear, 69 sign, 66
handleCollect, 70 signPower, 66
handleDelete, 70 sin, 66
handleStatus, 70 sine, 359
handleSubmit, 70 sinh, 66
heapFree, 70 sleep, 70
heapLimit, 70 slexp, 66
INDEX 565
numEqu, 96 RMIQCP, 88
numInfes, 96 RMPEC, 88
numNLIns, 96 model exchange
numNLNZ, 96 latex, 441
numNOpt, 96 model status, 113
numNZ, 96 error no solution, 114
numRedef, 96 error unknown, 114
numVar, 96 feasible solution, 114
numVarProj, 96 infeasible, 114
objEst, 96 integer
objVal, 96 infeasible, 114
optCA, 93 integer solution, 114
optCR, 93 intermediate infeasible, 114
optFile, 93 intermediate noninteger, 114
priorOpt, 93 locally optimal, 114
procUsed, 96 optimal, 114
real1, 93 unbounded, 114
real2, 93 MPEC, model type, 88
real3, 93 multiple solves, 99
real4, 93
real5, 93 na, extended range value, 40, 73
reform, 93 ncpCM, function, 66
resGen, 96 ncpF, function, 66
resLim, 93 ncpVUpow, function, 66
resUsd, 96 ncpVUsin, function, 66
rObj, 96 ne, relational operator, 124
savePoint, 93 negBinomial, distribution, 355, 357
scaleOpt, 93 NLP, model type, 88
solPrint, 93 nonlinear
equations, 110
solveLink, 93
programming, 77, 88
solveOpt, 93
nopt, solution marker, 118
solveStat, 96
normal
sumInfes, 96
completion(a solver status), 115
sysOut, 93
normal, distribution, 355, 357
threads, 93
normal, function, 66
tolInfeas, 93
not, logical operator, 124
tolInfRep, 93
not, relational operator, 136
tolProj, 93
number of rows and columns in display, 150
tryInt, 93
numCores, function, 70
tryLinear, 93
workFactor, 93 option
workSpace, 93 introduction, 313
model classification syntax, 313
CNS, 88 or, logical operator, 124
DNLP, 88 or, relational operator, 136
EMP, 88 ORANI, example from GAMSlib, 46
LP, 88 ordered set
MCP, 88 card operator, 141
MINLP, 88 circular lag and lead operator, 143
MIP, 88 introduction, 139
MIQCP, 88 lags and leads in assignments, 141
MPEC, 88 lags and leads in equations, 143
NLP, 88 linear lag and lead operator, 142
QCP, 88 ord operator, 140
RMINLP, 88
RMIP, 88 parameter
568 INDEX
variable
binary, 76
free, 76
integer, 76
negative, 76
positive, 76
statement, 75
statements, 76
styles for declaration, 76
suffix, 77
syntax of declaration, 75
types, 76
variable attributes
activity level (.l), 77
branching priority value (.prior), 77
fixed value (.fx), 77
lower bound (.lo), 77
marginal or dual value (.m), 77
scale value (.scale), 77
upper bound (.up), 77
variable bounds
activity level, 78
fixing, 78
vcPower, function, 66