GAMS Reader

1.1.     Introduction

GAMS is a software package to solve systems of equations. GAMS stands for General Algebraic Modelling System and is constructed by the GAMS Development Corporation. GAMS contains different solvers for different purposes.

The homepage of the GAMS corporation (www.gams.com) contains a lot of useful information. From the homepage, a full user guide can be downloaded at www.gams.com/docs/document.htm; the user guide contains the syntax for all GAMS commands and very helpful as a reference when writing GAMS models. Note that the user guide is also available via the Help function in GAMS-IDE.

There is a free version of GAMS available for installation on your own computer. This is a limited version of GAMS, which cannot solve large problems, but it may be handy when you are building proto-type models. It is available for download at http://www.gams.com/download.

1.2.     For what type of problems can GAMS be used?

GAMS has its origins in economic modelling, but this does not mean that the models you specify have to be in the field of economics. As you can see the subject index of the GAMS model library -  http://www.gams.com/modlib/modlib.htm - GAMS can provide a support optimisation program for the several fields.

Specifying an economic model means that we have to write down one or more equations with some economic relationship. This relationship can be between labour demand and wages, between demand and supply of a good, et cetera. The geographical scope of the model can range from writing an economic model for an individual firm to a model that tries to describe the global economy. Many models take the scope of a national economy.

1.3.     Working with GAMS-IDE

Most users of GAMS can run the system in the Integrated Development Environment (IDE).

When GAMS-IDE is started, a window will appear with a menu bar along the top and a main Edit Window for GAMS applications. As with most such systems, input and output operations are controlled by the File pull down menu, with other menu items used in edit operations, and in running the GAMS system.

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

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


The GAMS-IDE without any open files looks as follows:

 


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

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

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

Different parts of GAMS are presented in different colours. For example, all text that is written as a comment appears in grey, keywords are in blue and set elements are in green (at least in the lines where they are defined).

 

 

1.4.     The general structure of GAMS programs

The first step in modelling in GAMS is to write an input file. Though it is not strictly necessary, normally a GAMS input file has a file-extension .gms. You write the input file, run the model in GAMS and look at the output file for the results (the output file has an extension .lst).

The general structure of a simple GAMS input file contains the following elements:

PARAMETERS

{gives the data or exogenous constants of the model; these values are fixed}

VARIABLES

{indicates the variables that will be determined (calculated) within the model}

EQUATIONS

{first, the equations have to be declared, then they are defined}

MODEL

{the model is given a name}

SOLVE

{the solution mode is specified, as well as a declaration whether the optimand should be maximised or minimised}

Each of these elements can exist more than once in a single GAMS model.

The restrictions and special meanings of these words are all together called the syntax of a model. GAMS is a computer package and will only understand what you want if you write your model in the correct syntax.

The basic portions of GAMS code are now discussed in more detail.

PARAMETERS

The first step in writing a GAMS model is to provide the constant elements (also called ‘exogenous coefficients’). These are data that are not determined within the model, but they have a fixed value that you have to provide.

There are two stages in specifying parameters, first you must declare them by making a list of all parameters and closing the list with a semi-colon, and then you define the values and close each definition with a semicolon.  ( You can learn more about the use of semicolon at the end of this chapter.)

Suppose you have a parameter A and want to give it a value of 3. Then, the GAMS code is

PARAMETERS

A     Explanatory text on the meaning of A;

A = 3;

The first line is the ‘code-word’, telling GAMS which part of the model will follow. In this case, the ‘code-word’ is PARAMETERS. First give the name of the parameter, then you may write some explanatory text on the meaning (though this is not necessary). In a new section you define the value of the parameter.

Note that there is an alternative way of assigning values to parameters (and scalars). In the declaration, you can directly specify the value between slashes:

PARAMETERS

A     Explanatory text on the meaning of A      /3/;

Constant elements can be specified in several ways: as single parameters called scalars, (if applicable) as vector parameters or as tables (these will be introduced later). GAMS is indifferent to the way the constant elements are specified, but you’ll find that all types have their advantages. The following rules of thumb apply. First, tables are the most compact, so if you can use tables, do so. But only put data together into one table that have some cohesion with each other. Second, use parameters for constants with two or more dimensions (the dimensions are given by the indices used) and, finally, scalars are used for single values that do not change (the constants in the narrow sense).

Notice that you don’t write a semi-colon after each line, but only after the last line of the block with declarations. You can write a block of variables in the same way (see below).

VARIABLES

The variables are what you are really interested in as a modeller. These are the things that are determined endogenously within the model, and the value of which you cannot calculate beforehand (well, unless you write a very, very simple model). The values of the variables are determined by solving the equations. However, you first have to tell GAMS what the names of the variables are. In this declaration of the variables, you can also provide an explanatory text to the variable, to help you understand what the meaning of the variable is. The GAMS code is:

VARIABLES

      X1    Explanatory text on the meaning of X1

      X2    Explanatory text on the meaning of X2

      Y     Explanatory text on the meaning of Y;

So just as with the parameters, you first write the ‘code-word’, then provide the variables line-by-line. You can provide the explanatory text, but this is not necessary; the value of the variables are calculated by the model therefore you do not have to define value here.

Note that if you want to build more complex models, it becomes important to choose good names for your parameters and variables. Using the words “supply” and “demand” instead of just “s” and “d” helps you in later stages to read the model code. Try to keep the names and structure of the code as logical as possible.

EQUATIONS declaration

The treatment of the equations is a little more complicated in GAMS. The thing to remember is that you have to take two steps: first, you declare the equations, and, second, you write the equation itself in the equation definition section. The declaration of the equations is straightforward. You can use any name you want to declare the equations. Most people has some standard way of naming the equations. For example, a useful way of naming the equations is to take the variable that is determined by the equation and put a ‘Q’ in front of the variable name.

You may find it easier to you write down the equations themselves first, and then just above the equations you write the declarations.

So, in GAMS code, you could have

EQUATIONS

      QX1   Explanatory text on the meaning of the equation for X1

      QX2   Explanatory text on the meaning of the equation for X2

      QY    Explanatory text on the meaning of the equation for Y;

Equations definition

The core of any model is given by the equations that have to be solved. In GAMS, you can write the equations fairly straightforward. You write them one by one in the following way:

QX1.. X1 =L= A;

QX2.. X2 =E= 5;

QY..  Y =E= X1 + X2;

 

In the example above, the first equation determines the value of X1. The equation is named QX1, and states that the value of X1 should be less than A. The second equation tells us that X2 should equal 5. In the third equation, the value of Y is determined as the sum of X1 and X2.

You can use three types of equations:

·         the left-hand-side should be less than or equal to (=L=),

·         greater than or equal to (=G=) or

·         equal to (=E=) the right-hand-side.

This is a very simple model that you could calculate by hand. But the structure of the equations is very general, so writing much more complex model will not lead to much more complex GAMS code. For example, you can do multiplication, raise a variable or scalar to some power, et cetera.

The MODEL statement

The MODEL statement is quite simple: you think of a name to give to the model, for example TEST. Any other name can be used, as long as it’s not too long and does not have ‘special’ characters. You have to tell GAMS which equations are part of the model TEST. Normally, you want to include all equations, and then the MODEL statement looks like:

MODEL TEST /ALL/;

ALL refers to that you use all the equations, you can also specify a submodel here by listing all equations you want to include in the model. (Separate the equation names with commas).

The SOLVE statement

The SOLVE statement is to tell GAMS to solve the model. You provide the ‘code-word’ SOLVE, the model name, the solution mode, the optimand and whether to maximise or minimise.

For example, if we want to solve model TEST by maximising Y, using DNLP as the solution mode, we write:

SOLVE TEST USING DNLP MAXIMIZING Y;

The solution mode tells what type of model you have specified: if your model is linear, use linear programming (LP); if it is non-linear, use non-linear programming (NLP or DNLP). There are more model types, but we will not discuss them in this reader. Throughout this reader, we will use DNLP as the solution mode.

The optimand is the variable that should be maximised or minimised. GAMS will try and find that solution to the model where the value of Y is as high (MAXIMIZE) or low (MINIMIZE) as possible.

Use of the semi-colon

When you run the input file, GAMS will read the file you wrote line by line. To tell GAMS that the end of a line has arrived, use a semi-colon (“;”). The semi-colon is used to tell GAMS the end of a command is reached. In principle, you should end all lines with a semi-colon, except when you declare a list of parameters, variables or equations. Then, this list is regarded as a single block and you should end the block with a semi-colon. For example, if you want to include a second parameter B, you could write:

PARAMETERS

A     Explanatory text on the meaning of A;

A = 3;

 

PARAMETERS

B     Explanatory text on the meaning of B;

B = 5;

But it is more convenient to write it as a list of scalars and use a semi-colon only at the end of the list:

PARAMETERS

A     Explanatory text on the meaning of A

B     Explanatory text on the meaning of B;

      A = 3;

      B = 5;

The definitions of the equations cannot be treated as a block, so you should write a semi-colon after each equation definition.

The correct use of the semi-colon will become rapidly clear to you when you start writing your own models, as GAMS will come with an error message if you made a mistake. Still, always be careful in the syntax of your models.

Brief summary:

Use semi-colon

Do NOT use semi-colon

- after the end of each declaration block (parameters, variables, equations, etc.)

- after each line within a block (for blocks of parameters, variables, etc.)

- after each defined parameter

- after each declared scalar and parameter, only at the end of the block

- after each defined table

- after each declared variable

- after each defined equation

- after each declared equation

 

The complete code

So, now we have specified a complete model in GAMS code. The full model looks as follows:

Note that the order in which the portions of GAMS code can be specified is quite flexible. The principle that has to be obeyed is that all elements have to be declared before you can use them; so, for instance, an equation declaration must precede the equation specification.

True, this model is not very exiting and you will not be amazed that GAMS can actually compute that the optimal value of Y is 8. But this is just the general structure. Using the same syntax, you can specify much more interesting models and solve difficult systems of equations that you cannot calculate by hand.

1.5.     Scenarios and sensitivity analysis

Most model simulations do not stop after one solve of the model. Rather, the first solve is used as a reference scenario, that represents the current situation (or, in a dynamic model, the baseline projection represents the most likely development of the variables over time). Then, a so-called counter-factual analysis is done: some parameter values in the model or equation specifications are changed, the changed model is run and the new results are compared to the reference results. This can all be done within one GAMS model file.

The two major types of counter-factual analyses are scenario analysis (sometimes called uncertainty analysis) and sensitivity analysis. The basic difference between these types is that scenario analysis tries to answer questions of the type ‘what happens if one or more elements (or equations) in the model change’, while sensitivity analysis tries to answer ‘what is the consequence of a misspecification of some parameter value’.

In a scenario analysis, several alternative model specifications are compared to each other. These scenarios may differ due to differences in parameter values, but also due to differences in the model equations. In principle, each of the scenarios specified may be equally viable (though they not always are). Often, three or four scenarios are calculated to show the extremes within which the real value will probably lie (i.e. the scenarios are used as ‘corners of the playing field’). The scenarios specified may be used to do policy recommendations. For example, if we lower the tax rate on labour with 1%, total employment may go up with x%. Of course, these policy recommendations are only valid within the boundaries and assumptions that are made in the model.

A sensitivity analysis has another purpose: an (individual) parameter value is changed to analyse the effects of the value chosen on the model results. This gives a clue on the robustness of the model with respect to the specification of the model. For example, the emissions of phosphor from agriculture in the Netherlands may be estimated at 0.31 grams per guilder of agricultural production per year, which results in total phosphorous emissions from agriculture of 132 million kilograms per year. To investigate how the total emissions will change if the emissions per guilder of production are 1% higher, one can do a sensitivity analysis. In this example, the relationship is linear and the result straightforward: total emissions will also be 1% higher (133.32 million kilograms). But imagine a more complex model where relationships are not all linear. For example, what is the effect of a slight misspecification of the phosphor content of animal feed on total deposition of phosphor in water? Then, the results of a sensitivity analysis cannot be predicted so easily, and you need to simulate the sensitivity analysis in the GAMS program.

2.     Learning exercises

2.1.     Introductory level

The first exercises with GAMS are intended to familiarise you with the basic structure of GAMS and the IDE interface. The goal is that you are able to write, run and read GAMS models and their output.

 

Exercise  2.1.1. Starting GAMS-IDE

The first exercise should be easy:

Start the GAMS interface program GAMS-IDE by clicking on the GAMS-IDE button (the icon says IDE in red and has two black squares below the name: ).

Go to the right directory and make a new (or open an existing) project.

If there have not been created any projects on this machine before, you’ll get a window asking you to provide a project or name a new project. Go to your own directory[1] and make a new project (e.g. my project.gpr).

If GAMS-IDE opens with a different project with open files, close any files that are open by selecting “File / Close” from then menu, or by clicking the small x in the right-hand corner of the window containing the file. Warning: do not press the small x in the upper right-hand corner, as this will close GAMS-IDE and not just the file. Now you can make a new project (or open the existing project).

Actually, you can switch between projects without closing your files first. In this case next time you open your project these files are automatically opened.

The next step is to create a new file by selecting “File / New” from the menu. Save this empty file by selecting “File / Save” from the menu, or by pressing the Save button () on the toolbar. Give the file the name “intro”.

The program will automatically add the extension “.gms”. You could use other names, but for the practical it is useful that you stick to the names suggested here.

Exercise  2.1.2. The basic blocks of writing a model in the IDE

If necessary, open the file “intro.gms” in the project you chose in Exercise 3.1.1. Type the simple model as presented at the end of Section 1.4. (see page 10) Write all the basic blocks of code (parameters, variables, equations, model, solve). Carefully check for typing and other errors.

Exercise  2.1.3. Reading the process window

Run this GAMS file by selecting “File / Run” from the menu, by pressing the F9-key or by clicking on the button on the toolbar ().

The .gms-file is automatically saved before running it.

A process window appears. This window displays the log of the model run: it tells you what GAMS is doing, it shows information on the iterations of the solver and in this window you can read whether GAMS has solved the model correctly. Please take a careful look at the completion status of the model: if the process window informs you (at the bottom) that the model has ‘normal completion’ this does not necessarily mean that an optimal solution was found. So for each solve, carefully check that an optimal solution was found.

Depending on the settings of the project, the process window automatically moves to the last line written (it automatically scrolls down when GAMS moves on), or it stays at the top of the log. In the first case, you can manually scroll back up to look at earlier information, and in the latter case you can manually scroll down. (You can change this setting by selecting “File / Options” from the menu, then checking “Update process window” from the “execute” tab).

Exercise  2.1.4. Reading the listing file

When you run a GAMS file, a so-called listing file is automatically written by GAMS. So when you ran the file intro.gms, GAMS made the file intro.lst in the directory where the project is located (i.e. in the working directory).

Note: do not mix up the log file and the listing file. The log file is what GAMS-IDE shows during the run; the listing file is where GAMS stores the results of your model run.

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

Open the listing file intro.lst.

Read the output file carefully by following each item of the discussion of the general structure of a GAMS output file below.

The general structure of a GAMS output file is[2]:

1.         Echo print.

The first part of a list file gives a copy of the GAMS input file that has been run. For the sake of future reference (in case of errors) GAMS puts line numbers on the left hand side of the list file.

2.         Error messages. {Only available if there are mistakes in the model!}

If you have made any errors then these are displayed with a dollar sign ($) followed by a number. The error number and an explanation of the error is given after the echo print. If any errors have been made, then these should be corrected before proceeding. Errors are the topic of the next exercises.

3.         Reference maps.

The next section of the list file is a pair of reference maps that contain summaries and analyses of the input file for the purposes of debugging and documentation. 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 identifiers (e.g. scalars/parameters, variables, equations) of the model. The second reference map is a list of model identifiers grouped by type and listed with their associated documentary text.

4.         Equation listing.

If no errors have been made then the list file will also contain an equation listing. The equations listing allows you to check whether GAMS has indeed generated the model from your input file that you intended.

5.         Model Statistics.

This is the last section of output that GAMS produces before invoking the solver is a group of statistics about the model's size.

6.         Solve summary.

After the solver executes, GAMS prints out a brief status report. It is important to always check the Solver Status and the Model Status to verify that GAMS has found the optimal solution.

 7.        Solution reports.

This is the part that you are of course most interested in. The solution report of the variables gives the results of the optimisation problem that was solved in GAMS. The report presents lower, level, upper and marginal values, where lower and upper will give any lower and upper bounds that have been imposed. Level gives the optimal value for the variable, i.e. the solution. The value under marginal gives the dual value (shadow price) of the variable; this is the first derivative of the objective value to the level of the variable.

Read the solution report of the file intro. What are the optimal values, lower and upper bounds of the variables?

8.         Report summary.

At the end of the solution report, a report summary is given. The desired report summary should be as follows :

**** REPORT SUMMARY :   0     NONOPT

                  0     INFEASIBLE

                        0     UNBOUNDED

                        0     ERRORS

 

If you have made any errors, then correct them now.

Exercise  2.1.5. Debugging a compilation error

If you have carefully carried out the exercises above, you have not seen any errors yet. So in this exercise, we will make one intentionally.

Remove the semi-colon after equation QX1. Run the model again and see what the process window tells you.

Double-click the red line with the first error in the process window. You automatically jump to the file intro.gms and are near the point where the error is (in this case, you’ll jump to the line below the error). Double-click on the error message in the process window, just below the red line. The listing file appears and the error code is shown. More below in the listing file, you’ll find an explanation of the error codes, so you can check what type of error you’ve made.

Fix the error and save the correct file.

(If only you were always so lucky to know what the error is straight away.)

Trying to fix any errors you get when building a model is called debugging. This debugging is often the hardest and most time consuming part of the whole process of model building. Through learning-by-doing you’ll get better at debugging as you get more experience. So don’t feel bad if it takes you forever to fix a simple error when you’ve just started specifying GAMS model.

Exercise  2.1.6. Debugging a logical error

A second type of errors commonly made can be labelled as ‘logical errors’. These errors are not a conflict with the GAMS syntax, but a misformulation of the model itself. These logical errors are sometimes hard to find, especially if you do not fully understand the logic behind the model. And sometimes you do not even get an error, but you get just the wrong results. Therefore, always think hard about the specification of the model and make sure the specification is alright.

In this exercise we’ll find out what happens if we want to minimise Y instead of maximising it.

Replace ‘MAXIMIZE’ with ‘MINIMIZE’ in the SOLVE statement.

Explain why the model fails to get an optimal solution. Look at the listing file to find out what the model status is.

Repair the error and save the correct file.

Exercise  2.1.7. Building a new model

Now that you have learned to build and debug a GAMS model, you should be able to implement your first model in GAMS. Let’s start with a general description of the model:

Due to the existence of open access pastures there exists a tragedy of the commons. In west Africa pasture productivity is threatened by overgrazing, a headtax is envisioned to induce farmers to lower their livestock numbers. If we consider an area of 1000 hectares the present number of cattle is 2000 (without a headtax). The number of cattle supply decreases with 50 for each currency unit of tax imposed. The stocking rate is defined as the number of cattle per hectare. The damage per hectare due to grazing is the square of the stocking rate and valued at cost of 24 currency units. Livestock keeping itself is seen as a social beneficiary activity and valued at 50 currency units per head of cattle. Taxation is seen as undesirable. Hence, the social objective function consists of the positive effects of cattle keeping minus the tax burden and minus the value of damage due to overgrazing.

Implement this model in a new GAMS file called “intro2.gms”.

Note: if the model is solved properly, it will give a MODEL STATUS 2: locally optimal. This does not mean that there are 2 local optima. In non-linear models, like this one, GAMS will never give a model status 1: optimal.

Hints:

§         you can use the following parameters: pastures (=1000), cattle0 (=2000), taxcoef(=-50), benefit (=50), cost (=24) and tax (=30).

§         you need the following variables: damage, st_rate, cattle, obj. Each variable gets its own equation based on the description above:
eq_cat..  cattle =E= cattle0 + taxcoef*tax;
eq_sr..  st_rate =E= cattle/pastures;
eq_dam.. damage =E= cost*st_rate*st_rate*pastures;
eq_obj.. obj =E= (benefit-tax)*cattle – damage;

Change the tax rate (tax) from 30 to 20. How does this influence the social objective (obj)? What is the value for the social objective if the tax rate is 10? And if the tax rate is 0?

Exercise  2.1.8. Understanding what you have done

This exercise is to test whether you understand what you have been doing so far.

Hint: use the information in the appendix to check your model results.

a.  Go back to the file intro (if necessary, open the file again). Replace the defined value for  variable X2 in the equation by a parameter B that has the same value (5). Make all the necessary changes to the model so that the model works and the same values for X1 and Y result. Check whether GAMS has found an optimal solution. Repair any errors you get underway.

b. As a final test at this level, rewrite the model to have an environmental-economic meaning:

Replace equation QX1 with QPRD.. PRD =G= 100;

Replace equation QY with QEMIS.. EMIS =E= CO2+OTHER;

Add the equation QCO2.. CO2 =E= coef*PRD;

Rename the model to CLIMATE;

Change the objective from maximizing Y to minimizing EMIS;

Make sure all parameters and variables are declared and the parameters are given a value (OTHER=5 and coef=0.03) and remove all redundant code.

Run the model and analyse the results.

If you feel confident that you grasp the exercises above, go to the next level. If not, try to play around with the model some more (for example, you can specify parameter OTHER as a variable).

2.2.     Intermediate level

When you have successfully completed the introductory exercises, you are now ready to learn more of the syntax that is used in GAMS to specify your models. Step by step, elements of the GAMS language will be added, building up from the simplest model to technically more sophisticated models. The goal of the Intermediate exercises is to enable you to specify a model in GAMS based on a well-defined idea of the model characteristics. It is assumed that you will run the model after each exercise and check the solution listing for changes.

Beginner modellers are recommended to use the more sophisticated syntax as much as possible (that is, if you understand the meaning), as this will make things much easier for you when you start building larger models.

Exercise  2.2.1. DISPLAY your results

To make the results more convenient to read, you can use a display statement. In our example, we’re not really interested in the value of PRD or OTHER, but only in the values of CO2 and EMIS. So we add a new line at the end of our code to display the value of variable EMIS. You have to specify whether you are interested in the level value of EMIS (then use DISPLAY EMIS.L), it’s lower bound (EMIS.LO), it’s upper bound (EMIS.UP) or the marginal value (EMIS.M). Normally, you are only interested in the level value (EMIS.L). Note that these four categories are all represented in the solution listing as discussed above.

Now, if we also want to display the value of parameter OTHER, we do not have to specify the .L since parameters only have a value, not any bounds or marginal value. You can include more elements in one DISPLAY statement by separating them with commas. Combined, this should do the trick:

At the end of the code, add the following line:

DISPLAY EMIS.L,OTHER;

Save the model under the new name “exercise_321” by selecting File / Save As from the menu and run the model.

Look at the listing file and especially at the results of the display statement. Does it look similar to the previous results?

Save each model with the name of the exercise to identify it easily in the future. At the end of this course you will have a cluster of files in your folder.

Exercise  2.2.2. Commenting out single lines

If you want to comment out a single line, so that GAMS does not read the line, put an asterisk at the beginning of the line.

Between the declaration of the equations and the equation themselves, add the following line:

* The equation definition block:

Commenting out  lines is useful to add some explanations between the GAMS code, but can also be used to remove a part of the code from the model without actually throwing away the text. In this way, you can easily reactivate the line you have commented out if you want to.

Exercise  2.2.3. Using SCALARS

When you define one single parameter you can use scalars. Parameter OTHER=5 can also be defined with a GAMS code as:

SCALARS

OTHER Emissions of other greenhouse gasses      /5/;

As you can see, the value of the scalar is given directly in the declaration of the scalar, between slashes. This way of giving values to scalars is convenient (and widely used), but you can also skip the assignment of the value in this statement and assign the value in a separate statement:

SCALARS

OTHER Emissions of other greenhouse gasses;

OTHER = 5;

Both ways are equivalent. You can use the direct assignment of values also for parameters, though there it is often less convenient (and not common).

Note that if you want to change the value of a scalar or parameter later in the model, you cannot use slashes, but have to stick to the separate assignment statement using the equal sign.

Take the climate model and define the emission coefficient coef and other as a scalars.

If you have a single parameter with only a single value, you can choose whether you define it as a scalar or as a parameter.

Exercise  2.2.4. Solving more than one model

The first three exercises at this intermediate level were rather superficial, though in practice they turn out to be very useful. In this exercise, you’ll learn how to do so-called counter-factual simulations, i.e. you’ll learn how to do two different simulations with the same model. This involves solving the model twice and comparing the stored results.

Suppose that we want to know what influence the scalar OTHER has on the results for EMIS. We store the results of both solves into parameters and can then compare the parameter values (this is necessary since GAMS overwrites the results of the first solve, the variable levels, during the second solve).

This is done as the following:

(i)                  after the solve statement, declare a new parameter RES1 and assign it to have the same value as EMIS.L;
in GAMS syntax:
RES1 = EMIS.L;

(ii)                change the value of OTHER to 7 by adding a new command at the end of your code (after the solve statement!);
in GAMS syntax:
OTHER = 7;

(iii)               give another solve statement;

(iv)              declare a new parameter RES2 and give it the value of EMIS.L (which has changed after this second solve; hence, you have to give the value to RES2 after the second solve statement);

(v)                compare RES1 and RES2 (use a DISPLAY statement);

(vi)              analyse the result.

Note that you also learned how to assign a new value to a parameter or scalar; the syntax follows the obvious mathematical notation.

Exercise  2.2.5. Using  multidimensional PARAMETERS

We already introduced how to use scalars and single parameters, now we will introduce two dimensional  parameters.

Replace the declarations of scalars RES1 and RES2 by PARAMETER RES;

Store the value of EMIS after the first solve in the parameter:

RES(“1st solve”) = EMIS.L;

Note: You can declare RES only once. In this case declare it where the declaration of RES1 was before.

The text between brackets is called the identifier of the parameter: it tells GAMS which entry in the vector should be used.

Store the value of EMIS after the second solve in the same parameter, but using a different identifier:

RES(“2nd solve”) = EMIS.L;

Change the display statement to display RES and not RES1 and RES2.

The use of the parameter instead of two scalars has the major advantage that the model becomes more compact: less lines are needed and items that belong together are stored together. For small models, this is not so much an issue, but for larger models this may increase the readability of the model significantly.

Exercise  2.2.6. SETS and vector specification

In the exercise above, we specified a parameter with two distinct values, using an identifier between brackets. But we did not specify any domain within which this parameter identifier should lie. Think of the domain as all identifiers that are allowed for the parameter, i.e. it gives which elements are included in the vector that makes up the parameter.

Such a domain can be specified using the SET statement. The SET statement gives the index of the parameter, the list of all identifiers that are possible.

In the exercise above, two identifiers are possible for parameter RES: “1ST SOLVE” and “2ND SOLVE”. So parameter RES is a vector with 2 values, and the domain is given by the set {“1ST SOLVE”, “2ND SOLVE”}.

At the beginning of the model code, declare a SET called SOL, and list all possible elements between slashes:

SETS

          SOL       List of all solves

                    /"1st solve", "2nd solve"/

Next, in the declaration of the parameter RES, tell GAMS that only identifiers that are an element of set SOL are allowed, by replacing RES with RES(SOL); you do not have to change the commands where the elements of RES are given a value.

Now lets go one step further with the use of sets. In economic models, sets are often used to distinguish production sectors. Up to now, we’ve had only one production value, PRD. Suppose that there are three production sectors that each produce. Then the variable PRD can be sectoral production, or in GAMS syntax, PRD becomes PRD(J).This influences the model at several places: first, a new set,  J, has to be introduced, containing three elements; then, the corresponding variables and equations have to be declared and specified for each element of J; and finally, the equation specifications are changed.

Note: the following changes are within the existing code; do not add these lines to the end of the file.

 

§         Change the model to include a new set J with 3 elements (1, 2 and 3)
(at the top of your code);

§         declare the existing variable PRD and equation QPRD as a vector over J (add (J));

§         include a new parameter PRD_DATA(J) to define that sectors 1, 2 and 3 produce 10, 50 and 40, respectively:

§         PARAMETER
PRD_DATA(J);

   PRD_DATA(“1”) = 10;
   PRD_DATA(“2”) = 50;
   PRD_DATA(“3”) = 40;

§         change the equations QPRD such that it uses these sectoral data:
QPRD(J).. PRD(J) =G= PRD_DATA(J);

§         Finally, change equation QCO2 such that all production values contribute to the emissions:
QCO2.. CO2 =E= coef*(PRD(“1”)+PRD(“2”)+PRD(“3”));

Exercise  2.2.7. Summing over an index

The summation of the production values just introduced can be rather cumbersome if the number of sectors becomes large. Therefore, it is often more useful to use the SUM command. You can sum any parameter or variable over the corresponding set: for instance, summing variable PRD over the set J is done by SUM(J, PRD(J)) .

Change the equation QCO2 to include a sum of PRD over J.

Exercise  2.2.8. Including time: a dynamic specification

In this exercise, we add another set to account for time. All parameters and variables are given an additional index, T, so that they are specified for each period of time. As you cannot give an index to a scalar, COEF and OTHER now have to be specified as parameter. Also, the production variable PRD now gets two indexes: J and T. This is one of the strong points of GAMS: you can write PRD(J, T) and GAMS will interpret it as a whole matrix of all possible combinations of J and T; you do not have to write all elements by hand.

Introduce a new set T that has elements 2000 to 2004. This is most easily done by writing /2000*2004/ as possible elements of T. The star indicates that all values between 2000 and 2004 are also allowed.

Change the SCALAR statement into a PARAMETER statement and add time to COEF and OTHER. Give separate commands to specify the values of these new parameters.

This parameter block now looks something like this:

PARAMETER

      coef(T)     Emission coefficient CO2

      OTHER(T)    Emissions of other greenhouse gasses;

coef(T)  = 0.03;

OTHER(T) = 5;

Add an index T to all parameters, variables and equations.

Do NOT run the model yet, but read on.

Note that
1) parameter RES now contains two indices:
RES(T,SOL)
2) you have to write
EMIS.L(T) and not EMIS(T).L in the code, and
3) you should never add the index, in this case
(T), in the DISPLAY statement.

Now we have a new problem: we can no longer use EMIS as the variable to be minimised, as there is more than one value of EMIS. So, we introduce a new variable and a new equation summing EMIS over time. This new variable can then be the quantity to be minimised.

Add a variable TOTEMIS and an equation QTOTEMIS stating that TOTEMIS equals the sum of EMIS over time. Make TOTEMIS the variable to be minimised in both solves.

Exercise  2.2.9. Using TABLES for data input

You can provide data for a parameter with a separate command for each element, or by using a formula (the easiest formula is to give each element the same value, as in the exercise above). However, if you know the values of the elements you can also write the values in the form of a table. Tables are declared by the TABLE statement and are given a name just like parameters, sets, equations, et cetera. Tables are two-dimensional: columns and rows. In the declaration, the first index describes the rows and the second index the columns. You can use a star (*) if either the columns or rows are not made up of a set.

In the following example the table DATA is declared with row elements A and B and the column is the set T:

TABLE     Data(*,T)

          2000      2001      2002      2003      2004

A_DATA     3         4         5         6         7  

B_DATA     1         1         1         1         1;

Now we can get the data of the first row out of the table into the parameter X as follows:

X(T) = Data("A_DATA",T);

In our model, we suppose we have production values for each of the sectors.

Add the following table:

TABLE DATA(J,T)     Input data for PRD

         2000      2001      2002      2003      2004

1         10        11        12        13        14

2         50        52        54        56        58

3         40        42        44        46        48;

Put the values from the table in the parameter PRD_DATA(J,T):

PRD_DATA(J,T) = DATA(J,T);

Analyse the results from the model solutions.

Exercise  2.2.10. Defining POSITIVE VARIABLES

If you know that some variables cannot be negative, you can tell GAMS that they are POSITIVE VARIABLES (by using the statement with this name). All variables can be included in this statement, except for the variable that is optimised. The effect of this statement is only that GAMS solves the model quicker; the numerical results will not be different.

Add a command, after the variable declarations but before the model statement, that states that CO2, EMIS and PRD are positive.

Remember that the optimand variable cannot be constrained (TOTEMIS).

Exercise  2.2.11. Providing starting values

Before we go on, first a reminder that when you solve the models, you have to ALWAYS carefully check the solve summary: did you find an optimal solution or were there problems. Don’t jump directly to the results, since the results of an error-model are meaningless.

To help GAMS find the optimal solution, you can provide starting values. These starting values should, if your model is well-behaved, have no impact on the outcome itself, but does speed up the iteration process so that GAMS will find the optimal solution faster. For some models, GAMS cannot find the optimal solution at all if you don’t provide starting values. If you do not provide starting values, GAMS will implicitly take zero as starting value. The syntax for the starting values is straightforward: before the solve statement you provide a .L value to the parameters, for instance EMIS.L(T) = 10;.

Provide starting values for CO2 and EMIS of 1 and 6 for each period.

Check the solution listing for any changes.

Exercise  2.2.12. Providing lower and upper bounds

If you have information that the value of a variable cannot get lower (or higher) than some value, you can provide lower (or upper) bounds. This is done in a way similar to providing starting values, only now you don’t use the .L, but rather the .LO for lower bounds and .UP for upper bounds.

Lower bounds are very useful if you have an equation that is invalid if a variable becomes zero (for instance Z =E= X/Y; if Y is zero, then Z is undetermined). Then provide a small but positive lower bound on Y (like 0.0001).

Include an upper bound of 55 on production of sector 2 and a lower bound of 12 on production of sector 1 for each period. Make sure these bounds apply in the first solve.

Do these bounds influence the solve? Explain how and why.

Remove the bound that causes the model to run incorrectly, run the model again and analyse the results.

Note that these bounds will apply until you change them. So they also apply in the second simulation!

Exercise  2.2.13. Fixing variables

Fixing a variable is the same as providing a lower and an upper bound equal to each other. The shortcut way to do this is the use .FX instead of .LO and .UP and then provide the fixed value. You can ‘unfix’ (release) a variable by providing new bounds; if you want to release the variable completely, provide a lower bound of “-INF” and an upper bound of “+INF”.

Fix the value of PRD(“3”,”2000”) to 45 in the first simulation and release it completely before the second simulation.

Explain how this influences the results of the first solve.

Exercise  2.2.14. Using the LOOP statement

To repeat a number of commands over all elements in a set you can use the LOOP statement. Often, a loop is used to do multiple solves. In our case, the loop will then be over set SOL. The syntax is

LOOP(SOL,

*{add the commands you want for each element in set SOL,             }

*{these could be SOLVE statements, parameter calculations, et cetera }

);

The loop makes GAMS first use the first element of the set (in this case “1st solve”), go through all the statements given in the loop, and once it reaches the end of the loop, go back to the start of the loop and go through all the statement using the second element of the looped set.

We want to include a loop over all simulations and include the solve statement, the calculation of RES (now use SOL as the first index, and not “1ST SOLVE”) and the new bounds and values for the second solve, so we write directly after the MODEL statement:

LOOP(SOL,

        SOLVE CLIMATE USING DNLP MINIMIZING TOTEMIS;

        RES(SOL,T) = EMIS.L(T);

*Prepare for the second solve:

        PRD.LO('3','2000')= -INF;

        PRD.UP('3','2000')= +INF;

        OTHER(T) = 7;

);

DISPLAY RES;

Note that you cannot declare a parameter inside a loop, so you’ll have to move that command to above the start of the loop.

Use the LOOP statement to solve over both simulations, calculate parameter RES and change the bounds and values for the second solve.

You can also use the loop statement to calculate the values of a parameter, as we will see later.

Exercise  2.2.15. Using conditional statements ($-operations)

Before we deal with conditional statements, we will first add damages to the model to make it more realistic.

Add a new equation, QDAM(J,T) stating that the value of the new variable DAM(J,T) equals 0.05.

Change the equations QPRD such that production is greater than production data times (1-DAM(J,T)).

Explain the effects of this change on the results.

Conditional statements are GAMS’ way to say ‘only if’. If you write X=2+3$(Y>1), then X will be 2 for values of Y below 1 and X will be 5 for Y-values above 1; the statement is read as ‘X equals 2 plus 3 if Y is bigger than 1’. These dollar-operations can be used to conditionally assign values to parameters, but also to equations. For example, the relation between X and Y can also be written as:

QX1$(Y<=1).. X =E= 2;

QX2$(Y>1)..  X =E= 5;

Note: Y has to be a parameter and not a variable for GAMS technical reasons.

In our model, we will specify that damages are larger for higher production values.

Make a copy of the line with the equation for QDAM(J,T) and put it just below the original line. Comment out the original line (see Exercise 3.2.2). Add 0.05 to the damages in a sector in a period if the production data (PRD_DATA(J,T)) are above 50:

QDAM(J,T).. DAM(J,T) =E= 0.05 + 0.05$(PRD_DATA(J,T)>50);

Check whether the results of this revised model are the same as before.

Exercise  2.2.16. Using lags and leads in parameters and variables

When you specify a relationship between period T and T-1, this is called a “lag”. When you specify a relation between period T and T+1 this is a “lead”. A common example of a lead is the build-up of capital stock using investments: capital stock in period T+1 depends on capital stock in period T plus investments in period T: K(T+1)=K(T)+I(T);.

Lags and leads can be used for both parameters and variables, though there are some restrictions for use with variables.

Make the parameter COEF dependent on the sector by adding an index J:

CO2(T) =E= SUM(J,COEF(J,T)*PRD(J,T))

Provide 2000-data for COEF (0.01, 0.04 and 0.025 for sectors 1, 2 and 3 respectively) and then use a loop to calculate COEF(J,T+1) as COEF(J,T)*0.99.

Note that the new specification of the CO2-equation is not equivalent to
CO2(T) =E= SUM(J,COEF(J,T))*SUM(J,PRD(J,T))

Next, assume that the conditional statement in the equation for damages depends on the production quantities in the year before in stead of the current year.

Change the equation for damages such that the conditional statement depends on the production data in the year before. Analyse the effects on the damages.

QDAM(J,T)..         DAM(J,T) =E= 0.05+0.05$(PRD_DATA(J,T-1)>50);

Exercise  2.2.17. Raising to a power

Raising a variable to some power can be done by using two stars followed by the power number; if you want to square, the power number is 2.

In the equations for the production quantities, put a square on the damage factor (1‑dam(j,t)).

Notice that the model has now become non-linear. The model status has now changed from ‘optimal’ to ‘locally optimal’. This does not have to worry you, this status automatically changes when the model becomes non-linear.

Exercise  2.2.18. Using ORD and CARD

The autonomous decrease in the emission coefficient every year with 1% was written as

coef(“1”,”2000”) = 0.01;

coef(“2”,”2000”) = 0.04;

coef(“3”,”2000”) = 0.025;

LOOP(T, coef(j,t+1) = coef(j,t)*0.99).

The loop is used here because you want to calculate the time-dependent coefficients for every year. This cannot be done by just stating coef(j,t+1) = coef(j,t)*0.99.

The intuition is simple: when GAMS comes to this line, it only knows the values for the first year (2000). So it can only calculate the values for 2001. Using the loop, you then calculate 2002, 2003 etc. until all periods are calculated.

 

But, alternatively, you could write:

coef(“1”,T) = 0.01*(0.99**(ORD(T)-1));

coef(“2”,T) = 0.04*(0.99**(ORD(T)-1));

coef(“3”,T) = 0.025*(0.99**(ORD(T)-1));

The two specifications are mathematically equivalent. The ORD that is taken of index T gives the relative position of the active value in the set. So in our example, ORD(“2000”) equals 1, ORD(“2001”) equals 2, et cetera.

Note: in order to keep your code as simple and neat as possible, perhaps you can rewrite the statements above in vector notation.

Change the autonomous decrease in the emission coefficients by using the ORD specification. Check that the values of coef have not changed.

Optional:

Another convenient operator is CARD. The CARD value of a set is the total number of elements in the set. So, in our example, CARD(T)=5.

Both operators are often used together. For example, a straight interpolation from 0 to 1 over all elements in T can be modelled as (ORD(T)-1)/(CARD(T)-1).

Check that this is a straight line that starts at 0 and ends at 1 by adding a parameter INDEX(T) and displaying index.

Exercise  2.2.19. Using a free variable

Sometimes you want to add a variable to your model for which you do not have an equation, but want GAMS to find the optimal value. In this exercise, we will add such a ‘free variable’. Note that the term ‘free variable’ is not a GAMS code word; free variables are ordinary variables, only without an equation to determine their value.

Suppose it would make sense to weigh the CO2 emissions and the other emissions in the calculation of total emissions (in real life, this doesn’t make sense: you just add different greenhouse gas emissions, without weighing them first; we use this specification for illustration purposes only). What would then the optimal value of the weights be, given that they have to sum to unity? GAMS can answer this question for you if you introduce the weights as free variables.

Add a new variable, alpha, and provide a lower bound of 0.2 and an upper bound of 0.8 for alpha. Alpha can be described as the weight of CO2-emissions.

Change the equation for emissions into:

QEMIS(T)..  EMIS(T) =E= CO2(T)*alpha*2 + OTHER(T)*(1-alpha)*2;

In this case, if alpha is 0.5, both weights equal one and total emissions is just the sum of CO2 and OTHER emissions. If alpha exceeds 0.5, more weight is given to CO2, and if alpha is lower than 0.5 more weight is given to OTHER. Note that the lower and upper bound on alpha prevent extreme situations where only one of the two sources of emissions matters.

Run the model and check the results. Can you explain the optimal value of alpha?

We can now go back to Exercise  2.1.7 and change the parameter tax into a free variable. You can now easily calculate the optimal tax rate in this simple exercise.

Open the model from Exercise  2.1.7 and calculate the optimal tax rate within GAMS.

Exercise  2.2.20. Mapping set elements

If you want to aggregate a certain data set, you can use a utility in GAMS called “set mapping”. Suppose you have a 5-sector input-output (IO) table (“largedataset”) and want to aggregate this into a 3-sector IO-table (“smalldataset”). To achieve this in GAMS, you can identify a special set:

SET MAP(largedataset,smalldataset)
    /light_ind.industry, {more mapped sectors…}/;

In MAP you state which sectors in the large dataset correspond to which sectors in the small dataset. You use a period (.) to connect both elements, e.g. light_ind.industry means that the sector “light_ind” in the large dataset belongs to sector “industry” in the small dataset.

Once you have established all connections between both datasets, you can sum the elements in the large dataset, conditional on the mapping. For example, if you wish to find the new sectoral consumption levels, you can calculate:

smalldataset(i_small, "cons") = SUM(i_large$map(i_large, i_small),
                                largedataset(i_large, "cons"));

The full example of using mapping to aggregate a larger dataset into a smaller dataset can be downloaded. The model shows that you can use GAMS to build the new data table.

Download the model “MAPPING.GMS” from the GAMS-homepage of the Environmental Economics Group of Wageningen University.

Add the missing code to calculate the column totals and row totals of the small dataset, using the column and row totals of the large dataset and the mapping.

Hint: you can check whether the calculated totals are correct by looking at the auxiliary parameter CHECK. This checks whether subtotals add up to grand totals and rowtotals equal columntotals.

Exercise  2.2.21. Understanding what you have done

This exercise is to test whether you understand what you have been doing so far.

Add a 3rd simulation to the model, where the value of OTHER is 9. Make all the necessary changes so that the model solves all three simulations. Check whether GAMS has found an optimal solution. Repair any errors you get underway.

Hint:                 other(T) = other(T)+2

How about your economic understanding of the model?

For what economic questions could this model be used?

Do you think the relationship between damages and build-up emissions is realistic? Why / why not? How can the model be changed to become more realistic in this point?

If you feel confident that you grasp the exercises above, go to the next level. If not, try to play around with the model some more (especially with the exercises you did not fully understand).

 

Appendix I: Common error messages in GAMS

 

If your model does not solve properly, there are several things you can do. First step is to carefully read the error messages that GAMS provides. These should give some clues what the problem is and where it is located in your source file. The second step is to carefully review your code. And again. Unfortunately, error messages in GAMS can sometimes be a bit cryptic. Therefore this section gives some hints that may help you find out what the most common error messages in GAMS mean..

Error code 129

You model does not run. GAMS gives an error code 129 and stops completely. This error is caused by a very specific problem with Windows NT on the network and GAMS. Save your model, open a new project (go to file, project, new project) on the C-disk (for example: c:\mydocuments\models\gams.gpr) and open your gams file again.

Exit code 109

Error: too many process directories exist, remove or rename directory(’s) 225?

Gams gives exit code 109 and stops completely. Temporary files (stored in subdirectories 225a, 225b, et cetera) have not been deleted automatically and you have to do it manually. Go to the directory where your project file is stored and delete all directories that start with 225.

Error 002 Identifier expected

This error message means that you are using some gams code where GAMS expects you to use a name. There are two possible causes for this error message:

·         You can get these error messages when you use gams code for a name for a set, parameter, variable or equation. For example you want to name one of your variables system. System however is a specified GAMS code so you will get this error message. In GAMS-IDE it is easy to check if a word is a specified gams-code or not. Whenever a word turns blue, this means that the word is GAMS code, do not use this word as a name.

·         You can get this error message when you do not give a name when GAMS expects you to. For example if you type the word parameter, GAMS expects you to at least declare one parameter. If you do not declare a parameter you get this error message.

Error 036 '=' or '..' or ':=' or '$=' operator expected  
-or-
Error 037 '=l=' or '=e=' or '=g=' operator expected

Remember when giving a value to a parameter you use “=” For example:

Parameter   INCOME;

INCOME=100;

When writing an equation you have to specify whether the lefthandside is equal to (=E=), greater than (=G=) or less than (=L=) the righthandside.

Error 066/141 The symbol shown has not been defined or assigned. A wild shot: You may have spurious commas in the explanatory text of a declaration. Check symbol reference list.

This error message means you are using a parameter in an equation that has not been given a value. For example suppose you are using equation in which you say that the use of capital (variable) must be lower then the total stock of capital (parameter). If you do not give a value to the parameter stock capital then GAMS will not be able to calculate the value of the variable capital and will give an error message.

Check the listing file for information about which parameter does not have a value.

Error 071 The symbol shown has been declared as an equation, but no symbolic equation (..) was found. Hint - look for commas in the documentation text for the equations. Use quotes around the text or  eliminate the commas.

This error message means that you have declared an equation but that you have not used this equation. Delete the declared equation that you are not using.

Error 096 Blank needed between identifier and text       
 (-or- illegal character in identifier)      
 (-or- check for missing ';' on previous line)

This error code can mean three things.

1.       Most commonly it will mean that you forgot a semicolon (;). Check the line just above the error message to make sure that there is a semicolon there.

2.       It can also mean that you have no space between the name of a set, parameter, variable or equation and the explanatory text.

For example, the following example is correct:

VARIABLES

      Y     income;

However the following example give an error code:

VARIABLES

      Yincome;

3.       Finally this error message can mean that you have used some illegal characters in names for sets, parameters, variables and equations. Names can only contain letters or numbers. Each name should at least contain 1 letter. Do not use names longer then 10 characters (though later versions of GAMS can handle longer names than earlier versions). Tip: try to give names that refer to the meaning of the variable (or parameter); it makes the reading of the model code much easier.

Examples of legal names are: a, a15, revenue

Examples of illegal names are: 15, $casg, muchtoolong, milk&meat

Error 140 Unknown symbol

This error code means that you are using a set, parameter, variables or equation without declaring it first. You always have to define a name first before you can use it. Check if you have defined the name. If you did define the name, check if you have made any writing errors when using the name.

Error 148 Dimension different - The symbol is referenced with more/less indices as declared

You are using a parameter or a variable differently then you have declared it. If you have a variable with an index, you have to use the index always when using the variable. For example if you declare a certain variable Y as Y(t) which means that variable Y has the index t than every time you use Y you have the write Y(t).

So the following example is correct:

Variable    Y(t)  income;

Equation    QI(t) income equation;

QI(t)..     Y(t)=E=P*X;

 

The following example is not correct:

Variable    Y(t)  income;

Equation    QI    income equation;

QI..        Y=E=P*X;

Error 142 No suffix allowed here - suffix ignored

When you get this error message you are probably using a suffix after the name of a parameter. Suffix’s are: .L (level), .UP (upper bound) .LO (lower bound) .M (marginal value). If you want to display the value of a parameter just write the name:

DISPLAY Y;

instead of :

DISPLAY Y.L;

if Y is a parameter

Error 143 A suffix is missing

When referring to a variable outside an equation you always have to put a suffix after the variable name. Suffix’s are: .L (level), .UP (upper bound) .LO (lower bound) .M (marginal value). So if you want to display the value of a variable, remember to put a suffix after the variables name:

DISPLAY Y.L;

instead of :

DISPLAY Y;

if Y is a variable

Error 149 Uncontrolled set entered as constant

This error message means that the index of the equation name is not equal to the index of variables used in that equation.

Take for example the following equation:

QY..       Y(t)=E=P*X(t);

Income equals the value of consumption in all time periods t. However you have to specify to GAMS for which time period t this equation holds. If you want this equation to hold for all time period t, you have to add an index to the equation name:

QY(t)..    Y(t)=E=P*X(t);

Error 195 Symbol redefined with a different type

This error message means that you are using the same name for two different identifiers. Never use the same name twice. Not even equations can have the same names! Remember that GAMS does not see the difference between lower and upper case letters. For example “y” and “Y” are the same names for GAMS.

Error 409 Unrecognizable item - skip to find a new statement, looking for a ';' or a key word to get started again

This is a very general error message; there are several ways of getting this error message:

·         You have made a writing mistake in one of the gams codes. GAMS expects a gams code and does not see one and gives this error message.

·         You have used an index in the display statement. You can never use an index in the display statement.

Exec Error 0 Division by zero

If you get execution error 0 then GAMS tries to divide by zero. A solution to this problem is to give a small lower bound (e.g. 0.00001) for any variable that you use in the lower part of a division.

Sometimes you can get around this error by restructuring the equation (A*B=E=C instead of A=E=C/B).

Exec Error 10 Illegal arguments in ** operation

You can use the “to the power to” operation in GAMS but this can easily cause problems. Always use small lower bound (e.g. 0.00001) for variables you use in ** operations (if you are sure that they will have positive values anyway). GAMS sometimes has problems with performing a ** operation with negative numbers.

Rearranging you equations may also help. For example, if (A-B)**2 =E= D; does not work, write two equations: A-B =E= C; and C**2 =E= D;.

** Warning ** The variance of the derivatives in the initial point is large. A better initial point, a better scaling, or better bounds on the variables will probably help the optimization.

This is actually not an error message, but a warning. Basically, it says that your model is not well-behaved. Your model may still solve properly, but chances are high that the solver fails to find the optimal solution (and you do know how to check whether GAMS found the optimal solution, right!?).

The warning is quite informative and lists different options you have to improve the working of your model: provide better starting values, lower and upper bounds and scaling. You can find exercises on how to use these features in Section 2.2. of this reader.

In general, when you get warnings like this, it is a good point to start with evaluating your model fomulation. After carefully reviewing your code, re-ordering the code in a more logical way, and avoiding unnecessary complications in equations, you can move to the next step: carefully review your code again. You are bound to find things you missed the first time.

The warning may, however, also affect your choice of solver. For most model types, there are different solvers you can use to find the optimal solution. In many instances, especially for smaller models, all major solvers do a good (or even excellent) job in finding the optimum quickly.

One of the leading experts on this issue is Erwin Kalvelagen of GAMS Development Corporation. His advice on this issue is, as always, excellent:

“In general, CONOPT is one of the most reliable solvers for very large [non-linear, RD] models, but it is always possible another solver does better, so trying […] is certainly a good idea. Here are some more hints:

-          use a smaller instance to provide a starting point for a large instance.

-          use smart aggregation […] to reduce the size, solve that model and use this as a starting point for the disaggregated version.

-          use the point that the default solver gives you as a starting point for another solver.

-          even if other solvers cannot solve the model their behaviour and messages may give some insight in the origin of the problem.

-          look at the model formulation.

-          look again at the model formulation.”

 

 



[1] Note: in some cases there have been problems with using a network drive as the project directory (especially when using Windows 2000). In those cases, create a directory on the hard disk.

[2] Note that parts of the output file may look different if you use a different solver.