Table of Contents
- Introduction
- List of Dollar Control Options
- Dollar Control Options Affecting the Input Comment Format
- Dollar Control Options Affecting the Input Data Format
- Dollar Control Options Affecting the Output Format
- Dollar Control Options Affecting the Listing of Reference Maps
- Dollar Control Options Affecting Program Control
- Dollar Control Options for GDX Operations
- Dollar Control Options for Compile-Time Variables and Environment Variables
- Dollar Control Options for Macro Definitions
- Dollar Control Options for Compressing and Encrypting Source Files
- Detailed Description of Dollar Control Options
- Conditional Compilation
- Conditional Compilation: General Syntax and Overviews
- Conditional Compilation: Examples
- File Operation Test
- Conditional Compilation and Batch Include Files
- Testing Whether an Item Has Been Defined
- Testing the state of a flag set by a dollar control option
- Testing Whether an Item May Be Used in an Assignment
- Testing Whether an Identifier May Be Declared
- Comments in the Context of Conditional Compilation
- Error Level Test
- Solver Test
- Command Line Parameters in String Comparison Tests
- System Attributes in String Comparison Tests
- Conditional Compilation with $ifThen and $else
- Type of Identifiers
- Macros in GAMS
- Compressing and Decompressing Files
- Encrypting Files
Introduction
Dollar control options are used to indicate compiler directives and options. Dollar control options are not part of the GAMS language and must be entered on separate lines marked with the 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 separated by spaces. Since the dollar control options are not part of the GAMS language, they do not appear on the compilation output in the listing file unless an error has been detected or the user has requested them to be shown (with the option $onDollar).Note that dollar control option lines are not case sensitive and a continued compilation uses the previous settings.
This chapter is organized as follows. First an overview of the dollar control options will be given in section List of Dollar Control Options, where the options will be presented in groups reflecting their major functional categories. Section Detailed Description of Dollar Control Options will contain a reference list of all dollar control options in alphabetical order with detailed description for each.
We will conclude this chapter with separate sections for two important topics: Conditional Compilation, Macros in GAMS, Compressing and Decompressing Files, and Encrypting Files.
Syntax
In general, the syntax in GAMS for dollar control statements is as follows:
$option_name argument_list {option_name argument_list}
The symbol $
in the first column indicates that this is a dollar control statement. It is followed by the name of the dollar control option option_name
and the list of arguments argument_list
of the option. Depending on the particular option, the number of arguments required can vary from 0 to many. More than one dollar control option may be activated in one statement. Note that in this case the symbol $
is not repeated. Observe that some dollar control options require that they be the first option on a line.
- Note
- No blank space is permitted between the character
$
and the first option that follows. - The effect of the dollar control option is felt immediately after the option is processed.
- Dollar control options are not part of the GAMS language they instruct the compiler to perform some task. Therefore, dollar control options are not terminated with a semicolon as real GAMS language statements.
- No blank space is permitted between the character
A simple example of a list of dollar control options is shown below:
$title Example to illustrate dollar control options
$onsymxref onsymlist
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. These options turn on the echoing of the symbol cross reference table and symbol listing in the compilation output in the listing file.
Observe that it is also permitted to place a dollar control statement in a column other than column 1. However, in this case the statement must begin with the symbols $$
, like in this example
$$title Example showing that dollar control option can start in any column with an extra $ added
List of Dollar Control Options
The dollar control options are grouped into nine major functional categories affecting
- the input comment format
- the input data format
- the output format
- reference maps
- program control
- GDX operations
- compile-time variables and environment variables
- macro definitions
- compressing and encrypting source files
The following subsections briefly describe the options in each of the categories.
Dollar Control Options Affecting the Input Comment Format
Option | Description |
---|---|
comment | Set the comment character |
eolCom | Set the end-of-line comment character(s) |
inlineCom | Set the in-line comment characters |
maxCol | Set the right-hand margin of the input file |
minCol | Set left-hand margin of the input file |
offEolCom | Turn end-of-line comments off |
offInline | Turn in-line comments off |
offMargin | Turn margin marking off |
offNestCom | Turn nested comments off |
offText | Turn text mode off |
onEolCom | Turn end-of-line comments on |
onInline | Turn in-line comments on |
onMargin | Turn margin marking on |
onNestCom | Turn nested comments on |
onText | Turn text on: the following lines are comment |
Note that comments in GAMS are introduced in section Comments.
Dollar Control Options Affecting the Input Data Format
Option | Description |
---|---|
dollar | Set the 'dollar' character |
offDelim | Turn delimited data statement syntax off |
offDigit | Turn the number precision check off |
offEmbedded | No embedded text or data allowed |
offEmpty | Disallow empty data initialization statements |
offEnd | Disallow alternate program control syntax |
offEps | Disallow interpretation of EPS as zero |
offExternalInput | End of external input section |
offGlobal | Disallow inheritance of parent file settings |
offIDCProtect | Allow to change external input symbols at execution time |
offImplicitAssign | Trigger compilation error 141 if symbol has not been assigned |
offSuffixDLVars | Do not allow domain limited variables with suffixes in model |
offSuffixAlgebraVars | Do not allow variables with suffixes in model algebra |
offTroll | Do not recognize Troll periodicity in set definitions using sequences |
offUNDF | Do not allow UNDF as input |
offUni | Do not allow domain violations in assignments |
offWarning | Do not convert domain errors into warnings |
onDelim | Turn delimited data statement syntax on |
onDigit | Turn number precision check on |
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 zero as EPS |
onExternalInput | Start of external input section |
onGlobal | Force inheritance of parent file settings |
onIDCProtect | Protect external input symbols from being changed at execution time |
onImplicitAssign | Suppress compilation errors 141 and implicitly assign symbol if symbol has not been assigned |
onSuffixDLVars | Allow domain limited variables with suffixes in model |
onSuffixAlgebraVars | Allow variables with suffixes in model algebra |
onTroll | Recognize Troll periodicity in set definitions using sequences |
onUNDF | Allow UNDF as input |
onUni | Allow domain violations in assignments |
onWarning | Convert certain domain errors into warnings |
use205 | Language syntax of release 2.05 |
use225 | Language syntax of release 2.25 Version 1 |
use999 | Latest language syntax |
version | Test GAMS compiler version number |
Dollar Control Options Affecting the Output Format
Option | Description |
---|---|
double | Double-spaced listing follows |
echo | Echo text to a file |
echoN | Echo text 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 the page |
log | Send message to the log |
offDollar | Turn the listing of dollar control option lines off |
offEcho | End of block echo |
offExternalOutput | End of external output section |
offEpsToZero | Do not interpret EPS as zero when writing to GDX |
offInclude | Turn the listing of include file names off |
offListing | Turn echoing input lines to listing file off |
offLog | Turn line logging off |
offPut | End of block put |
offUpper | Following print to listing file is mixed cased |
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 |
onEpsToZero | Interpret EPS as zero when writing to GDX |
onExternalOutput | Start of external output section |
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 |
onUpper | Following print to listing file is all upper cased |
onVerbatim | Start verbatim copy if dumpopt \(\geq\) 10 |
remark | Comment line with suppressed line number |
[x]save[.keepCode] | Create a (compressed) save file during compilation with and without execution code compiled so far |
single | Single-spaced listing follows |
stars | Set "****" characters in listing file |
sTitle | Set subtitle and reset page |
title | Set title and reset page |
Dollar Control Options Affecting the Listing of Reference Maps
Option | Description |
---|---|
offSymList | Turn symbol list off |
offSymXRef | Turn symbol cross reference listing off |
offUElList | Turn unique element listing off |
offUElXRef | Turn unique element cross reference off |
onSymList | Turn symbol list on |
onSymXRef | Turn symbol cross reference listing on |
onUElList | Turn unique element listing on |
onUElXRef | Turn unique element cross reference on |
Dollar Control Options Affecting Program Control
Option | Description |
---|---|
abort[.noError] | Issue an (error) message and abort compilation |
batInclude | Include file with substitution arguments |
call | Execute another program during compilation |
call.Async[NC] | Execute another program asynchronously during compilation |
call.checkErrorLevel | Execute another program during compilation and raise error in case of problem |
callTool | Execute a GAMS tool during compilation |
callTool.checkErrorLevel | Execute a GAMS tool during compilation and raise error in case of problem |
clear | Reset all data for an identifier to its default value |
clearError[s] | Clear compilation errors |
else | Else clause |
elseIf | ElseIf structure with case sensitive comparison |
elseIfE | ElseIf structure with expression evaluation |
elseIfI | ElseIf structure with case insensitive comparison |
endif | Close 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 | Execute another program (hidden) during compilation |
hiddenCall.Async[NC] | Execute another program (hidden) asynchronously during compilation |
hiddenCall.checkErrorLevel | Execute another program (hidden) during compilation and raise error in case of problem |
hiddenCallTool | Execute a GAMS tool (hidden) during compilation |
hiddenCallTool.checkErrorLevel | Execute a GAMS tool (hidden) during compilation and raise error in case of problem |
if | Conditional processing, case sensitive |
ifE | If statement with expression evaluation |
ifI | Conditional processing, case insensitive |
ifThen | IfThen-elseIf structure with case sensitive comparison |
ifThenE | IfThen-elseIf structure with expression evaluation |
ifThenI | IfThen-elseIf structure with case insensitive comparison |
include | Include file |
kill | Kill data connected with identifier |
label | Label name as entry point from $goto . |
libInclude | Include file from library directory |
offCheckErrorLevel | Do not check errorLevel automatically after $[hidden]call |
offECImplicitLoad | Do not allow implicit loading from embedded code |
offEmbeddedCode | Ends embedded code section |
offFiltered | Turn behavior of $[gdx]load* to domain checked read |
offMulti | Turn redefinition of data off |
offOrder | Allow lag and lead operations on dynamic or unordered sets |
offRecurse | Disable recursive include files |
offStrictSingleton | Take first label if data statement for singleton set has multiple elements |
onCheckErrorLevel | Throw compilation error, if errorLevel is not 0 after $[hidden]call |
onECImplicitLoad | Allow implicit loading from embedded code |
onEmbeddedCode | Starts embedded code section with substitution |
onEmbeddedCodeS | Starts embedded code section with substitution |
onEmbeddedCodeV | Starts embedded code section without substitution |
onFiltered | Turn behavior of $[gdx]load* to filtered read |
onMulti | Turn redefinition of data on (merging into existing data) |
onMultiR | Turn redefinition of data on (replacing existing 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 | Define a phantom element |
shift | bat/lib/sysInclude argument shift operation |
stop | Stop compilation |
sysInclude | Include file from system directory |
terminate | Terminate compilation and execution |
warning | Issue compilation warning |
Note that conditional compilation in GAMS is discussed in section Conditional Compilation below.
Dollar Control Options for GDX Operations
Option | Description |
---|---|
declareAndLoad | Declare and load all symbols from specified GDX file |
gdxIn | Open GDX file for input |
gdxLoad | Load specified symbols from specified GDX file |
gdxLoadAll | Load all symbols which are known to GAMS from specified GDX file |
gdxOut | Open GDX file for output |
gdxUnload | Unload symbols into specified GDX file. |
load | Load symbols from previously opened GDX file |
loadDC | Load symbols from previously opened GDX file - domain checked |
loadDCM | Load symbols from previously opened GDX file - domain checked - merge |
loadDCR | Load symbols from previously opened GDX file - domain checked - replace |
loadFiltered | Load symbols from previously opened GDX file - domain filtered |
loadFilteredM | Load symbols from previously opened GDX file - domain filtered - merge |
loadFilteredR | Load symbols from previously opened GDX file - domain filtered - replace |
loadIdx | Load symbols from previously opened GDX file which has been written using an indexed write |
loadM | Load symbols from previously opened GDX file - merge |
loadR | Load symbols from previously opened GDX file - replace |
offExternalInput | End of external input section |
offExternalOutput | End of external output section |
offFiltered | Turn behavior of $[gdx]load* to domain checked read |
onExternalInput | Start of external input section |
onExternalOutput | Start of external output section |
onFiltered | Turn behavior of $[gdx]load* to filtered read |
unLoad | Unload symbols into previously opened GDX file. |
Note that GDX facilities and utilities are introduced in chapter GAMS Data eXchange (GDX).
Dollar Control Options for Compile-Time Variables and Environment Variables
Option | Description |
---|---|
drop | Drop a scoped compile-time variable |
dropGlobal | Drop a global compile-time variable |
dropLocal | Drop a local compile-time variable |
dropEnv | Drop an OS environment variable |
escape | Define the % escape symbol |
eval | Evaluate and define a scoped compile-time variable |
eval.Set | Evaluate and define a scoped compile-time variable based on a GAMS set |
evalGlobal | Evaluate and define a global compile-time variable |
evalGlobal.Set | Evaluate and define a global compile-time variable based on a GAMS set |
evalLocal | Evaluate and define a local compile-time variable |
evalLocal.Set | Evaluate and define a local compile-time variable based on a GAMS set |
prefixPath | Prefix the environment variable PATH . |
scratchFileName | Set a name for a temporary file in the scratch directory using the scratch file extension |
setArgs | Define local compile-time variables using argument list |
setComps | Unpack dotted names into compile-time variables |
setDDList | Check double dash GAMS parameters |
setDDList.Cont | Start list of identifiers to check double dash GAMS parameters |
setEnv | Define an OS environment variable |
set | Define a scoped compile-time variable |
setGlobal | Define a global compile-time variable |
setLocal | Define a local compile-time variable |
setNames | Unpack a filename into local compile-time variables |
show | Show current GAMS compile-time variables, macros, and active files |
showFiles | Show active input and include files |
showMacros | Show current macros |
showVariables | Show current GAMS compile-time variables |
splitOption | Unpack a key/value pair into scoped environment variables |
See also sections Compile-Time Variables and Environment Variables in GAMS.
Dollar Control Options for Macro Definitions
Option | Description |
---|---|
macro | Preprocess macro definition |
offDotL | Do not assume .l for variables in assignments |
offDotScale | Assume .scale for variables and equations 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 and put statements |
onDotScale | Assume .scale for variables and equations in assignments and put statements |
onExpand | Expand macros when processing macro arguments |
onLocal | No limit on .local nesting |
onMacro | Recognize macros for expansion |
Note that macros are introduced in section Macros in GAMS below.
Dollar Control Options for Compressing and Encrypting Source Files
Option | Description |
---|---|
compress | Create compressed GAMS system file |
decompress | Decompress a GAMS system file |
encrypt | Create an encrypted GAMS system file |
expose | Remove all access control restrictions |
hide | Hide objects from the user |
protect | Protect objects from being modifified by the user |
purge | Remove the objects and all associated data |
Detailed Description of Dollar Control Options
In this section we will describe each dollar control option in detail. Note that the dollar control options are listed in alphabetical order for easy reference. Note further, that in each entry the default value, if applicable, is given in parentheses.
Syntax:
$abort[.noError] [text]
If used as
$abort
, this option will issue a compilation error and abort the compilation. It may be followed by a text.Example:
$if not %system.fileSys% == UNIX $abort We only do UNIX
This stops compilation if the operating system is not Unix. Running the example above on Windows will result in the compilation being aborted and the following lines in the listing file:
2 $abort We only do UNIX **** $343 Error Messages 343 Abort triggered by above statementThis option has a variant:
$abort.noError
. If the extension.noError
is used the compilation will be aborted as well, but there will be no error. If a save file is written, all remaining unexecuted code will be flushed. This allows effective reuse of the save file.Note that there is also an abort statement in GAMS, it is used to terminate the execution of a program.
See also $exit, $error, $stop, and $terminate.
Syntax:
$batInclude external_file {arg}
The
$batInclude
facility performs the same task as the $include facility: it inserts the contents of the specified fileexternal_file
at the location of the call. However, in addition, the option$batInclude
also passes on argumentsarg
which may be used inside the include file.External_file
is the name of the batch include file, it may be quoted or unquoted. The argumentsarg
are passed on to the batch include file. These arguments are treated as character strings that are substituted by numbers inside the included file. The arguments may be single unbroken strings (quoted or unquoted) or quoted multi-part strings.Note that 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 an 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). Observe that parameters are substituted independent of context and the entire line is processed before it is passed to the compiler. There is one exception: parameter flags that appear 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.
- The case of the passed parameters is preserved, thus it may be used in string comparisons.
Example:
$batInclude "file1.inc" abcd "bbbb" "cccc dddd"
Note that
file1.inc
is included withabcd
as the first parameter,bbbb
as the second parameter andcccc
dddd
as the third parameter.Parameter a,b,c ; a = 1 ; b = 0 ; c = 2 ; $batInclude inc2.inc b a display b ; $batInclude inc2.inc b c display b ; $batInclude inc2.inc b "a+5" display b ;
The external file
inc2.inc
contains the following line:%1 = sqr(%2) - %2 ;
The echo print in the corresponding listing file follows:
1 Parameter a,b,c ; 2 a = 1 ; b = 0 ; c = 2 ; BATINCLUDE C:\tmp\inc2.inc 4 b = sqr(a) - a ; 5 display b ; BATINCLUDE C:\tmp\inc2.inc 7 b = sqr(c) - c ; 8 display b ; BATINCLUDE C:\tmp\inc2.inc 10 b = sqr(a+5) - a+5 ; 11 display b ;Note that the option
$batInclude
appears three times with different arguments. GAMS is interprets the contents of the batch include file in turn as:b = sqr(a) - a ; b = sqr(c) - c ; b = sqr(a+5) - a+5 ;
Note that the third call is not interpreted as
sqr(a+5)-(a+5)
, but instead assqr(a+5)-a+5
. The results of the display statement are shown at the end of the listing file are given below:---- 5 PARAMETER b = 0.000 ---- 8 PARAMETER b = 2.000 ---- 11 PARAMETER b = 40.000Observe that the third call leads to
b = sqr(6)-1+5
, thus the final value ofb
is 40. Suppose the statement in the batch include file is modified to read as follows:%1 = sqr(%2) - (%2) ;
With this modification the output generated by the display statement will be as follows:
---- 5 PARAMETER b = 0.000 ---- 8 PARAMETER b = 2.000 ---- 11 PARAMETER b = 30.000Note that the third call leads to
b = sqr(6)-6
which results inb
taking a value of 30.
- Note
- The option
$batInclude
without any arguments is equivalent to the option $include.See also $include, $libInclude, $sysInclude.
Syntax:
$call [=]command
This option passes a
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.Example:
$call dir
This command creates a directory listing on a PC.
Note that the command string may be passed to the system and executed directly without using a command processor by prefixing the command with an '
=
' sign. Compilation errors will be issued if the command or the command processor cannot be loaded and executed properly.$call gams trnsport $call =gams trnsport
The first call will run the model [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, will send the command directly to the system. The return codes from the system will be intercepted correctly and they will be available to the GAMS system through the errorLevel function.
- Attention
- Some commands (like
copy
on a PC andcd
in Unix) are shell commands and cannot be spawned off to the system. Using these in a system call will create a compilation error.The first call will work on a PC, but the second will not. The copy command may be used only from a command line shell. The system is not aware of this command (Try this command after clicking Run under the Start menu in Windows. You will find that it does not work).$call 'copy myfile.txt mycopy.txt' $call '=copy myfile.txt mycopy.txt'
- One has to take special care when the first argument of the
command
contains spaces (for example an executable with absolute path), e.g.:This would fail, since the command processor would try to call$call C:\path with spaces\gams.exe trnsport.gms
C:\path
as the executable. So, one might think that protecting the spaces using quotes will resolve this problem:However, the quotes delimit the entire$call "C:\path with spaces\gams.exe" trnsport.gms
$call
command
, so thattrnsport.gms
gets interpreted as new dollar control option instead of an argument for the executable. The solution is to use nested quotes: One pair to delimit the$call
command
and another one to protect the spaces of the executable like this:It gets even more complicated if the argument contains spaces as well, e.g. if we have$call '"C:\path with spaces\gams.exe" trnsport.gms'
my model.gms
instead oftrnsport.gms
. Another pair of quotes solves this:$call '"C:\path with spaces\gams.exe" "my model.gms"'
See also $call.Async, $call.checkErrorLevel, $hiddenCall.
Syntax:
$call.Async[NC] command
$call.Async
works like $call but allows asynchronous job handling. This means users may start a jobcommand
without having to wait for the result, they may continue in their model and collect the return code of the job later. The function jobHandle may be used to get the process ID (pid) of the last job started. The status of the job may be checked using the function jobStatus(pid). An interrupt signal to a running job may be sent with the function jobTerminate(pid). With the function jobKill(pid) a kill signal may be sent to a running job.The difference between
$call.Async
and$call.AsyncNC
is, that the latter starts processes in a new console, rather than sharing the console of the parent process.
- Note
- On non-Windows platforms
$call.AsyncNC
and$call.Async
are synonyms.
Syntax:
$call.checkErrorLevel [=]command
$call.checkErrorLevel
works like $call but checks the errorLevel implicitly, raises a compilation error and aborts compilation, if that is not 0.Example:
$call.checkErrorLevel gams trnsport
This is doing the same as:
$call gams trnsport $ifE errorLevel<>0 $abort 'Problem calling gams trnsport'
Syntax:
$callTool command
This option calls a tool of the GAMS Tools Library at compile time.
Example:
$callTool [data.]ExcelDump excelFile [gdxOut=fileOut.gdx]
This tool writes all worksheets of an Excel workbook to GAMS symbols.
- Note
- Similar to $call,
$callTool
returns a shell code that can be checked viaerrorLevel
. In case one expects the tools to perform without error, it is recommended to add the suffix .checkErrorLevel. This will stop the entire execution of GAMS if an error occurs while executing the tool.$callTool[.checkErrorLevel] [...]
is ignored while $onExternalInput is active and IDCGDXInput is set.
- Attention
- $callTool is only available for calling tools from the GAMS Tools Library. For general commands to the operating system $call must be used.
See also $callTool.checkErrorLevel, $hiddenCallTool.
Syntax:
$callTool.checkErrorLevel command
$callTool.checkErrorLevel
works like $callTool but checks the errorLevel implicitly, raises a compilation error and aborts compilation, if that is not 0.Example:
$callTool.checkErrorLevel [data.]ExcelDump excelFile [gdxOut=fileOut.gdx]
This is doing the same as:
$callTool [data.]ExcelDump excelFile [gdxOut=fileOut.gdx] $ifE errorLevel<>0 $abort 'Problem calling gams trnsport'
Syntax:
$clear ident {ident}
This option resets all data for the identifiers
ident
to their default values. Note that only the following data types may be reset: sets, parameters, variables and equations. Note further, that the clearing is carried out during compile time and not when the GAMS program executes.Example:
Set i / 1*20 /; Scalar a / 2 /; $clear i a display i, a;
The option
$clear
resetsi
anda
to their default values: an empty set fori
and zero fora
. The output generated by the display statement follows:---- 4 SET i ( EMPTY ) ---- 4 PARAMETER a = 0.000
- Attention
- The two-pass processing of a GAMS file may 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.Scalar a / 12 /; a = 5; $clear a display a;
Note that 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 ;
Therefore the result is that
a
takes the value of 5. The output from the display statement is as follows:---- 4 PARAMETER a = 5.000Compare also $kill and the execution time option clear.
Syntax:
$clearError[s]
This option (
$clearError
and$clearErrors
are synonyms) clears GAMS awareness of compiler errors and turn them into warning messages instead.Example:
Scalar z / 11 /; $eval x sqrt(-1) $clearError $log %x% Display z;
Note that without the use of
$clearError
the program above would not continue with the execution after line 2.
Syntax:
$comment char
This option changes the symbol indicating a single line comment from the default
*
to the single characterchar
. Note that after this option is used, the new comment characterchar
cannot be used in column 1 as before, since it got a special meaning. Note further, that the case of the character does not matter if it is used as a comment character. This option should be used with great care and we recommend to reset the symbol quickly to the default.
- Attention
- The case of the start-of-line comment character does not matter when being used.
Example:
$comment c c now we use a FORTRAN style comment symbol $comment * * now we are back to the default
See also section Comments.
Syntax:
$compress source target
This option causes the file
source
to be compressed into the packed filetarget
.Example: Consider the following example where the well-known model [TRNSPORT] is used:
$call gamslib trnsport $compress trnsport.gms t2.gms $include t2.gms
The first command retrieves the file
trnsport.gms
and the second command compresses it. Note that a compressed GAMS file is treated like any other GAMS file, therefore it may be included and executed as usual. Large data files that do not change often can be compressed this way to save disk space.The following example serves as a little utility to compress and decompress files:
$ifthen set decompress $ if not set input $set input file_c.gms $ if not exist %input% $abort No file input file %input% exist $ if not set output $set output file.gms $ log Decompressing %input% into %output% $ decompress %input% %output% $else $ if not set input $set input file.gms $ if not exist %input% $abort No file input file %input% exist $ if not set output $set output file_c.gms $ log Compressing %input% into %output% $ compress %input% %output% $endif
The program (saved to a file called
compress.gms
) can be used as follows:> gams compress.gms --input myfile.gms --output myfile_c.gms > gams compress.gms --decompress=1 --input myfile_c.gms --output myfile.gmsSee also $decompress. Further details are given in chapter Compressing and Decompressing Files.
Syntax:
$declareAndLoad GDXFileName
This option loads all symbols from a specified GDX file. It is similar to $gdxLoadAll, but does not only load the symbols declared so far but also declares symbols found in the GDX file on the fly if they were unknown. If a symbol already exists in GAMS the GDX declaration better matches it's previous GAMS declaration exactly (same rules as if we would write the second declaration in source, e.g. different symbol text is allowed or incremental declaration first
Variable x;
and in GDXPositive Variable x;
) otherwise we trigger an error.Example:
If there is a GDX file
trnsport
created from the [TRNSPORT] model, the following code will declare and load all symbols seen in the trnsport model before:$declareAndLoad trnsport.gdx option DmpUserSym;
This can be seen in the
.lst
file afterwards:SYMBOL TABLE DUMP (USER SYMBOLS ONLY), NR ENTRIES = 12 ENTRY ID TYPE DIM LENGTH MEMORYEST DEFINED ASSIGNED DATAKNOWN 138 i SET 1 2 0 MB TRUE FALSE TRUE 139 j SET 1 3 0 MB TRUE FALSE TRUE 140 a PARAM 1 2 0 MB TRUE FALSE TRUE 141 b PARAM 1 3 0 MB TRUE FALSE TRUE 142 d PARAM 2 6 0 MB TRUE FALSE TRUE 143 f PARAM 0 1 0 MB TRUE FALSE TRUE 144 c PARAM 2 6 0 MB TRUE FALSE TRUE 145 x VAR 2 6 0 MB TRUE FALSE TRUE 146 z VAR 0 1 0 MB TRUE FALSE TRUE 147 cost EQU 0 1 0 MB TRUE FALSE TRUE 148 supply EQU 1 2 0 MB TRUE FALSE TRUE 149 demand EQU 1 3 0 MB TRUE FALSE TRUE END OF SYMBOL TABLE DUMPSee also $(on|off)Filtered, $(on|off)Multi, and $onMultiR.
Syntax:
$decompress source target
This option causes the compressed file
source
to be decompressed into the unpacked filetarget
.Example: Consider the following example where the well-known model [TRNSPORT] is used:
$call gamslib trnsport $compress trnsport.gms t2.gms $decompress t2.gms t3.gms $call diff t3.gms trnsport.gms $if errorlevel 1 $abort t3.gms and trnsport.gms are not identical!
The first command retrieves the file
trnsport.gms
, the second command compresses it and the third command decompresses the compressed file. Note that the resulting file,t3.gms
, is identical to the original filetrnsport.gms
which is tested via thediff
program.See also $compress. Further details are given in chapter Compressing and Decompressing Files.
Syntax:
$dollar char
This option changes the current 'dollar' symbol to the single character
char
.
- Note
- The special
%$
substitution symbol can be used to get the current 'dollar' symbol.Example:
$dollar # #log now we can use '%$' as the '$' symbol
Syntax:
$double
The lines following this option will be echoed double spaced to the echo print in the listing file.
Example:
Set i / 1*2 / ; Scalar a / 1 / ; $double Set j / 10*15 / ; Scalar b / 2 / ;
The resulting echo print in the 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 option
$double
are listed single spaced, while the lines after the option are listed with double space.See also $single.
Syntax:
$drop VARNAME
This option destroys (removes from the program) the scoped compile-time variable
VARNAME
that was defined with the dollar control option $set.Example:
$set NAME my name $if set NAME $log Scoped compile-time variable NAME is set to "%NAME%" $drop NAME $if not set NAME $log Scoped compile-time variable NAME is not available anymore
See also $set, $dropGlobal, and $dropLocal.
Syntax:
$dropEnv VARNAME
This dollar control option destroys (removes from the program) the operating system environment variable
VARNAME
. For detailed information, see the dollar control option .Example:
$if setEnv GDXCOMPRESS $dropEnv GDXCOMPRESS
See also $setEnv, and $if setEnv.
Syntax:
$dropGlobal VARNAME
This option destroys (removes from the program) the global compile-time variable
VARNAME
that was defined with the dollar control option $setGlobal.Example:
$setGlobal NAME my name $if setGlobal NAME $log Global compile-time variable NAME is set to "%NAME%" $dropGlobal NAME $if not setGlobal NAME $log Global compile-time variable NAME is not available anymore
See also $setGlobal, and $drop.
Syntax:
$dropLocal VARNAME
This option destroys (removes from the program) the local compile-time variable
VARNAME
that was defined with the dollar control option $setLocal.$setLocal NAME my name $if setLocal NAME $log Local compile-time variable NAME is set to "%NAME%" $dropLocal NAME $if not setLocal NAME $log Local compile-time variable NAME is not available anymore
Syntax:
$echo text >[>] external_file
This option allows to write the text
text
to a fileexternal_file
. The text and the file name may both be quoted or unquoted. The file name is expanded using the working directory. The option$echo
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 an option $call or any variant of the option $include is encountered. The redirection symbols>
and>>
have the usual meaning of starting at the beginning or appending to an existing file respectively.Example:
$echo > echo.txt $echo The message written goes from the first non blank >> echo.txt $echo 'to the first > or >> symbol unless the text is' >> echo.txt $echo "is quoted. The input File is %gams.input%. The" >> echo.txt $echo 'file name "echo.txt" will be completed with' >> echo.txt $echo %gams.workdir%. >> echo.txt $echo >> echo.txt
The content of the resulting file
echo.txt
is the following:The message written goes from the first non blank to the first > or >> symbol unless the text is is quoted. The input File is C:\tmp\echoTest.gms. The file name "echo.txt" will be completed with C:\tmp\.See also $on/offEcho, and $echoN.
Syntax:
$echoN text >[>] external_file
This option sends a text message
text
to an fileexternal_file
like $echo but writes no end of line marker so the line is repeatedly appended to by subsequent commands. The redirection symbols>
and>>
have the usual meaning of starting at the beginning or appending to an existing file respectively. Note that the text and the file name may be quoted or unquoted. By default the file will be saved in the working directory.Example:
$echoN 'Text to be sent' > 'aaa.txt' $echoN 'More text' >> aaa.txt $echoN And more and more and more >> aaa.txt $echo This was entered with $echo >> 'aaa.txt' $echo This too >> aaa.txt
The created file
aaa.txt
contains the following text:Text to be sentMore textAnd more and more and moreThis was entered with $echo This tooSee also $on/offEcho, and $echo.
Syntax:
$eject
This option advances the echo print to the next page.
Example:
$eject Set i,j ; Parameter Data(i,j) ; $eject Scalar a; a = 7;
The statements following the first
$eject
will be listed on one page in the echo print of the listing file and the statements following the second$eject
will be listed on the next page.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option always appears together with the option $ifThen[E/I]. It is followed by an instruction which is executed if the conditional expression of the matching option $ifThen[E/I] is not true. For an example, see section Conditional Compilation with $ifThen and $else.
See also $ifThen, $elseIf and section Conditional Compilation.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option always appears together with the option $ifThen[E/I]. It is followed by another condition and instruction. For an example, see section Conditional Compilation with $ifThen and $else.
See also $ifThen, $else, $elseIfE, $elseIfI and section Conditional Compilation.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option does the same as $elseIf but evaluates numerical values of the control variables.
See also $elseIf and section Conditional Compilation.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option does the same as $elseIf but it is case insensitive.
See also $elseIf and section Conditional Compilation.
Syntax:
$encrypt source target
This option causes a file to be converted into an encrypted file. Here
source
is the name of the source file to be encrypted andtarget
is the name for the resulting encrypted file. Note that encryption requires the secure option to be licensed and is available for commercial licenses only. The command line parameter pLicense specifies the target license to be used for encryption. The encrypted file can only run on a system licensed with the license file used for encryption. No special action is required on the executing system since GAMS recognizes whether a file is encrypted and will process it accordingly. There is no option to decrypt an encrypted file, so better keep the original unencrypted file.Further details and examples are given in chapter Encrypting Files.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This must option must be matched with one of the options $ifThen, $ifThenE or $ifThenI. For an example, see section Conditional Compilation with $ifThen and $else.
See also $ifThen and section Conditional Compilation.
Syntax:
$eolCom char[char]
This option redefines and activates the end-of-line comment symbol, which may be one character or a sequence of two characters. By default, this is initialized to
!!
, but is not active. The option $onEolCom is used to activate the end-of-line comments. If$eolCom
is used, $onEolCom is set automatically.Example:
$eolCom // Set i /1*2/ ; // set declaration Parameter a(i) ; // parameter declaration
Here the character sequence
//
serves as the end-of-line-comment indicator.
- Attention
- It is not allowed to reset the end-of-line comment symbol to the current end-of-line comment symbol. This would cause an compilation error as in the following example:
$eolCom // $eolCom //
Some end of line character settings can cause confusion. The widely used end of line character sequence
//
is also legal GAMS syntax input
statement to indicate two line breaks:file fx; put fx; put 'first line' // 'second line' //; $eolCom // put 'third line' // 'fourth line';
results in a put file with the following content:
first line second line third lineThis can also confuse syntax highlighting in editors (or on thsi web page). Other popular end of line characters like
#
and@
are also used as GAMS syntax, see Controlling the Cursor On a Page.The default for dealing with end-of-line comments can be set using the command line parameter eolCom.
See also section Comments for more about comments in GAMS.
Syntax:
$error [text]
This option will issue a compilation error and will continue with the next line.
Example:
$if not exist myfile $error File myfile not found - will continue anyway
Note that the first line checks if the file
myfile
exists. If the file does not exist, it will generate an error with the commentFile myfile not found - will continue anyway
and then the compilation will continue with the next line.See also $abort, $exit, $terminate, and $stop.
Syntax:
$escape character
This option allows users to work with text sequences containing
%
without substitution.This causes all subsequent commands of the form
%symbol%
to not have parameter substitution done for them. As a consequence, no parameter substitutions are performed in GAMS statements (mostly useful in display and put statements) and the outcome of such statements where%symbol%
is used is just%symbol%
.Note that the effect of the option
$escape
may be reversed with the option$escape %
.Example:
$set tt DOIT file it; put it; display "first %tt%"; display "second %&tt%&"; put "display one ", "%system.date%" /; put "display two " "%&system.date%&"/; $escape & display "third %tt%"; display "fourth %&tt%&"; put "display third ", "%system.date%" /; put "display fourth " "%&system.date%&"/; $escape % display "fifth %tt%"; display "sixth %&tt%&"; put "display fifth ", "%system.date%" /; put "display sixth " "%&system.date%&"/;
The output generated by the display statements follows:
---- 6 first DOIT ---- 7 second %&tt%& ---- 12 third DOIT ---- 13 fourth %tt% ---- 18 fifth DOIT ---- 19 sixth %&tt%&The file
it.put
will contain the following lines:display one 08/10/17 display two %&system.date%& display third 08/10/17 display fourth %system.date% display fifth 08/10/17 display sixth %&system.date%&Note that this option was introduced to facilitate writing GAMS code (or command.com/cmd.exe batch scripts) from GAMS including unsubstituted compile-time variables. Text can also be written at compile-time without parameter substitution via option $on/offEchoV and at run-time via $on/offPutV.
- Note
- In GAMS the escape character follows the character (
%
) that needs to be escaped. In many other languages the escape character precedes the to be escaped character.
Syntax:
$eval VARNAME expression
This option evaluates a numerical expression at compile time and places it into a scoped compile-time variable. In turn the option $ifE may be used to do numeric testing on the value of this variable.
VARNAME
is the name of a compile-time variable andexpression
is an expression that consists of constants, functions, operators and other compile-time variables with numerical values. Note that no whitespace is allowed in the expression which can be overcome by additional parentheses.Example:
$eval b1 ifthen(uniform(0,1)<0.5,0,1) $eval b2 ifthen(uniform(0,1)<0.5,0,1) $eval b3 (%b1%)xor(%b2%) $log b1=%b1% b2=%b2% b1 xor b2=%b3%
The first two lines use the
uniform
function to generate a random number between 0 and 1 and assign0
if this number is less than 0.5 otherwise1
via theifthen
function to the scoped compile-time variableb1
andb1
. In the third line we apply the logicalxor
operator tob1
andb2
and store the result inb3
. The parentheses are required because the more natural expression%b1% xor %b2%
contains spaces. In the forth line we print the values and result to the log.b1=1 b2=1 b1 xor b2=0The expression are evaluated using IEEE nonstop arithmetic, so no evaluation errors are triggered as demonstrated in the following example:
$eval OneDividedByZero 1/0 $log 1/0=%OneDividedByZero%
This produces the following log:
1/0=+INFThe
$eval
and related dollar control options give access to a reduced set of GAMS functions: abs, card, ceil, cos, errorlevel, exp, fact, floor, frac, gamsrelease, gamsversion, gday, gdow, ghour, gleap, gmillisec, gminute, gmonth, gsecond, gyear, ifthen, jdate, jnow, jobhandle, jobkill, jobstatus, jobterminate, jstart, jtime, log, log10, log2, max, min, mod, numcores, pi, power, round, sameas, sign, sin, sleep, sqr, sqrt, tan, trunc, and uniform. The available operators are: +, -, *, /, ** and even ^ (integer power) which is not available in regular GAMS expression and requires the use of the functionipower
. The comparison relations are <, >, <=, >=, <>, and =. The logical operators are not, and, or, xor, imp, and eqv.The expression also allows the use of dollar on the right. In the following example we replace the
ifthen
function by a dollar one the right:$eval b1 1$(uniform(0,1)>=0.5) $eval b2 1$(uniform(0,1)>=0.5) $eval b3 (%b1%)xor(%b2%) $log b1=%b1% b2=%b2% b1 xor b2=%b3%
Moreover, the
$eval
has access to data available at compile time. The expression can access the value of scalars and for other symbols we can use thecard
function to access the cardinality (at this point) of the symbol. Here is an example:Scalar ac 'Avogadro constant' / 6.0221409e+23 /; $eval log_ac round(log10(ac)) $log round(log10(ac))=%log_ac% Set d / d0*d%log_ac% /; $eval card_d card(d) $log card(d)=%card_d%
Access to individual records of symbols is not possible. The embedded code facility allows access to symbol records at compile time.
The user has the possibility to hide some of the GAMS functions by symbols with the same name. In this case, the GAMS function can still be accessed, but needs to be prefixed with
system.
as in the following example:Scalar pi /3/; $eval myPi pi $eval GAMSPi system.pi $log myPi = %myPi% $log GAMSPi = %GAMSPi%
This is the resulting output in the log:
myPi = 3 GAMSPi = 3.14159265358979See also $eval.Set, $evalGLobal, $evalLocal, $ifE, and $set.
Syntax:
$eval.Set VARNAME SETID[.[First|Last]TE|[First|Last]TL|[First|Last]TN|TS]
This option evaluates an attribute of a GAMS set at compile time and places it into a scoped compile-time variable.
VARNAME
is the name of a compile-time variable andSETID
is the identifier of a GAMS set. The following attributes are allowed in this context:
Attribute Description [First OR Last]TE
Explanatory text of the first or last element of the set SETID
[First OR Last]TL
Label of the first or last element of the set SETID
[First OR Last]TN
Set identifier with with element labels of the first or last element of the set SETID
TS
Explanatory text of the set SETID
. This is also the default, if no attribute is specified
- Note
First??
and??
are synonyms in the table above. It always accesses the first element of the referenced set.Last??
always accesses the last element of the referenced set.- For Singleton Sets
First??
,Last??
and??
are synonyms.Example:
Singleton Set h Greeting / Hello 'Welcome' /; Set p Person / Mr.President 'Male' Mrs.Chancellor 'Female' /; $eval.Set X h.TE $log %X% $eval.Set X p.lastTL $log %X% $eval.Set X p.FirstTN $log %X%
This will generate the following in the log:
Welcome Mrs.Chancellor p('Mr','President')See also $eval, $evalGLobal.Set, $evalLocal.Set, and $set.
Syntax:
$evalGlobal VARNAME expression
This option evaluates a numerical expression at compile time and places it into a global compile-time variable. The syntax and behavior otherwise is identical to $eval.
Syntax:
$evalGlobal.Set VARNAME SETID[.[First|Last]TE|[First|Last]TL|[First|Last]TN|TS]
This option evaluates an attribute of a GAMS set at compile time and places it into a global compile-time variable. The syntax and behavior otherwise is identical to $eval.Set.
Syntax:
$evalLocal VARNAME expression
This option evaluates a numerical expression at compile time and places it into a local compile-time variable. The syntax and behavior otherwise is identical to $eval.
Syntax:
$evalLocal.Set VARNAME SETID[.[First|Last]TE|[First|Last]TL|[First|Last]TN|TS]
This option evaluates an attribute of a GAMS set at compile time and places it into a local compile-time variable. The syntax and behavior otherwise is identical to $eval.Set.
Syntax:
$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.
Example:
Scalar a ; a = 5 ; display a ; $exit a = a+5 ; display a ;
Note that the lines following the option
$exit
will not be compiled.Observe that there is a difference to the dollar control option $stop. If there is only one input file,
$stop
and$exit
will have the same effect. If the option$exit
occurs within an include file, it acts like an end-of-file on the include file. However, if the option$stop
occurs within an include file, GAMS will stop reading all input.See also $abort, $error, $terminate, and $stop.
Syntax:
$expose all | ident1 ident2 ...
This option removes all privacy restrictions from identifiers.
With explicit identifiers the privacy restrictions are removed only for the listed identifiers and with
all
the restrictions are removed for all identifiers. The privacy restrictions may be set with the dollar control options $hide or $protect. Note that a special license file is needed for this feature to work and that theexpose
only takes effect in subsequent restart files. For further information, see chapter Secure Work Files.
Syntax:
$FuncLibIn InternalLibName ExternalLibName
This makes extrinsic function libraries available to a model.
InternalLibName
is the internal name of the library in the GAMS code andExternalLibName
is the name of the shared library in the file system. See Using Function Libraries for more information.
Syntax:
$gdxIn [GDXFileName]
This option is used in a sequence to load specified items from a GDX file. Here
GDXFileName
denotes the name of the GDX file (with or without the extension.gdx
) and the command opens the specified GDX file for reading. The use of$gdxIn
without a file name closes the currently open GDX file. The command is used in conjunction with the option $load or one of its variants.Example:
set i,j; parameters a(i), b(j), d(i,j), f; $gdxIn mydata.gdx $load i j a b d f $gdxIn
Syntax:
$gdxLoad GDXFileName [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option loads specified symbols from a specified GDX file. It basically combines $gdxIn and $load in one call. This can be particularly useful for $[bat|lib]include files when you want to be sure, to not interfere with potentially previously opened GDX files. For example, a $load after a "$gdxLoad" will still load the symbols from the GDX file opened before:
$gdxIn A.gdx $load a b c $gdxLoad B.gdx d * The following $load gets the symbols e, f, and g from GDX file A.gdx $load e f g
See also $(on|off)Filtered, $(on|off)Multi, and $onMultiR.
Syntax:
$gdxLoadAll GDXFileName
This option loads all symbols known from a specified GDX file. It is similar to $gdxLoad, but does not need/allow a list of symbols to be loaded. Instead it compares the list of previous declared symbols with the symbols in the specied GDX file and loads all symbols that match. If we have incompatibilities between symbols in GDX and GAMS (the incompatibilities are the same as if we would do an explicit
$load sym
) CMEX triggers an error. Symbols in GDX that don't exist in GAMS are just ignored.Example:
If there is a GDX file
trnsport
created from the [TRNSPORT] model, the following code will load the symbolsi
,j
andc
. All other symbols are ignored:Set i,j,k; Parameter c(i,j); $gdxLoadAll trnsport.gdx
See also $(on|off)Filtered, $(on|off)Multi, and $onMultiR.
Syntax:
$gdxOut [GDXFileName]
This option is used in a sequence to unload specified items to a GDX file at compile time. Here
GDXFileName
denotes the name of the GDX file (with or without the extension GDX) and the command opens the specified GDX file for writing. The use of$gdxOut
without a file name closes the currently open output GDX file and initiates the actual writing of the sequence of symbols. The command is used in conjunction with the dollar control option $unLoad.Example:
set i /i1*i3/; parameters a(i) /i1 3, i2 87, i3 1/; $gdxOut mydata.gdx $unLoad i a $gdxOut
Syntax:
$gdxUnload GDXFileName [sym1[,] sym2=gdxSym2[,] ...]
This option unloads symbols from a specified GDX file. It basically combines $gdxOut and $unload in one call. This can be particularly useful for $[bat|lib]include files when you want to be sure, to not interfere with potentially previously opened GDX files. For example, a $unload after a "$gdxUnload" will still unload the symbols to the GDX file opened before:
$gdxOut A.gdx $unload a b c $gdxUnload B.gdx d * The following $unload puts the symbols e, f, and g into GDX file A.gdx $unload e f g
Syntax:
$goto id $label id
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 $batinclude 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, jumps to the same label are restricted to a maximum of 100 times by default. This maximum may be changed with the option $maxGoto.Example:
Scalar a ; a = 5; display a ; $goto next a = a+5 ; display a ; $label next a = a+10 ; display a ;
Note that GAMS will continue from line
$label next
after reading line$goto next
. Observe that all lines in between are ignored. Therefore the final value ofa
in the example above will be 15.
- Attention
- The lines
$goto
and $label have to be in the same file. If the target label is not found in the current file an error will be issued.
$hidden
Syntax:
$hidden text
A line starting with this option 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.
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.
- Note
- This option is particularly useful when the input file is encrypted.
$hiddenCall
Syntax:
$hiddenCall [=]command
This option does the same as $call but the statement is neither shown on the log nor the listing file.
$hiddenCall.Async[NC]
Syntax:
$hiddenCall.Async[NC] command
This option does the same as $call.Async[NC] but the statement is neither shown on the log nor the listing file.
$hiddenCall.checkErrorLevel
Syntax:
$hiddenCall.checkErrorLevel [=]command
This option does the same as $call.checkErrorLevel but the statement is neither shown on the log nor the listing file.
$hiddenCallTool
Syntax:
$hiddenCallTool command
This option does the same as $callTool but the statement is neither shown on the log nor the listing file.
$hiddenCallTool.checkErrorLevel
Syntax:
$hiddenCallTool.checkErrorLevel command
This option does the same as $callTool.checkErrorLevel but the statement is neither shown on the log nor the listing file.
Syntax:
$hide all | ident1 ident2 ...
This option hides identifiers so they cannot be displayed or computed, but they may still be used in model calculations (i.e. commands when the solve statement is executed).
With explicit identifiers the listed identifiers are hidden and with
all
all identifiers are hidden. These restrictions may be removed with the dollar control options expose or purge. Note that a special license file is needed for this feature to work.For further information, see chapter Secure Work Files.
Syntax:
$if [not] conditional_expression new_input_line
This dollar control option provides the greatest amount of control over conditional processing of the input file(s).
For more information on the
conditional
expressions
allowed, details on thenew_input_line
and examples, see section Conditional Compilation below.
Syntax:
$ifE [not] conditional_expression new_input_line
This dollar control option does the same as the option $if but allows constant expression evaluation. The
conditional_expression
may take two different forms:expr1 == expr2 TRUE if (expr1-expr2)/(1+abs(expr2)) < 1e-12 expr TRUE if expr1 <> 0Example:
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 output:
---- 3 PARAMETER a = 1.000 ---- 4 PARAMETER a = 2.000 ---- 6 PARAMETER a = 4.000See also $if and section Conditional Compilation.
Syntax:
$ifI [not] conditional_expression new_input_line
This option is working like the option $if. The only difference is that $if makes comparisons involving text in a case sensitive fashion while
$ifI
is case insensitive.See also $if and section Conditional Compilation.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option is a form of the option $if that controls whether a number of statements are active. The syntax for the condition is generally the same as for the option $if. Like
$if
, it is case sensitive. Often it is followed by one or more of the following dollar control options: $else, $elseIf, $elseIfI, $elseIfE. The option$ifThen
must be matched with the option $endIf that marks the end of the construct. An example is given in section Conditional Compilation with $ifThen and $else.Note that users may add a tag to the
$ifThen
and $endIf. For example,$ifThen.tagOne
has to match with$endif.tagOne
.Example:
$ifThen.one x == y display "it1"; $elseIf.one a == a display "it2"; $ifThen.two c == c display "it3"; $endIf.two $elseIf.one b == b display "it4"; $endIf.one
The resulting listing file will contain the following lines:
---- 2 it2 ---- 4 it3Note that the first condition (
x == y
) is obviously not true and the fourth condition (b == b
) is not tested because the second condition (a == a
) was already true.Also note that the false clause is not interpreted by the compiler. So the following code would compile without problems:
$ifThen x == y $the $compiler doesn't complain $endIf
See also $if, $ifThenE, $ifThenI, $else, $elseIF and section Conditional Compilation.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option does the same as the option $ifThen but evaluates numerical values of the control variables.
See also $ifThen and section Conditional Compilation.
Syntax:
$ifThen[E|I] cond ... { $elseIf[E|I] cond ... } [ $else ... ] $endIf
This option does the same as the option $ifThen but it is case insensitive.
See also $ifThen and section Conditional Compilation.
Syntax:
$include external_file
This option inserts the contents of a specified text file at the location of the call. Note that text files that have been compressed with Posix utility
gzip
or have been encrypted with tool ENDECRYPT are also allowed.External_file
is the name of the file that is included. It can be quoted or unquoted. Note that include files may be nested.The include file names are processed in the same way like the input file. 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 search path may be extended with the command line parameter InputDir.
Note that the start of the include file is marked and the include file is echoed to the echo print in the listing file. This reference to the include file may be omitted by using the option $offInclude.
Example:
$include myfile $include "myfile"
Both statements above are equivalent and the search order for the include file is as follows:
myfile
in current working directorymyfile.gms
in current working directorymyfile
andmyfile.gms
(in that order) in directories specified by the command line parameter InputDir.
- 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 option $onGlobal is set.
Note that details on the compilation output of include files are given in section The Include File Summary.
See also $batInclude, $libInclude, $sysInclude.
Syntax:
$inlineCom char[char] char[char]
This option redefines and activates the in-line comment symbols. These symbols are placed at the beginning and the end of the in-line comment and are one character or a two character sequence at the beginning and the end. By default, the system is initialized to ' \(/*\)' and ' \(*/\)', but is not active. The option $onInline is used to activate the in-line comments. If
$inlineCom
is used, $onInline is set automatically.Example:
$inlineCom {{ }} Set {{ this is an inline comment }} i / 1*2 / ;
Note that the character pairs
{{ }}
serve as the indicator for in-line comments.
- Attention
- It is not allowed to reset the option
$inlineCom
to the current symbol for in-line comments. This would cause an compilation error as in the following example:$inlinecom {{ }} $inlinecom {{ }}
- Note
- The option $onNestCom enables the use of nested comments.
The default for dealing with inline comments can be set using the command line parameter inlineCom.
See also section Comments.
Syntax:
$kill ident {ident}
This option removes all data for the identifiers
ident
, only the type and dimension are retained (this means that these identifiers will be declared but not defined anymore). Note that only the data of the following data types may be removed: sets, parameters, variables and equations. Note further that the data removal is carried out during compile time and not when the GAMS program executes.Example:
Set i / 1*20 /; Scalar a /2/; $kill i a
Note that the effect of the third line above is that all data from
a
andi
is removed, so the seti
and the scalara
are declared, but not initialized or assigned to. Note that afteri
anda
have been killed, a display statement for them will trigger an error. However, new data may be assigned to identifiers that were previously killed. Thus the following statements are valid if appended to the code above:Set i / i1 *i3 /; a = 7;
Observe that this option needs to be distinguished from the dollar control option $clear, that resets the data to the default values.
Syntax:
$goto id $label id
This option marks a line to be jumped to by a dollar control option $goto. Any number of labels may be used in files and not all of them need to be referenced. Re-declaration of a label identifier will not generate an error and only the first occurrence encountered by the GAMS compiler will be used for future $goto references.
Example:
Scalar a ; a = 5 ; display a ; $goto next a = a+5 ; display a ; $label next a = a+10 ; display a ;
When GAMS reaches the line
$goto next
, it continues from the line$label next
. All lines in between are ignored. Therefore in the example above, the final value ofa
is 15.
- Attention
- If several dollar control options appear in one line and
label
is one of them, thenlabel
must be listed first.
Syntax:
$libInclude external_file {arg}
This option is mostly equivalent to the option $batInclude. 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 directory
inclib
in the GAMS standard locations. Note that the list of default directories searched may be prepended with the command line parameter libIncDir.Example:
$libInclude abc x y
This call will first look for the include file
inclib/abc
in the standard locations. If this file does not exist there GAMS will look for the fileinclib/abc.gms
in the standard locations. The argumentsx
andy
are passed on to the include file and are interpreted as explained in the detailed description of the option $batInclude.See also $include, $batInclude, $sysInclude.
Syntax:
$lines n
This option starts a new page in the listing file if less than
n
lines are available on the current page.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.
Syntax:
$load [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option is preceded and succeeded by the option $gdxIn that open the GDX file for reading. The option
$load
loads specified items from the GDX file. Note that more than one instance of$load
may occur. A listing of the GDX file contents will be created if the option$load
is not followed by arguments.Examples
Consider the following example, where
transsol
is the GDX file of the transportation model [TRNSPORT]$gdxIn transsol $load Sets i, j; Parameters a(i), b(j), d(i,j), f; $load i j a b d f $gdxIn
A comma between the symbols is optional. The follow example works identically:
$gdxIn transsol $load Sets i, j; Parameters a(i), b(j), d(i,j), f; $load i, j, a, b, d, f $gdxIn
The
$load
without any arguments produces a table of contents of the GDX container in the listing file:Content of GDX C:\Users\default\Documents\gamsdir\projdir\transsol.gdx 5 UELs Number Type Dim Count Name 1 Set 1 2 i canning plants 2 Set 1 3 j markets 3 Parameter 1 2 a(i) capacity of plant i in cases 4 Parameter 1 3 b(j) demand at market j in cases 5 Parameter 2 6 d(i,j) distance in thousands of miles 6 Parameter 0 1 f freight in dollars per case per thousand miles 7 Parameter 2 6 c(i,j) transport cost in thousands of dollars per case 8 Variable 2 6 x(i,j) shipment quantities in cases 9 Variable 0 1 z total transportation costs in thousands of dollars 10 Equation 0 1 cost define objective function 11 Equation 1 2 supply(i) observe supply limit at plant i 12 Equation 1 3 demand(j) satisfy demand at market jSymbols may be loaded with new names with the following syntax:
$load i=gdx_i j=j_gdx
. The universal set may be loaded using$load uni=*
.$gdxIn transsol Sets i, jj, uni; Parameters a(i), bb(jj), d(i,jj), f; $load i jj=j uni=* a bb=b d f $gdxIn display uni;
This results in a display of all used labels:
---- 5 SET uni Seattle , San-Diego, New-York , Chicago , TopekaThe syntax
sym<[=]GDXSym[.dimI]
allows to load a one dimensional set from a symbol in the GDX file that has even a higher dimensionality. GAMS tries to find the setsym
as a domain in the symbolGDXSym
and uses the labels from this index position (with<
the first domain set from the right and with<=
from the left). If no domain information is stored in the GDX file or the domain information does not match the suffix.dimI
allows to pick a fixed index position.In the following we work with a GDX file created by the following code:
set i / i1*i3 /, ii(i,i) / i1.i2, i2.i3 /; execute_unloadDI 'ii', i, ii;
Now use use this GDX file to load the first and second index from
ii
:set i, i1; $gdxIn ii * Load first index from ii as i $load i<=ii i1<ii.dim1 display i, i1;
the display lists all labels from the first index of
ii
:---- 5 SET i Domain loaded from ii position 1 i1, i2 ---- 5 SET i1 Domain loaded from ii position 1 i1, i2Now we match from the right and get the second index of
ii
:set i, i2; $gdxIn ii * Load second index from ii as i $load i<ii i2<ii.dim2 display i, i2;
The resulting listing file will contain the following lines:
---- 5 SET i Domain loaded from ii position 2 i2, i3 ---- 5 SET i2 Domain loaded from ii position 2 i2, i3This type of projection loading can be useful to extract the domain sets from a single parameter that is stored in a GDX file:
set i,j,k; parameter data(i,j,k); $gdxIn data $load i<data.dim1 j<data.dim2 k<data.dim3 data
- Attention
- Loading an item that was already initialized will cause a compilation error.
For example, the following code snippet will cause a compilation error:
Set j / 1*5 /; $gdxIn transsol $load j $gdxIn
Note that GAMS offers variants of
$load
that do not cause a compilation error in such a case: $loadM and $loadR.
- Note
- One can load the level values of a variable into a parameter of the same dimension using the syntax
parametername=var.l
as follows
Loading the level values for a variable into the same variable (x=x.l) works but loads everything including bounds, scales, marginals and levels.parameter storexlevel(i,j); $gdxin trnsport $load storexlevel=x.l $gdxin display storexlevel;
Syntax:
$loadDC [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option is an alternative form of $load. It performs domain checking when items are loaded. Any domain violations will be reported and flagged as compilation errors. This is basically the opposite of $loadFiltered. All other features are the same as discussed under $load .
Example: Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set i, j; Parameter b(i), a(j); $gdxIn transsol $load i b $loadDC j a $gdxIn
Note that in contrast to the example above, the parameter
a
is indexed over the seti
and the parameterb
is indexed over the setj
in the filetranssol
. While$load i b
does not generate an error andb
is just empty, the option$loadDC j a
triggers a domain violation error because intranssol
a
is indexed overi
and produces a list of errors in the listing file:--- LOAD a = 3:a **** Unique domain errors for symbol a Dim Elements 1 seattle, san-diego 5 $loadDC j a **** $649
Syntax:
$loadDCM [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option combines the functionality of merging as in $loadM and domain checking as in $loadDC.
Example:
Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set i, uni 'all labels'; Parameter abFail(i), ab(uni) 'capacity and demand'; $gdxIn transsol $load i abFail=a $loadDCM abFail=b $loadDCM uni=i uni=j ab=a ab=b $gdxIn display uni, ab;
Here we try to merge parameters
a
andb
together into one parameter. The first attempt (to merge it into parameterabFail
) would fail because of line 5 and result into a domain violation report as described with dollar control option $loadDC. In the second attempt we first merge the setsi
andj
into setuni
and then merge the parametersa
andb
intoab
. If one comments line 5 the resulting display looks as follows:---- 8 SET uni all labels seattle , san-diego, new-york , chicago , topeka ---- 8 PARAMETER ab capacity and demand seattle 350.000, san-diego 600.000, new-york 325.000 chicago 300.000, topeka 275.000
Syntax:
$loadDCR [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option combines the functionality of replacing data as in $loadR and domain checking as in $loadDC.
Example:
Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set uni 'all labels'; Parameter ab(uni) 'capacity and demand'; $gdxIn transsol $loadM uni=i uni=j ab=a $loadDCR ab=b $gdxIn display uni, ab;
Here we try to read twice into the parameter
ab
. First GDX symbola
andb
are read intoab
. GDX symbolb
is read with replace and hence the parameterab
contains the elements ofb
only.
Syntax:
$loadFiltered [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option is an alternative form of $load, in particular, it works like
$load
while $onFiltered is set. That means, when items are loaded, domain violations are not flagged as compilation errors, but items violating the domain definition are just filtered out. This is basically the opposite of $loadDC. All other features are the same as discussed under $load .Example: Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set i / seattle / j / new-york, chicago /; Parameter a(i), b(j); $gdxIn transsol $loadFiltered a $loadDC b $gdxIn
While
$loadFiltered a
does not generate an error, but just ignores the data that does not match the defined domain,$loadDC b
triggers a domain violation error.See also $loadFilteredM and $loadFilteredR.
Syntax:
$loadFilteredM [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option combines the functionality of merging as in $loadM and domain filtering as in $loadFilterd.
Example:
Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set i, uni 'all labels'; Parameter abFilter(i), ab(uni) 'capacity and demand'; $gdxIn transsol $load i abFilter=a $loadFilteredM abFilter=b $loadFilteredM uni=i uni=j ab=a ab=b $gdxIn Display uni, ab, abFilter;
Here we try to merge parameters
a
andb
together into one parameter. The first attempt (to merge it into parameterabFilter
) does not add anything, since the elements in b do not match the defined domaini
(compare $loadFilterd). In the second attempt we first merge the setsi
andj
into setuni
and then merge the parametersa
andb
intoab
. TheDisplay
statement produces the following output:---- 31 SET uni all labels seattle , san-diego, new-york , chicago , topeka ---- 31 PARAMETER ab capacity and demand seattle 350.000, san-diego 600.000, new-york 325.000, chicago 300.000, topeka 275.000 ---- 31 PARAMETER abFilter capacity of plant i in cases seattle 350.000, san-diego 600.000
Syntax:
$loadFilteredR [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option combines the functionality of replacing data as in $loadR and domain filtering as in $loadFilterd.
Example:
Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set uni 'all labels'; Parameter ab(uni) 'capacity and demand'; $gdxIn transsol $loadFilteredM uni=i uni=j ab=a $loadFilteredR ab=b $gdxIn Display uni, ab;
Here we try to read twice into the parameter
ab
. First GDX symbola
andb
are read intoab
. GDX symbolb
is read with replace and hence the parameterab
contains the elements ofb
only:---- 31 SET uni all labels seattle , san-diego, new-york , chicago , topeka ---- 31 PARAMETER ab capacity and demand new-york 325.000, chicago 300.000, topeka 275.000
Syntax:
$loadIdx [sym1[,] sym2=gdxSym2[,] ...]
This option is an alternative form of $load. Each symbol in the GDX file to read must be a parameter and should have been written using an indexed write; see also execute_unloadidx.
See Example 3 - Reading a GDX File and [ldidx01] on how to use
$loadidx
.
Syntax:
$loadM [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option is an alternative form of $load. Instead of replacing an item or causing a symbol redefined error if the item was already initialized it merges the contents. Records that would result in domain violations will be ignored.
Example:
Consider the following example where
transsol
is the GDX file of the transportation model [TRNSPORT].Set i, uni 'all labels'; Parameter ab(uni) 'capacity and demand'; $gdxIn transsol $loadM uni=i uni=j ab=a ab=b $gdxIn display uni, ab;
Here we merge parameters
a
andb
together into one parameterab
. We first merge the setsi
andj
into setuni
and then merge the parametersa
andb
intoab
. The resulting display looks as follows:---- 6 SET uni all labels seattle , san-diego, new-york , chicago , topeka ---- 6 PARAMETER ab capacity and demand seattle 350.000, san-diego 600.000, new-york 325.000 chicago 300.000, topeka 275.000
Syntax:
$loadR [sym1[,] sym2=gdxSym2[,] sym3<[=]gdxSym3[.dimI][,] ...]
This option is a variant of the option $load. With
$loadR
we can have multiple loads into the same symbols and the data stored in GAMS will be replaced with the one from the GDX container.Example:
Consider the following example, where
transsol
is the GDX file of the transportation model [TRNSPORT]:Sets i / 1*3 / j / 1*2 /; $gdxIn transsol $loadR i j $gdxIn display i, j;
The resulting listing file will contain the following lines:
---- 6 SET i canning plants Seattle , San-Diego ---- 6 SET j markets New-York, Chicago , Topeka
Syntax:
$log text
This option will send a message
text
to the log file. Recall that by default, the log file is the console. The default log file may be reset with the command line parameters logOption and logFile.
- Attention
- Leading blanks are ignored when the text is written out to the log file as a result of using the
$log
option.- All special
%
symbols will be substituted before the text passed through the$log
option is sent to the log file.Example:
$log $log The following message will be written to the log file $log with leading blanks ignored. All special % symbols will $log be substituted before this text is sent to the log file. $log This was line %system.incLine% of file %system.incName% $log
The log file that results by running the lines above will contain the following lines:
The following message will be written to the log file with leading blanks ignored. All special % symbols will be substituted before this text is sent to the log file. This was line 5 of file C:\tmp\logTest.gmsNote that
%system.incLine%
is replaced by 5 which is the line number where the string replacement was requested. Note further that%system.incName%
is substituted with the name of the file completed with the absolute path. Observe that the leading blanks on the second line of the example are ignored.
Syntax:
$macro name(arg1,arg2,arg3, ...) macro_body
This option defines a macro in GAMS. Here
name
is the name of the macro,arg1,arg2,arg3,...
are the arguments andmacro_body
defines what the macro should do. The macro names follow the rules for identifiers. The macroname
cannot be used for other symbols. For further details and examples, see section Macros in GAMS below.
Syntax:
$maxCol n
This option restricts the valid range of input columns at the right margin. Note that all input after column
n
is treated as comment, therefore it is ignored.Example:
$maxCol 30 Set i / vienna, rome /; set definition Scalar a / 2.3 /; scalar definition
Observe that the text strings
set definition
andscalar definition
are treated as comments and are ignored since they begin on or after column 31.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 following message:NEW MARGINS: 20-110
- Note
- GAMS requires that the right margin set by
$maxCol
is greater than 15.- GAMS requires that the right margin set by
$maxCol
is greater than the left margin set by $minCol.See also $on/offMargin and section Comments.
Syntax:
$maxGoTo n
This option sets the maximum number of jumps to the same label and is used in the context of the options $goTo and $label. Once the maximum number is reached a compilation error is triggered. Such a limit has been implemented to avoid infinite loops at compile time.
Example:
Scalar a / 1 /; $maxGoTo 5 $label label1 a = a+10; display a ; $goTo label1
Note that a compilation error is triggered if
$goTo label1
is called for the fifth time.
Syntax:
$minCol n
This option restricts the valid range of input columns at the left margin. Note that all input before column
n
is treated as comment, therefore it is ignored.Example:
$minCol 30 Set definition Set i / vienna, rome /; Scalar definition Scalar a / 2.3 /;
Observe that the text strings
set definition
andscalar definition
are treated as comments and are ignored since they are placed before column 30.Any changes in the margins via the option $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 MARGINS: 20-110
- Attention
- GAMS requires that the left margin set by the option
$minCol
is smaller than the right margin set by the option $maxCol.See also $on/offMargin and section Comments.
$(on|off)CheckErrorLevel ($offCheckErrorLevel)
Syntax:
$onCheckErrorLevel $offCheckErrorLevel
If the option
$onCheckErrorLevel
is active, the errorLevel is checked implicitly after $call, $hiddenCall, $callTool and $hiddenCallTool. A compilation error is triggered and the compilation is aborted if it is not 0. With$offCheckErrorLevel
, this is not done, but one can do it explicitly. So, with$onCheckErrorLevel
$call behaves like $call.checkErrorLevel, $hiddenCall behaves like $hiddenCall.checkErrorLevel, $callTool behaves like $callTool.checkErrorLevel and $hiddenCallTool behaves like $hiddenCallTool.checkErrorLevel.The default for dealing with error levels can be set using the command line parameter checkErrorLevel.
Syntax:
$onDelim $offDelim
This option controls whether data in table statements may be entered in delimited format. As delimiter one can use
"."
,","
, or"TAB"
.Example:
Sets plant 'plant locations' / NEWYORK, CHICAGO, LOSANGELES / market 'demands' / MIAMI, HOUSTON, PORTLAND /; Table dist(plant,market) $onDelim ,MIAMI,HOUSTON,PORTLAND NEWYORK,1300,1800,1100 CHICAGO,2200,1300,700 LOSANGELES,3700,2400,2500 $offDelim ; Display dist;
The resulting listing file will contain the following output:
---- 12 PARAMETER dist MIAMI HOUSTON PORTLAND NEWYORK 1300.000 1800.000 1100.000 CHICAGO 2200.000 1300.000 700.000 LOSANGELES 3700.000 2400.000 2500.000
Syntax:
$onDigit $offDigit
Historically, GAMS has run on widely different platforms where even the floating-point arithmetic varied. To ensure the precision specified in the GAMS input didn't exceed what could be stored and computed with as GAMS ran, we limited the precision (i.e. the number of significant digits used for numbers) that could be specified in the GAMS source. This limit could be relaxed by using the
$offDigit
control.Modern computers all support IEEE double-precision arithmetic, and GAMS uses this internally. It's a well-accepted and familiar standard, and the current behavior - to convert the decimal value in the GAMS source into the nearest double-precision value, regardless of the number of digits in the GAMS source - is what is generally expected. There is a limit (currently 40) on the number of digits treated as potentially significant: digits beyond this point are quietly treated as zero.
The
$offDigit
control remains useful for changing how GAMS handles numbers with very large or small magnitude. With$onDigit
, GAMS throws compiler warnings/errors for these values. With$offDigit
, GAMS quietly converts them to UNDF or EPS, respectively.Example:
scalar aboveTheLimit / 222e299 /; scalar tiny / 1.0e-275 /; scalar tinier / 1.0e-285 /; $offdigit scalar uberTheLimit / 222e299 /; scalar klein / 1.0e-275 /; scalar kleiner / 1.0e-285 /;
The resulting listing file will contain the following lines:
1 scalar aboveTheLimit / 222e299 /; **** $106 2 scalar tiny / 1.0e-275 /; **** $595 3 scalar tinier / 1.0e-285 /; **** $594 5 scalar uberTheLimit / 222e299 /; 6 scalar klein / 1.0e-275 /; 7 scalar kleiner / 1.0e-285 /; Error Messages 106 abs(number) out of range abs(number) must be less than 1E300 $offdigit can be used to replace large numbers with UNDF 594 Exponent very very small - rejected $offdigit can be used to replace with EPS 595 Exponent very small $offdigit can be used to quietly accept very small valuesThe default for dealing with digits can be set using the command line parameter digit.
Syntax:
$onDollar $offDollar
This option controls the echoing of dollar control option lines in the listing file.
Example:
$hidden This line will not be displayed $onDollar $hidden This line will be displayed $offDollar $hidden This line will not be displayed
The compilation output of the resulting listing file will contain the following lines:
2 $onDollar 3 $hidden This line will be displayedNote that all lines between the option
$onDollar
and the option$offDollar
are echoed in the listing file. Note further that the effect of this option is immediate: the line$onDollar
is echoed in the listing file, while the line$offDollar
is not.
Syntax:
$onDotL $offDotL
This option activates or deactivates the automatic addition of the attribute
.L
to variables on the right-hand side of assignments and in put statement. It is most useful in the context of macros. For further information, see section Macros in GAMS below.Example:
Consider the following code snippet which can be added to the end if the [TRNSPORT] model:
$onDotL file fx; put fx; loop((i,j), put / x(i,j) ); $offDotL file fx; put fx; loop((i,j), put / x(i,j) );
This is the generated output:
50.00 300.00 0.00 275.00 0.00 275.00 x('seattle','new-york') x('seattle','chicago') x('seattle','topeka') x('san-diego','new-york') x('san-diego','chicago') x('san-diego','topeka')First, we see the
level
for eachx
record. After setting$offDotL
we are back at the default which means, that the .tn attribute is used implicitly.
$(on|off)DotScale ($offDotScale)
Syntax:
$onDotScale $offDotScale
This option activates or deactivates the automatic addition of the attribute
.Scale
to variables and equations on the right-hand side of assignments and in put statements. As with on|offDotL It is most useful in the context of macros. For further information, see section Macros in GAMS below.
Syntax:
$onEcho[S|V][.tag] >[>] external_file text {text} $offEcho[.tag]
This option is used to send one or more lines of
text
to an fileexternal_file
. The text and the file name may be quoted or unquoted. The external file is not closed until the end of the compilation or when the option $call or any variant of the option $include is encountered. Note that the redirection symbols>
and>>
have the usual meaning:>
creates a new file and writes to it or - in case there exists already a file with the respective name - overwrites the existing file and>>
appends to a file. Note further that parameter substitutions are permitted with$onEcho
. The option$onEcho
has two more variants:$onEchoS
and$onEchoV
.$onEchoS
allows parameter substitutions like$onEcho
, so it is just a synonym which makes it more obvious that parameter substitution is allowed with the appendedS
. The option$onEchoV
does not allow parameter substitutions but writes the text verbatim.Example:
$set it TEST $onEchoS > externalfile1.txt send %it% to external file line 2 to send $offEcho $onEchoV > externalfile2.txt send %it% to external file line 2 to send $offEcho
The
externalfile1.txt
will contain the following lines:send TEST to external file line 2 to sendThe
externalfile2.txt
will contain these lines:send %it% to external file line 2 to sendObserve that in the first case
%it%
is substituted withTEST
, but in the second case there is no substitution.Note that by default the external file will be placed in the current working directory if there is no path specified.
One may add a
tag
to the$onEcho[S|V]
and$offEcho
. This allows to use nested echo blocks like this:$onEcho.outer > outerFile.gms $onEcho.inner > innerFile.txt Line 1 of text Line 2 of text $offEcho.inner $offEcho.outer
The resulting file
outerFile.gms
looks like this:$onEcho.inner > innerFile.txt Line 1 of text Line 2 of text $offEcho.inner
$(on|off)ECImplicitLoad ($onECImplicitLoad)
Syntax:
$onECImplicitLoad $offECImplicitLoad
This option enables or disables the implicit loading of symbols set in embedded code sections, which are not loaded explicitly with $offEmbeddedCode.
Example:
Set i(*); $offECImplicitLoad $onEmbeddedCode Python: i = ['a','b'] print(i) gams.set("i", i) $offEmbeddedCode
This will result in a compilation error, since
i
is set in the embedded code block (bygams.set("i", i)
), but not loaded with$offEmbeddedCode
. If$onECImplicitLoad
would be active,$offEmbeddedCode
would be treated like$offEmbeddedCode i
here.See also ECImplicitLoad.
$(on|off)Embedded ($offEmbedded)
Syntax:
$onEmbedded $offEmbedded
This option enables or disables the use of embedded values in parameter and set data statements. If enabled, the explanatory text for set elements is concatenated with blank separators. For parameters, the embedded values get multiplied.
Example:
Set k / a,b / l / a /; Set i(k,l) / a.a 'aaaa cccc dddd' b.a 'bbbb cccc dddd' /; Parameter m(k,l) / a.a 12 b.a 24 /; $onEmbedded Set j(k,l) / (a aaaa, b bbbb).(a cccc) dddd /; Parameter n(k,l) / (a 1, b 2) .(a 3) 4 /;
Note that the explanatory text of the set elements in
i
andj
as well as the values of the parametersm
andn
are identical.
$(on|off)EmbeddedCode[S|V][.tag]
Syntax:
$onEmbeddedCode[S|V][.tag] Connect|Python: [arguments] Embedded code {Embedded code} $offEmbeddedCode[.tag] {symbol[<[=]embSymbol[.dimX]]}
This option is used to execute one or more lines of embedded code (e.g. Python code) while GAMS stays alive. The embedded code has access to GAMS symbols and can read and change them.
Note that parameter substitutions are permitted with
$onEmbeddedCode
. The option$onEmbeddedCode
has two more variants:$onEmbeddedCodeS
and$onEmbeddedCodeV
.$onEmbeddedCodeS
allows parameter substitutions like$onEmbeddedCode
, so it is just a synonym which makes it more obvious that parameter substitution is allowed with the appendedS
. The option$onEmbeddedCodeV
does not allow parameter substitutions but passes the code verbatim to the embedded code engine. The optionalarguments
given to$onEmbeddedCode[S|V]
can be accessed in the Python code.
$offEmbeddedCode
can be followed by a GAMS symbol or a list of GAMS symbols. If GAMS symbols are specified they get updated in the GAMS database after the embedded code got executed. The syntaxsymbol<[=]embSymbol[.dimX]
allows to load a one dimensional set from a symbol which was set in the embedded code that has even a higher dimensionality (here we call<[=]
theprojection operator
). GAMS tries to find the setsymbol
as a domain in the symbolembSymbol
and uses the labels from this index position (with<
the first domain set from the right and with<=
from the left). If no domain information is stored in the GDX file or the domain information does not match the suffix.dimX
allows to pick a fixed index position (X
needs to be replaced by the desired index position).One may add a
tag
to the$onEmbeddedCode[S|V]
and$offEmbeddedCode
. For example,$onEmbeddedCode.tagOne
would match with$offEmbeddedCode.tagOne
.Example:
Set cc / "France - Paris", "France - Lille", "France - Toulouse" "Spain - Madrid", "Spain - Cordoba", "Spain - Seville", "Spain - Bilbao" "USA - Washington DC", "USA - Houston", "USA - New York", "Germany - Berlin", "Germany - Munich", "Germany - Bonn" / country city mccCountry(cc,country<) Mapping between country and related elements in set cc mccCity(cc,city<) Mapping between city and related elements in set cc; $onEmbeddedCode Python: mccCountry = [] mccCity = [] for cc in gams.get("cc"): r = str.split(cc, " - ", 1) mccCountry.append((cc,r[0])) mccCity.append((cc,r[1])) gams.set("mccCountry",mccCountry) gams.set("mccCity",mccCity) $offEmbeddedCode mccCountry mccCity Option mccCountry:0:0:1, mccCity:0:0:1; Display country, city, mccCountry, mccCity;
The data definition of the sets
country
andcity
happen while loading the setmccCountry
andmccCity
implicitly because of the implicit set definition in declarations ofmccCountry
andmccCity
. Also note, that the list of output symbols does not need to be explicitly specified (for most embedded code engines). Performing the actual write in the embedded code (here viagams.set
) is sufficient to signal GAMS to load the symbols. Providing an explicit list of symbols can be required (for embedded code engines without implicit loading) and be advantageous for code readability even for embedded code engines that support this. With the dollar control option $offECImplicitLoad providing an explicit list of output symbols can be enforced and setting symbols inside the embedded code not in the explicit list will lead to compilation errors.The program above will result in the following listing file:
---- 25 SET country Spain , USA , Germany, France ---- 25 SET city Berlin , Bilbao , Cordoba , Madrid New York , Washington DC, Paris , Houston Munich , Lille , Seville , Bonn Toulouse ---- 25 SET mccCountry France - Paris .France France - Lille .France France - Toulouse .France Spain - Madrid .Spain Spain - Cordoba .Spain Spain - Seville .Spain Spain - Bilbao .Spain USA - Washington DC.USA USA - Houston .USA USA - New York .USA Germany - Berlin .Germany Germany - Munich .Germany Germany - Bonn .Germany ---- 25 SET mccCity France - Paris .Paris France - Lille .Lille France - Toulouse .Toulouse Spain - Madrid .Madrid Spain - Cordoba .Cordoba Spain - Seville .Seville Spain - Bilbao .Bilbao USA - Washington DC.Washington DC USA - Houston .Houston USA - New York .New York Germany - Berlin .Berlin Germany - Munich .Munich Germany - Bonn .BonnUsing the
projection operator
on the$offEmbeddedCode
line the same task could be done like this:Set cc / "France - Paris", "France - Lille", "France - Toulouse" "Spain - Madrid", "Spain - Cordoba", "Spain - Seville", "Spain - Bilbao" "USA - Washington DC", "USA - Houston", "USA - New York", "Germany - Berlin", "Germany - Munich", "Germany - Bonn" / country city mccCountry(cc,country) Mapping between country and related elements in set cc mccCity(cc,city) Mapping between city and related elements in set cc; $onEmbeddedCode Python: mccCountry = [] mccCity = [] for cc in gams.get("cc"): r = str.split(cc, " - ", 1) mccCountry.append((cc,r[0])) mccCity.append((cc,r[1])) gams.set("mccCountry",mccCountry) gams.set("mccCity",mccCity) $offEmbeddedCode country<mccCountry city<mccCity Option mccCountry:0:0:1, mccCity:0:0:1; Display country, city, mccCountry, mccCity;
Please note that due to implicit output symbol loading, see $offECImplicitLoad, the symbols
mccCountry
andmccCity
are not only used to definecountry
andcity
but are also loaded into GAMS because the embedded code usesgams.set
to write to these symbols.See also chapter Embedded Code Facility for more details.
Syntax:
$onEmpty $offEmpty
$onEmpty
allows empty data statements for list or table formats (default). When setting$offEmpty
, empty data statements will cause a compilation error.Example:
Set i / 1,2,3 / ; Set j(i) / / ; Parameter x(i) "empty parameter" / / ; Table y(i,i) "headers only" 1 2 3 ; $offEmpty *offEmpty from here on Set k(i) / / ; Parameter xx(i) "empty parameter" / / ; Table yy(i,i) "headers only" 1 2 3 ;
The resulting listing file will contain the following lines:
1 Set i / 1,2,3 / ; 2 Set j(i) / / ; 3 Parameter x(i) "empty parameter" / / ; 4 Table y(i,i) "headers only" 5 1 2 3 6 ; 8 *offEmpty from here on 9 Set k(i) / / ; **** $460 **** 460 Empty data statements not allowed. You may want to use $ON/OFFEMPTY 10 Parameter xx(i) "empty parameter" / / ; **** $460 **** 460 Empty data statements not allowed. You may want to use $ON/OFFEMPTY 11 Table yy(i,i) "headers only" 12 1 2 3 13 ; **** $462 **** 462 The row section in the previous table is missingEmpty data statements are most likely to occur when data is being entered into the GAMS model by an external program.
- Note
- The empty data statement may only be used with symbols which have a known dimension. If the dimension is also derived from the data, the option $phantom should be used to generate 'phantom' set elements.
The option
$onEmpty
in conjunction with the option $onMulti and the save and restart feature may be used to set up a model and add data later.The default for dealing with empty data statements can be set using the command line parameter empty.
Syntax:
$onEnd $offEnd
This option offers an alternative syntax for flow control statements. The option
$onEnd
causes the following words to be regarded as keywords:do
,endLoop
,endIf
,endFor
andendWhile
. They are used to close the language constructsloop
,if
,for
andwhile
respectively.Example:
- Note
- The standard syntax is given as an end-of-line comment.
Set i / 1*3 /; Scalar cond / 0 /; Parameter a(i) / 1 1.23, 2 2.65, 3 1.34/; $eolCom // $onEnd loop i do // loop (i, display a; // display a; endLoop; // ); if (cond) then // if (cond, display a; // display a; else // else a(i) = a(i)/2; // a(i) = a(i)/2; display a; // display a; endIf; // ); for cond = 1 to 5 do // for (cond = 1 to 5, a(i) = 2 * a(i); // a(i) = 2 * a(i); endFor; // ); while cond > 3 do // while (cond > 3, a(i) = a(i) / 2; // a(i) = a(i) / 2; cond = cond-1; // cond = cond-1; endWhile; // );
Observe that the alternative syntax is more in line with the syntax used in some of the popular programming languages.
- Attention
- Setting the option
$onEnd
will make the alternative syntax valid, and at the same time it will make the standard syntax invalid. Therefore the two forms of the syntax will never be valid simultaneously.
Syntax:
$onEolCom $offEolCom
This option acts as a switch to control the use of end-of-line comments. Note that by default, the end-of-line comment symbol is set to
!!
but the processing is disabled.Example:
$onEolCom Set i /1*2/ ; !! set declaration Parameter a(i) ; !! parameter declaration
Observe that after the option
$onEolCom
has been specified, comments may be entered on the same line as GAMS code.
- Note
- The option $eolCom automatically sets
$onEolCom
.The default for dealing with end-of-line comments can be set using the command line parameter eolCom.
See also section Comments.
Syntax:
$onEps $offEps
This option is used to interpret zero values as
EPS
when non-scalar parameters, variable attributes, or equation attributes are defined or loaded (e.g. from GDX or embedded code ) at compile time. This can for example be useful if the value of zero is overloaded with existence interpolation.See option zeroToEps for the execution-time equivalent.
Example 1:
Consider the following example where zero values are defined for a one dimensional parameter, once under
$onEps
and$offEps
.Set i / one, two, three, four /; Parameter a(i) / $onEps one 0 $offEps two 0 three EPS /; Display a ;
The outcome generated by the display statement follows:
---- 8 PARAMETER a one EPS, three EPSNote that only those entries specifically entered as 0 are treated as
EPS
.Example 2:
Consider the following example where zero values are loaded from a GDX file, once under
$offEps
(default) and$onEps
(derived from test library model [ZEROTOEPS1] ).Set s,t; Parameter p(s<,t<) pOnEps(s,t); $gdxIn zeropar.gdx $onText P looks like this: t1 t2 t3 s1 0 0.843267 s2 0.224053 0.349831 0 s3 0 5 $offText $load p $onEps $load pOnEps=p display p, pOnEps;
The outcome generated by the display statement follows:
---- 15 PARAMETER p t1 t2 t3 s1 0.843 s2 0.224 0.350 s3 5.000 ---- 15 PARAMETER pOnEps t1 t2 t3 s1 EPS 0.843 s2 0.224 0.350 EPS s3 EPS 5.000Example 3:
Consider the following example where zero values are loaded from embedded Python code, once under
$offEps
(default) and$onEps
(derived from test library model [ZEROTOEPS1] ).Set s / s1*s3 /; Parameter pEC(s) pECOnEps(s); $onEmbeddedCode Python: p = [('s1',1), ('s3',0)] gams.set('pEC',p) $offEmbeddedCode pEC $onEps $onEmbeddedCode Python: p = [('s1',1), ('s3',0)] gams.set('pECOnEps',p) $offEmbeddedCode pECOnEps display pEC, pECOnEps;
The outcome generated by the display statement follows:
---- 14 PARAMETER pEC s1 1.000 ---- 14 PARAMETER pECOnEps s1 1.000, s3 EPS
$(on|off)EpsToZero ($offEpsToZero)
Syntax:
$onEpsToZero $offEpsToZero
This option is used to write
EPS
values as zero when parameters, or variable and equation levels get written to GDX at compile time.See option EpsToZero for the execution-time equivalent.
Example:
Usually GAMS squeezes out 0 values when writing to GDX. To get them written anyway, one can define them as
EPS
(e.g. by using$onEps
) and set$onEpsToZero
:Set i / zero, one, two /; $onEps Parameter a(i) / zero 0 one 1 two 2 /; $onEpsToZero $gdxUnload 'zero.gdx' a
Syntax:
$onExpand $offExpand
This option changes the processing of macros that appear in the arguments of a macro call. The default operation is not to expand macros in the arguments. The switch
$onExpand
enables the recognition and expansion of macros in the macro argument list and$offExpand
will restore the default behavior.Example:
variable x(*,*); $macro f(i) sum(q, x(i,q)) $macro equ(x) equation equ_&x; equ_&x.. &x =e= 0; equ(f(i))
The macro expansion of the code above will result in an equation definition that reads as follows:
equation equ_f(I); equ_f(i).. f(i) =e= 0;
If we compile the code under
$onExpand
the argumentf(i)
is expanded before the macroequ()
gets expanding resulting in the following (incorrect) code:equation equ_sum(q, x(i,q)); equ_sum(q, x(i,q)).. sum(q, x(i,q)) =e= 0;
For further information, see section Macros in GAMS below.
$(on|off)ExternalInput ($offExternalInput)
Syntax:
$onExternalInput $offExternalInput
$onExternalInput
and$offExternalInput
mark the beginning and end of a well defined section in which data is loaded implicitly from an external data source, namely from a GDX file specified by the command line parameter IDCGDXInput.
- Note
- If none of the command line parameters IDCGDXInput, IDCGenerateGDXInput, IDCJSON, IDCGenerateJSON, or IDCGenerateGDX is set, nothing - but a few checks for consistency - will happen by setting
$onExternalInput
and$offExternalInput
.- If at least one of the before mentioned command line parameters is set, an additional license check will be triggered: Without the
MIRO Connector License
not more than 10 indexed symbols can be declared as external input or external output.For symbols, which are declared, while
$onExternalInput
is active, data in data statements of the declaration is ignored. Instead, the data is loaded from the GDX file specified by IDCGDXInput. Also for those symbols, if they are referenced with $load* or $offEmbeddedCode while$onExternalInput
is active, the data is loaded from the GDX file specified by IDCGDXInput instead of the defined data source and symbol renaming as well as the projection operator are ignored in this case.In addition, the following dollar control options are ignored, while
$onExternalInput
is active and IDCGDXInput is set:
- $batInclude
- $call
- $call.Async[NC]
- $call.checkErrorLevel
- $callTool
- $callTool.checkErrorLevel
- $gdxIn
- $hiddenCall
- $hiddenCall.Async[NC]
- $hiddenCall.checkErrorLevel
- $hiddenCallTool
- $hiddenCallTool.checkErrorLevel
- $include
- $libInclude
- $onEmbeddedCode[S|V] (including the following embedded code until
$offEmbeddedCode
is hit)- $sysInclude
Example:
Lets look at a modified version of the simple example presented here:
Set i 'canning plants' j 'markets'; $onExternalInput $call mdb2gms I=Sample.accdb Q="SELECT city1, city2, distance FROM distances" O=distances.inc Parameter d(i<,j<) 'distance in thousands of miles' / $include distances.inc /; $offExternalInput display d;
Without setting a command line parameter, this runs in the same way as described in the other chapter, so by default, setting
$onExternalInput
and$offExternalInput
does not make much of a difference. Now, lets run it with IDCGDXInput being set totranssol
, which is a GDX file generated by running the transportation model [TRNSPORT]. There will be some new messages in the log:--- GDXin=transsol.gdx --- Distances1.gms(7) 2 Mb --- Ignoring $call in externalInput section --- Distances1.gms(9) 2 Mb --- Ignoring $include in externalInput sectionFirst, we notice, that the file
transsol.gdx
will be opened for input. This happens implicitly with$onExternalInput
. Then, both the$call
as well as the$include
lines were ignored, since we do not want to query the data source explicitly defined in the model, but the GDX file defined by IDCGDXInput. Note, that the data statement in the declaration ofd
is actually empty when we ignore the$include
statement. While$onExternalInput
this does not lead to an error, but behaves as if $onEmpty was set. Looking at the output of thedisplay
statement in thelst
file, one can see that the expected data was loaded:---- 13 PARAMETER d distance in thousands of miles new-york chicago topeka seattle 2.500 1.700 1.800 san-diego 2.500 1.800 1.400If any of the options IDCGDXInput, IDCGDXOutput, IDCJSON or their
Generate
versions, e.g. IDCGenerateGDXInput, has been set, a MIRO connector license is required.See also $(on|off)ExternalOutput.
$(on|off)ExternalOutput ($offExternalOutput)
Syntax:
$onExternalOutput $offExternalOutput
$onExternalOutput
and$offExternalOutput
mark the beginning and end of a well defined section in which data is written implicitly to an external data file, namely to a GDX file specified by the command line parameter IDCGDXOutput or IDCGenerateGDXOutput.
- Note
- If none of the command line parameters IDCGDXOutput, IDCGenerateGDXOutput, IDCJSON, IDCGenerateJSON, or IDCGenerateGDX is set, nothing - but a few checks for consistency - will happen by setting
$onExternalOutput
and$offExternalOutput
.- If at least one of the before mentioned command line parameters is set, an additional license check will be triggered: Without the
MIRO Connector License
not more than 10 indexed symbols can be declared as external output or external input.Example:
This is a slightly modified code snippet of the transportation model [TRNSPORT]:
... $onExternalOutput Parameter c(i,j) 'transport cost in thousands of dollars per case'; c(i,j) = f*d(i,j)/1000; Variable x(i,j) 'shipment quantities in cases' $offExternalOutput z 'total transportation costs in thousands of dollars'; Positive Variable x; Equation $onExternalOutput cost 'define objective function' $offExternalOutput supply(i) 'observe supply limit at plant i' demand(j) 'satisfy demand at market j'; ...
Without setting a command line parameter, this runs in the same way as the original model, so by default, setting
$onExternalOutput
and$offExternalOutput
does not make much of a difference. Now, lets run it with IDCGDXOutput being set totransOut.gdx
. This generate the filetransOut.gdx
with the following content:So, this implicit generation of the output file is basically equivalent to the following explicit statement:
execute_unload 'transOut.gdx', c, x, cost;
If any of the options IDCGDXInput, IDCGDXOutput, IDCJSON or their
Generate
versions, e.g. IDCGenerateGDXInput, has been set, a MIRO connector license is required.See also $(on|off)ExternalInput.
$(on|off)Filtered ($onFiltered)
Syntax:
$onFiltered $offFiltered
This dollar control option controls how GAMS loads data from GDX with gdxLoad, $load, $loadR, and $loadM. With
$onFiltered
the$load*
calls behave like $loadFiltered* calls. With$offFiltered
the$load*
calls behave like $loadDC* calls. This dollar control option also controls how GAMS loads symbols on the $offEmbeddedCode line. With$onFiltered
data is read filtered while$offFiltered
triggers a domain check of the data. The gams.set Python function allows to overwrite the setting of this dollar control option with the argumentdomCheck=DomainCheckType.CHECKED
ordomCheck=DomainCheckType.FILTERED
.The default of how GAMS loads data from GDX can be set with the command line parameter filtered.
Syntax:
$onGlobal $offGlobal
When an include file is inserted, it inherits the dollar control options from the higher level file. However, the dollar control option settings specified in the include file do not affect the higher level file. This convention is common among most scripting languages or command processing shells. In some cases, it may be desirable to break this convention. This option allows an include file to change the options of the parent file as well.
Example:
$include 'inc.inc' $hidden after first call to include file $onGlobal $include 'inc.inc' $hidden after second call to include file
The file
inc.inc
contains the following lines:$onDollar $hidden text inside include file
The the echo print of the resulting listing file follows:
INCLUDE D:\GAMS\INC.INC 2 $onDollar 3 $hidden text inside include file INCLUDE D:\GAMS\INC.INC 7 $onDollar 8 $hidden text inside include file 9 $hidden after second call to include fileNote that the dollar control option $onDollar inside the include file does not affect the parent file until
$onGlobal
is set. The text following the option $hidden is then echoed to the listing file.
$(on|off)IDCProtect ($onIDCProtect)
Syntax:
$onIDCProtect $offIDCProtect
This controls if symbols which are declared as external input can be changed at execution time. With
$onIDCProtect
external input symbols are protected from being changed;$offIDCProtect
allows it.The initial state of this can be set with the command line parameter IDCProtect.
$(on|off)ImplicitAssign ($offImplicitAssign)
Syntax:
$onImplicitAssign $offImplicitAssign
This controls if the compiler issues or ignores the 141 error in case an unassigned symbol in the code is referenced (e.g. on the right hand side of an assignment statement). With
$onImplicitAssign
the error is ignored.The initial state of this can be set with the command line parameter ImplicitAssign.
Syntax:
$onInclude $offInclude
This option controls the listing of the expanded include file name in the listing file.
Example:
$include 'inc.inc' $offInclude $include 'inc.inc'
We assume that the file
inc.inc
contains the following lines:$onDollar $hidden Text inside include file
The resulting listing file will contain the following lines:
INCLUDE C:\tmp\inc.inc 2 $onDollar 3 $hidden Text inside include file 6 $onDollar 7 $hidden Text inside include fileNote 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
has been set. Also, the include file summary and the creation of an Expanded Include File is suppressed if$offInclude
is set.
Syntax:
$onInline $offInline
This option acts as switch to control the use of in-line comments. Note that by default, the in-line comment symbols are set to the two character pairs \(/*\) and \(*/\) but the processing is disabled. In-line comments may span several lines till the end-of-comment characters are encountered.
Example:
$onInline Set i /* The default comment symbols are now active. These comments can continue to additional lines till the closing comments are found. */ / i1*i3 / ;
- Note
- The option $inlineCom automatically sets
$onInline
.- Nested in-line comments are illegal unless the option $onNestCom is set.
The default for dealing with inline comments can be set using the command line parameter inlineCom.
See also section Comments.
Syntax:
$onListing $offListing
This option controls the echoing of input lines to the compilation output of the listing file. Note that suppressed input lines do not generate entries in the symbol and reference sections that appear at the end of the compilation output. Lines with errors will always be listed.
Example:
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 will contain the following lines:
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 1Note that the lines in the source file between the options
$offListing
and$onListing
are not echoed to the listing file.
- Note
- For some projects the listing file can become huge and can take significant time to be written. This time can be saved by setting
$offListing
at the beginning of the input file and$onListing
just before the parts one is interested in, or not at all, if one does not look at the listing file anyway.The default for dealing with the compilation output of the listing file can be set using the command line parameter listing.
Syntax:
$onLocal $offLocal
The suffix
.local
attached to the name of a controlling set will use an implicit alias within the scope of the indexed operation or on the left-hand side of an assignment statement. This feature is particularly useful in the context of nested macros.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 p(i); p(i.local) = sum(j, xxx(i,j)); display p;
Note that in the assignment statement the set
i
on the right-hand side is controlled byi.local
on the left-hand side. Thus we have the following values for the two parameters:---- 3 PARAMETER xxx 1 2 3 1 1.000 13.000 2 2.000 3 31.000 3.000 ---- 7 PARAMETER p 1 14.000, 2 2.000, 3 34.000In the example above, the suffix
.local
appeared one time on the left-hand side. The option$onLocal
allows the suffix.local
to appear more that one time attached to the same symbol. Consider the following example that extends the example above:Parameter g(i,i); g(i.local-1,i.local) = xxx(i,i); display g;
Note that in the assignment statement of
g
the suffix.local
attached to the seti
appears two times on the left-hand side. The question arises whether the reference to the seti
on the right-hand side refers to the first or the second instance of.local
on the left-hand side. The assignment statement may alternatively be written in the following way using an explicit alias statement:alias (i,i1,i2); g(i1-1,i2) = xxx(i2,i2);
Thus is becomes clear that the symbol on the right-hand side refers to the controlling index that enters last (here the second one). The output generated by the display statement follows:
---- 10 PARAMETER g 1 2 3 1 1.000 2.000 3.000 2 1.000 2.000 3.000Observe that the multiple use of the suffix
.local
on the same symbol is considered an error with the option$offLocal
.Note that it is also allowed to combine the original index with an index suffixed with
.local
. Consider the following alternative formulation:g(i.local-1,i) = xxx(i,i);
Note that in this case the index suffixed with
.local
takes precedence and the reference ofi
on the right-hand side refers to the indexi.local
even thoughi
is entered last. Observe that this statement even works with$offLocal
as the suffix.local
appears only once.See also section Macros in GAMS below.
Syntax:
$onLog $offLog
This option acts as a switch that controls logging information about the line number and memory consumption during compilation. This is scoped like the option $on/offListing applying only to included files and any subsequent included files but reverting to the setting
$onLog
in the parent files (if it was not changed there as well).Example:
Set i /i1*i20000000/; $include inc.inc Set l /l1*l20000000/;
The file
inc.inc
looks like this:Set j /j1*j20000000/; $offLog Set k /k1*k20000000/;
The generated log will contain the following lines:
--- test.gms(1) 1602 Mb 5 secs --- test.gms(2) 1602 Mb --- .inc.inc(1) 3122 Mb 6 secs --- test.gms(3) 6161 Mb 14 secsNote that the first line of both the parent and the include file got logged, but not the third line of the include file, after
$offLog
was set. The last line of the parent file got logged again.
Syntax:
$onMacro $offMacro
Enables or disables the expansion of macros defined by $macro.
Example:
$macro oneoverit(y) 1/y $offMacro y = oneoverit(x1); display y;
causes an error because the macro
oneoverit
in line 3 can not be expanded.
Syntax:
$onMargin $offMargin
This option controls margin marking, that means if margins set by the options $minCol and $maxCol, should be marked in the lst file.
Example:
$onmargin mincol 20 maxcol 51 Now we have Set i "plant" / US, UK /; This defines I turned on the Scalar x / 3.145 /; A scalar example. margin marking. Parameter a, b; Define some parameters. $offmargin
The lst file will contain this:
2 Now we have |Set i "plant" / US, UK /; |This defines I 3 turned on the |Scalar x / 3.145 /; |A scalar example. 4 margin marking. |Parameter a, b; |Define some 5 | |parameters.Note that any statements between columns 1 and 19 and any input beyond column 52 are treated as comments. These margins are marked with
| on the left and right.
See also section Comments.
Syntax:
$onMulti $offMulti
This option controls multiple data statements or tables. By default, GAMS does not allow data statements to be redefined. If this option is activated the second or subsequent data statements are merged with entries of the previous ones. Note that all multiple data statements are performed before any other statement is executed.
- Note
- There is also $onMultiR, which behaves similarly, but replaces existing data instead of merging into it. Compare the example here and there to see the difference.
- When
$onMulti
is active $load behaves like a $loadM.- The initial state of this dollar control option can be set through the command line parameter multi.
Example:
Consider the following slice of code. The list after the end of line comment describes the complete content of the symbol x after the data statement has been processed:
$eolCom // Set i / i1*i10 /; Parameter x(i) / i1*i3 1 / // /i1 1,i2 1,i3 1/ $onMulti Parameter x(i) / i7*i9 2 / // /i1 1,i2 1,i3 1,i7 2,i8 2,i9 2/ Parameter x(i) / i2*i6 3 / // /i1 1,i2 3,i3 3,i4 3,i5 3,i6 3,i7 2,i8 2,i9 2/ Parameter x(i) / i3*i5 0 / // /i1 1,i2 3,i6 3,i7 2,i8 2,i9 2/ $offMulti display x;
Note that the repeated parameter statements would have resulted in a compilation error without the presence of the option
$onMulti
. The result of the display statement in the listing file follows:---- 8 PARAMETER x 1 1.000, 2 3.000, 6 3.000, 7 2.000, 8 2.000, 9 2.000Note that
x("i1")
is assigned the value of 1 with the first data and is not affected by any of the subsequent data statements.x("i3")
on the other hand is reset to 3 by the third data statement and wiped out with 0 in the fourth data statement.
- Attention
- The two-pass processing of a GAMS file may lead to seemingly unexpected results. Dollar control options and data initialization are both done in the first pass and assignments in the second, irrespective of their relative locations. This is an issue particularly with the option
$onMulti
since it allows data initializations to be performed more than once. See section GAMS Compile Time and Execution Time Phase for details.Consider the following example:
Scalar a /12/; a=a+1; $onMulti Scalar a /20/; display a;
Note that the two
scalar
data initialization statements and the option$onMulti
are processed before the assignment statementa=a+1
. As a result, the final value ofa
will be 21. The output of the display statement follows:---- 5 PARAMETER a = 21.000Observe that the option $onEmpty in conjunction with the option
$onMulti
and the save and restart feature may be used to set up a model and add data later. See example in section Advanced Separation of Model and Data for details.
$onMultiR|offMulti ($offMulti)
Syntax:
$onMultiR $offMulti
This option controls multiple data statements or tables. By default, GAMS does not allow data statements to be redefined. If this option is activated the second or subsequent data statements replace the previous ones. Note that all multiple data statements are performed before any other statement is executed.
- Note
- There is also $onMulti, which behaves similarly, but merges into existing data instead of replacing it. Compare the example here and there to see the difference.
- In contrast to $onMulti,
$onMultiR
also allows to redefine an equation and a macro.- The initial state of this dollar control option can be set through the command line parameter multi.
Example:
Consider the following slice of code. The list after the end of line comment describes the complete content of the symbol x after the data statement has been processed:
$eolCom // Set i / i1*i10 /; Parameter x(i) / i1*i3 1 / // /i1 1,i2 1,i3 1/ $onMultiR Parameter x(i) / i7*i9 2 / // /i7 2,i8 2,i9 2/ Parameter x(i) / i2*i6 3 / // /i2 3,i3 3,i4 3,i5 3,i6 3/ Parameter x(i) / i3*i5 0 / // ( ALL 0.000 ) $offMulti display x;
Note that the repeated parameter statements would have resulted in a compilation error without the presence of the option
$onMultiR
. The result of the display statement in the listing file follows:---- 9 PARAMETER x ( ALL 0.000 )
- Note
- When using a redefinition with
$onMulitR
to remove elements from a set, which was used as domain of another symbol, also the dependent symbol gets reduced. This can happen through data statements, but also with $clear and $load/$loadDC.- When
$onMultiR
is active $load behaves like a $loadR with the exception of the previous note. So, the only way to allow for a redefiniton of a domain set is to activate$onMultiR
. If that is not active$loadR
for a domain set would trigger an error.Example:
Set i / i1*i5 /; Parameter p(i) / #i 3 /; $onMultiR Set i / i3*i6 /; Display p;
Looking at the output from the
Display
statement one can see, that the entries fori1
andi2
were removed by the second definition ofi:
---- 7 PARAMETER p i3 3.000, i4 3.000, i5 3.000
- Attention
- The two-pass processing of a GAMS file may lead to seemingly unexpected results. Dollar control options and data initialization are both done in the first pass and assignments in the second, irrespective of their relative locations. This is an issue particularly with the option
$onMultiR
since it allows data initializations to be performed more than once. See section GAMS Compile Time and Execution Time Phase for details.Consider the following example:
Scalar a /12/; a=a+1; $onMultiR Scalar a /20/; display a;
Note that the two
scalar
data initialization statements and the option$onMultiR
are processed before the assignment statementa=a+1
. As a result, the final value ofa
will be 21. The output of the display statement follows:---- 5 PARAMETER a = 21.000Observe that the option $onEmpty in conjunction with the option
$onMultiR
and the save and restart feature may be used to set up a model and add data later. See example in section Advanced Separation of Model and Data for details.
$(on|off)NestCom ($offNestCom)
Syntax:
$onNestCom $offNestCom
This option controls nested in-line comments. It makes sure that the open-comment and close-comment characters match.
Example:
$inlineCom { } onNestCom { nesting is now possible in comments { braces have to match } }
See also $inlineCom, $onInline and section Comments.
Syntax:
$onOrder $offOrder
Lag and lead operations and the ord operator require the referenced set to be ordered and constant. In some special cases users might want to use those operations 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.Example:
Set t1 / 1987, 1988, 1989, 1990, 1991 / t2 / 1983, 1984, 1985, 1986, 1987 /; Parameter p(t2); $offOrder p(t2) = ord(t2); display t2,p;
Without the
$offOrder
the compilation of the linep(t2) = ord(t2);
would have triggered a compilation error. The ordinal numbers assigned here are probably not what one expects. The element1987
gets ordinal number 1 although it seems to be last last in the set. The ordinal numbers are assigned in the order the set is stored internally in GAMS. This order is also used when displaying the sett2
:---- 6 SET t2 1987, 1983, 1984, 1985, 1986 ---- 6 PARAMETER p 1987 1.000, 1983 2.000, 1984 3.000, 1985 4.000, 1986 5.000
Syntax:
File myputfile; put myputfile; $onPut[S|V][.tag] text {text} $offPut[.tag]
The pair
$onPut[S|V]
-$offPut
causes a block of text to be placed in a put file at run-time. The is one of the few dollar control options that operate at run time. The$
in the first column usually indicates action at compile time.Note that parameter substitutions are not permitted with
$onPut
. The option$onPut
has two more variants:$onPutS
and$onPutV
.$onPutS
allows parameter substitutions while the option$onPutV
does not allow parameter substitutions, like$onPut
, so it is just a synonym which makes it more obvious that the text is written verbatim with the appendedV
.Example:
$set it TEST File myputfile; put myputfile; $onPutS Line 1 of text "%it%" Line 2 of text %it% $offPut
This code generates the put file
myputfile.put
with the following content:Line 1 of text "TEST" Line 2 of text TESTNote that the compile-time variable
%it%
was replaced byTEST
. However, if the option$onPutV
is used instead, then%it%
will not be substituted:$set it TEST File myputfile put myputfile $onPutV Line 1 of text "%it%" Line 2 of text %it% $offPut
The resulting file
myputfile.put
will contain the following lines:Line 1 of text "%it%" Line 2 of text %it%One may add a
tag
to the$onPut[S|V]
and$offPut
. This allows to use nested put blocks like this:File myputfile / outer.gms /; put myputfile; $onPut.outer File myputfile; put myputfile; $onPut.inner Line 1 of text Line 2 of text $offPut.inner $offPut.outer
The resulting file
outer.gms
looks like this:File myputfile; put myputfile; $onPut.inner Line 1 of text Line 2 of text $offPut.inner
Syntax:
$onUpper $offUpper
GAMS code echoed to the listing file is written in upper case after
$onUpper
. The default of mixed code echoing is restored with$offUpper
.
- Note
- The default case of the echo print can be set using the command line option case.
Example:
Set i 'Canning plants' / seattle, san-diego / j 'Markets' / new-york, chicago, topeka /; $onupper Parameter a(i) 'Capacity of plant i in cases' / seattle 350 san-diego 600 / $offupper b(j) 'Demand at market j in cases' / new-york 325 chicago 300 topeka 275 /;
The generated listing file looks like this:
1 Set 2 i 'Canning plants' / seattle, san-diego / 3 j 'Markets' / new-york, chicago, topeka /; 4 6 PARAMETER 7 A(I) 'CAPACITY OF PLANT I IN CASES' 8 / SEATTLE 350 9 SAN-DIEGO 600 / 10 12 b(j) 'Demand at market j in cases' 13 / new-york 325 14 chicago 300 15 topeka 275 /;
$(on|off)Recurse ($offRecurse)
Syntax:
$onRecurse $offRecurse
This option controls whether it is permitted for a file to include itself.
Example:
The following GAMS program result in a recursive inclusion of the program itself:
$onRecurse $include "%gams.input%"
Note that the maximum include nesting level is 40 and if it is exceeded an error is triggered.
In the following example that prints a string and then the reverse string the nesting level is less that 40 and one get some kind of recursion at compile time:
$onEchoV > reverse.gms $ifthene %1=%3+1 put ' ' $ exit $endif loop(map(chars,code)$(code.val=ord("%2",%1)), put chars.tl:0); $eval posPlus1 %1+1 $batInclude reverse %posPlus1% %2 %3 loop(map(chars,code)$(code.val=ord("%2",%1)), put chars.tl:0); $offEcho set chars / A*Z /, code / 65*90 /, map(chars,code) / #chars:#code /; file fx /''/; put fx; $onRecurse $batInclude reverse 1 RACECAR 7 put /; $batInclude reverse 1 LAGER 5
The log will print the following lines:
--- Starting execution: elapsed 0:00:00.067 RACECAR RACECAR LAGER REGAL *** Status: Normal completion
$(on|off)StrictSingleton ($onStrictSingleton)
Syntax:
$onStrictSingleton $offStrictSingleton
If the option
$onStrictSingleton
is active, a compilation error is triggered if a data statement for a singleton set contains more than one element. After activating the option$offStrictSingleton
GAMS will take the first element of a singleton set that was declared with multiple elements as the valid element, the other elements are disregarded and there is no error. The option to change the initial state of$(on|off)StrictSingleton
and/or to control this behavior at runtime is strictSingleton.Example:
The first element is not always the one that appears in the data statement first as the following example shows:
set i /1,2/ $offStrictSingleton singleton set ii(i) /2,1/; display ii;
The set
ii
contains the element1
because it is the first in the GAMS label order as the display statements shows:---- 4 SET ii 1
$(on|off)SuffixDLVars ($offSuffixDLVars)
Syntax:
$onSuffixDLVars $offSuffixDLVars
This option controls if it is allowed to use suffixes on variables with limited domains in a model. By default this is not allowed but this can be changed by setting
$onSuffixDLVars
.Example:
Set n / n1*n100 / t / t1*t10 / sub(n,t) / #n:#t /; Variable z, x(n,t); Equation obj; x.up(n,t) = uniformInt(7,13); obj.. z =e= sum((n,t),x(n,t)/x.up(n,t)); Model m / all, x(sub) /; Solve m min z use lp;
This causes the following error by default:
*** Problem in Model Generation: Variable "x" appears with suffix "Up". *** Error at line 12: Cannot use domain limited variables with suffix in model - use $onSuffixDLVars to allow thisThe purpose is to make the user aware of the fact, the she uses
x.l
, which would also be affected by the domain restriction ofx(sub)
in the model statement. So, if the user made sure, that this is all intended, setting$onSuffixDLVars
before the solve statements overcomes this error. Though, with the example given here, this would actually lead to a "division by zero" error, since somex.up
were excluded leaving a0
as divisor.The default for dealing with suffixes on variables with limited domains can be set using the command line parameter SuffixDLVars.
$(on|off)SuffixAlgebraVars ($onSuffixAlgebraVars)
Syntax:
$onSuffixAlgebraVars $offSuffixAlgebraVars
This option controls if it is allowed to use suffixes in equations. By default this is allowed but it can be changed by setting
$offSuffixAlgebraVars
. Activating$offSuffixAlgebraVars
can be useful to ensure, that no decision variable in a model was replaced by one of its attributes, for example if one is dealing with a model written by someone else.Example:
Variable x / l 0 /, z / l 0 /; Equation e; e.. z =e= sqr(1-x.l); Model m /e/; solve m min z use nlp;
This runs, but might give a different solution than expected.
Activating
$offSuffixAlgebraVars
will point to a potential problem:5 e.. z =e= sqr(1-x.l); **** $917 **** 917 Cannot use variable with suffix in model algebra - **** Use $onSuffixAlgebraVars to allow thisSee also related command line parameter SuffixAlgebraVars.
$(on|off)SymList ($offSymList)
Syntax:
$onSymList $offSymList
This option controls whether the symbol listing map appears in the compilation output of the listing file. The symbol listing map contains the complete listing of all symbols that have been defined and their explanatory text. The entries are in alphabetical order and grouped by symbol type.
Example:
The symbol listing map generated by running [TRNSPORT] with
$onSymList
is as follows:Symbol Listing 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 transportThis serves as a simple description of the symbols used in a model and may be used in reports and other documentation. For further information, see section The Symbol Listing Map.
$(on|off)SymXRef ($offSymXRef)
Syntax:
$onSymXRef $offSymXRef
This option controls the following:
- Collection of cross references for symbols like sets, parameters, variables, acronyms, equations, models and put files.
- Symbol cross reference report of all collected symbols in the compilation output of the listing file. For details, see section The Symbol Reference Map.
- Listing of all referenced symbols and their explanatory text by symbol type in listing file. This listing may also be activated with the option $onSymList.
Example:
$onSymXRef Set i / 1*6 /, k; $offSymXRef Set j(i) "will not show" / 1*3 /; $onSymXRef k('1') = yes;
The resulting listing file will contain the following symbol reference map and symbol listing map:
SYMBOL TYPE REFERENCES i SET declared 2 defined 2 k SET declared 2 assigned 6 SETS i kNote that the set
j
does not appear in these listings because the listing was deactivated with the option$offSymXRef
in line 3 of the code above.
Syntax:
$onText $offText
The pair
$onText
-$offText
encloses comment lines. Line numbers in the compiler listing are suppressed to mark skipped lines.Example:
* 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 echo print of the resulting listing file will contain the following lines:
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.See also section Comments.
Syntax:
$onTroll $offTroll
This option controls whether to recognize Troll periodicity in set definitions using sequences (
id*id
). Leap years are taken into account. Supported formats areyyyyA
(annual),yyyyQq
(quartely),yyyyMmm
(monthly) andyyyyWww
(weekly).Example:
$onTroll Set trollw / 1990w49*1991w4 / trollm / 1990m10*1991m5 / trollq / 1990q1*1991q4 / ; Display trollw, trollm, trollq;
The resulting listing file will contain the following output:
---- 25 SET trollw 1990W49, 1990W50, 1990W51, 1990W52, 1991W1 , 1991W2 , 1991W3 , 1991W4 ---- 25 SET trollm 1990M10, 1990M11, 1990M12, 1991M1 , 1991M2 , 1991M3 , 1991M4 , 1991M5 ---- 25 SET trollq 1990Q1, 1990Q2, 1990Q3, 1990Q4, 1991Q1, 1991Q2, 1991Q3, 1991Q4
$(on|off)UElList ($offUElList)
Syntax:
$onUElList $offUElList
This option controls the complete listing of all set elements that have been entered in the compilation output of the listing file. For details see section The Unique Element Listing Map.
Example:
The unique element listing in the listing file generated by running the model [TRNSPORT] with
$onUElList
follows:Unique Element Listing Unique Elements in Entry Order 1 seattle san-diego new-york chicago topeka Unique Elements in Sorted Order 1 chicago new-york san-diego seattle topekaNote that the sorted order is not the same as the entry order. For more information, see section Ordered and Unordered Sets.
$(on|off)UElXRef ($offUElXRef)
Syntax:
$onUElXRef $offUElXRef
This option controls the collection and listing of cross references of set elements in the compilation output. For more information, see section The Unique Element Listing Map.
Example:
Set i "set declaration" / one, two, three /, k(i); $onUElXRef k('one') = yes; $offUElXRef k('two') = yes; $onUElXRef k('three') = yes;
The resulting listing file will contain the following unique element reference report:
Unique Element Listing ELEMENT REFERENCES one index 3 three index 7Note that the element
two
does not appear in this listing because the listing was deactivated with the option$offUElXRef
in line 4 of the code above.
Syntax:
$onUNDF $offUNDF
This option controls the use of the special value UNDF which indicates a result is undefined. For details see section Extended Range Arithmetic. By default, UNDF is not permitted to be used in assignments. This may be changed with the option
$onUNDF
.Example:
Scalar x; $onUNDF x = UNDF; Display x;
The output of the display statement follows:
---- 4 PARAMETER x = UNDFNote that an error would have been triggered without the use of
$onUNDF
. The option$offUNDF
will return the system to the default, whereUNDF
may not be used in assignments.
Syntax:
$onUni $offUni
This controls whether the compiler checks the referential integrity (see section Domain Checking) of the code. This is an essential part of good GAMS programming and it is highly recommend to declare symbols with proper domains. With the universe as a domain the compiler does not help the user with easy-to-make mistakes, like swapping indexes,
a(i,j)
versusa(j,i)
. By default something like this would generate an error, ifa
was declared asa(i,j)
. Such an error could be ignored, by setting$onUni
, which can be useful in few situations, when accessing a symbol with a set that is not the domain or a subset of the domain. For example, we could read data of a union of sets that already exist. We could use the universe as the domain for that symbol, but perhaps we need to protect the referential integrity of this symbol too.Example:
Set fruit / apple, pear / veggie / carrot, pea / produce / #fruit, #veggie /; Parameter produceCalories(produce) "per 100g" / apple 52, pear 57, carrot 41, pea 81 / fc(fruit) "calories per 100g" vc(veggie) "calories per 100g"; $onUni fc(fruit) = produceCalories(fruit); vc(veggie) = produceCalories(veggie); $offUni display fc, vc;
So when assigning
fc
we only accessproduceCalories
withfruit
. We could reverse the order of declaration offruit
,veggie
andproduce
and use a proper subdomain, but sometimes data flow and input don't allow that.
- Attention
- When the GAMS compiler operates under $onUni it treats all symbols as being declared over the universe. So all domain checking is gone. We can set elements in a symbols that normally can't be entered. This can also lead to strange effects:
set i / 1*2 / j / a,b /; parameter pi(i); $onuni pi(j) = 1; $offuni * We will see elements from j in pi Display pi; * The following should only clear the i-elements from pi, but it clears the * entire symbol, because GAMS knows it's doing this to the entire domain and * takes a shortcut. pi(i) = no; Display pi;
Syntax:
$onVerbatim $offVerbatim
These options are used in conjunction with the GAMS command line parameter DumpOpt to suppress the input preprocessing for input lines that are copied to the dmp file. This feature is mainly used to maintain different versions of related models in a central environment.
- Note
- The options
$on/offVerbatim
are only recognized forDumpOpt
\(\geq\) 10 and apply only to lines in the file between the two options- If
$onVerbatim
is active,DumpOpt = 11
behaves likeDumpOpt = 21
(comments are kept)Observe that the use of the options $goto and
$on/offVerbatim
are incompatible and may produce unexpected results.Example:
$set f 123 $log %f% $onVerbatim $log %f% $offVerbatim $log %f%
The corresponding dmp file will contain the following lines:
$log 123 $onVerbatim $log %f% $offVerbatim $log 123
See also command line parameter DumpOpt.
$(on|off)Warning ($offWarning)
Syntax:
$onWarning $offWarning
This option acts as a 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, see example below.
- This may have serious side affects and we recommend to exercise great care when using this feature.
Example:
Set i / one, two, three / $onWarning j(i) / four, five / k / zero /; Parameter x(i) "Messed up Data" / one 1.0, five 2.0 /; x('six') = 6; x(j) = 10; x('two') = x('seven'); j(k) = yes; $offWarning display i,j,x;
Note that the set
j
, although specified as a subset ofi
, contains elements not belonging to its domain. Similarly, the parameterx
contains data elements outside the domain ofi
. The skeleton listing file that results from running this code follows:1 Set i / one, two, three /; 3 j(i) / four, five / **** $170 $170 4 k / zero /; 5 Parameter x(i) "Messed up Data" / one 1.0, five 2.0 /; **** $170 6 x('six') = 6; x(j) = 10; x('two') = x('seven'); **** $170 $116,170 7 j(k) = yes; **** $171 9 display i,j,x; Error Messages 116 Label is unknown 170 Domain violation for element 171 Domain violation for set **** 0 ERROR(S) 7 WARNING(S) E x e c u t i o n ---- 9 SET i one , two , three ---- 9 SET j four, five, zero ---- 9 PARAMETER x Messed up Data one 1.000, four 10.000, five 10.000, six 6.000Observe that the domain violations are marked like normal compilation errors but are only treated as warnings and it is permitted to execute the code.
For an introduction to domain checking in GAMS, see section Domain Checking.
Syntax:
$phantom id
This option is used to designate
id
as a phantom set element. Syntactically, a phantom element is handled like any other set element. Semantically, however, it is handled like it does not exist. This is sometimes used to specify a data template that initializes the phantom records to default values.Example:
$phantom null Set i / null / j / a, b, null /; display i,j;
The output generated by the display statement is shown below:
---- 4 SET i ( EMPTY ) ---- 4 SET j a, bNote that
null
does not appear in the listing file.
- Attention
- Statements that assign values to phantom labels are ignored.
Consider the following extension to the previous example:
Parameter p(j) / a 1, null 23 /; display p;
The output generated by the display statement is shown below:
---- 6 PARAMETER p a 1.000The system attribute system.empty is an implicitly defined phantom element. The following code works even without specifying
$phantom
:Set i / system.empty / j / a, b, system.empty /; display i,j;
Another way to specify empty data statements makes use of on/offEmpty. The following example produces the same data as the data statement with the phantom label. In contrast to the example we
$phantom
we need to provide the dimensionality of the symboli
explicitly via the(*)
:$onEmpty Set i(*) / / j / a, b /; display i,j;
Syntax:
$prefixPath directoryPath
This option augments the search path in
PATH
environment variable. The effect is that the textdirectoryPath
is added to the beginning of the search path.Example:
$log %sysenv.PATH% $prefixPath C:\somewhereelse\anotherpath $log %sysenv.PATH%
The log contains the following two relevant lines:
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0 C:\somewhereelse\anotherpath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0The option setEnv and
%sysEnv.VARNAME%
allow to modify system environment variables but the length of the environment variable value is limited in GAMS to 255 characters. ThePATH
environment variable is often much longer and therefore this special$prefixPath
option exists.This works on all platforms but the path separator depends on the operating system (
;
for Windows and:
for Unix).
Syntax:
$protect all | ident1 ident2 ...
This option creates a privacy setting: it freezes all values of identifiers with the result that modifications are no longer allowed but the parameters may still be used in model calculation (for example, equation definitions). Here
ident1
andident2
are specific GAMS identifiers previously defined in the program and the keywordall
denotes all identifiers.Note that this option is mainly used in the context of secure work files. The privacy restrictions may be removed with the options $expose or $purge.
Syntax:
$purge all | ident1 ident2 ...
This option removes the identifiers and all associated data in a privacy setting. With explicit identifiers the listed identifiers are removed, and with
all
all identifiers are removed.Note that this option is used in the context of secure work files. A special license file is needed for this feature to work, the removal only takes effect in the restart files.
Syntax:
$remark text
This option performs a parameter substitution and writes a comment
text
to the compilation output of the listing file. Note that the line numbers of the comment are suppressed.Example:
$set it TEST $remark Write %it% to the listing file
The resulting listing file will contain the following line:
Write TEST to the listing file
Syntax:
$[x]save[.keepCode] saveFileName
This option creates a work file with all of the GAMS components compiled up to this point. Without the suffix
keepCode
no execution code is written, hence a restart from this work file has nothing to execute.$xsave
writes a compressed work file, while work files created with$save
are uncompressed.Example:
set i /1*5/; parameter p(i) / #i 1 /; p(i) = 2; $save mywork $onEcho > create_put.gms file f / p.txt /; put f; loop(i, put i.tl p(i) /); $offEcho $call.checkErrorLevel gams create_put.gms lo=2 restart=mywork
The resulting file
p.txt
will contain the following lines:1 1.00 2 1.00 3 1.00 4 1.00 5 1.00
Adding the suffix .keepCode
in this example, i.e. $save.keepCode mywork
will also write out unexecuted execution code, so a restart from this work file will execute this code. This option with suffix cannot be used inside a loop or if statement. This will trigger a compilation error. The example with the .keepCode
suffix will result in the p.txt
file containing the following lines:
1 2.00 2 2.00 3 2.00 4 2.00 5 2.00
Syntax:
$scratchFileName VARNAME [fileStem]
This option establishes or redefines the content of a scoped compile-time variable that is accessible in the code where the command appears and all code included therein. Here
VARNAME
is any user chosen variable name;fileStem
is optional and used to built the name for a file in the scratch directory with a scratch extension (unless an extension is set explicitly). If it is omitted, the system will make up a random file name.So,
$scratchFileName fn abc
is equivalent to
$set fn %gams.scrDir%abc.%gams.scrExt%
Example:
* Set fileStem explicitly $scratchFileName fn1 abc $log %fn1% * Omit fileStem $scratchFileName fn2 $log %fn2%
The log will show:
C:\Data\t m p\225a\abc.dat C:\Data\t m p\225a\__sFN__-0_313342928588555.datSee also $set and section Compile-Time Variables.
Syntax:
$set VARNAME text
This option establishes or redefines contents of a scoped compile-time variable that is accessible in the code where the command appears and all code included therein. Here
VARNAME
is any user chosen variable name;text
is optional and may contain any text. The text may contain spaces. The text can not be longer than 255 characters otherwise a compilation error is triggered. Observe that scoped compile-time variables may be destroyed (removed from the program) with the option $drop.Note that in contrast to the option $eval the option
$set
does not evaluate the expression at compile time.Note that GAMS allows scoped, local and global compile-time variables to be defined with the same name and therefore in some cases needs to prioritize. When referencing a compile-time variable via
%VARNAME%
a local variable hides scoped and global variables and a scoped variables hides the global variable as the following example demonstrates.Example:
$setLocal myvar this is a local variable $set myvar this is a scoped variable $setGlobal myvar this is a global variable $log %myvar% $droplocal myvar $log %myvar% $drop myvar $log %myvar%
The log will look as follows:
this is a local variable this is a scoped variable this is a global variableIf one wants to set a compile-time variable in an include file that is visible to the program after the
$include
one need to use$setglobal
:$onEchoV > setvar.gms $setArgs varname varvalue $setglobal %varname% %varvalue% $offEcho $batInclude setvar MYVAR one $log %MYVAR%
The log will show
oneAn inventory of all defined compile-time variables and their type (local, scoped, and global) is available with the option $show.
See also $setGlobal, $setLocal, and section Compile-Time Variables.
Syntax:
$setArgs id1 id2 id3 ...
With this option parameters that may be substituted are defined as GAMS compile-time variables. Note that
$setArgs
may only be used in external files that are included with the option $batInclude, $libInclude, and $sysInclude.Example:
Scalar a /2/, b /4/, c /5/; $batInclude test3 a b c
The file
test3.gms
contains the following lines:Scalar x; x = %1 + %2 * %3 ; display x; $setArgs aa bb cc x = %aa% - %bb% * %cc% ; display x; x = %1 + %2 * %3 ; display x;
The option
$setArgs
allows the batInclude file to use the more descriptive compile-time variables%aa%
instead of%1
,%bb%
instead of%2
and%cc%
instead of%3
. Note that the use of%1
,%2
etc. is still allowed. The program listing looks as follows:1 Scalar a /2/, b /4/, c /5/; BATINCLUDE C:\Users\default\Documents\gamside\projdir\test3.gms 3 Scalar x; 4 x = a + b * c ; 5 display x; 7 x = a - b * c ; 8 display x; 9 x = a + b * c ; 10 display x;and the output generated by the display statements follows:
---- 5 PARAMETER x = 22.000 ---- 8 PARAMETER x = -18.000 ---- 10 PARAMETER x = 22.000See also $set, $batInclude.
Syntax:
$setComps perioddelimstring id1 id2 id3 ...
This option establishes or redefines compile-time variables so they contain the components of a period delimited string.
Here
perioddelimstring
is any period delimited string like the set specification of a multidimensional parameter,id1
is the name of a scoped compile-time variable that will contain the name of the set element in the first position,id2
is the name of a scoped compile-time variable that will contain the name of the set element in the second position andid3
is the name of a scoped compile-time variable that will contain the name of the set element in the third position. The items may be recombined back into the original filename string by using%id1%.%id2%.%id3%
.Example:
$setComps period.delim.string id1 id2 id3 $log id1=%id1% $log id2=%id2% $log id3=%id3% $set name %id1%.%id2%.%id3% $log name=%name%
The resulting log file will contain the following lines:
id1=period id2=delim id3=string name=period.delim.string"See also $set.
Syntax:
$setDDList.Cont id1 id2 ... $setDDList id3 id4 id5 ...
This option causes GAMS to look for misspelled or undefined double dash GAMS parameters.
Example: Consider the following example where three double dash GAMS parameters are defined on the command line:
> gams mymodel.gms --one=11 --two=22 --three=33 --four=44The corresponding GAMS file follows:
$log %one% $log %two% $setDDList three $log %three% $log %four%
Note that the option
$setDDList three
checks if all double dash parameters have been used so far except forthree
. An error is triggered becausefour
has not been used so far, the log file will contain the following:*** 1 double dash variables not referenced --four=44
$setDDList.Cont
can be used to define a list of parameters to be checked over multiple lines. So, the following two examples do the same thing:$setDDList one two three four
$setDDList.Cont one $setDDList.Cont two three $setDDList four
- Note
$setDDList.Cont
does not do anything without a$setDDList
statement.See also section Double Dash Parameters.
Syntax:
$setEnv VARNAME value
This option defines an operating system environment variable. Here
VARNAME
is a user chosen environment variable name andvalue
may contain text or a number. Note that system environment variables are destroyed (removed from the program) with the option $dropEnv or when GAMS terminates.Example:
$ondollar $set env this is very silly $log %env% $setenv verysilly %env% $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 sillySee also $dropEnv and section Environment Variables in GAMS.
Syntax:
$setGlobal VARNAME text
This option establishes or redefines contents of a global compile-time variable that is accessible in the code where the command appears and all code included therein and all parent files. Here
VARNAME
is any user chosen variable name;text
is optional and may contain any text. The text may contain spaces. The text can not be longer than 255 characters otherwise a compilation error is triggered. Observe that global compile-time variables may be destroyed (removed from the program) with the option $dropGlobal.The difference between local, scoped, and global compile-time variable is explained with the option $set.
See also $set, $setLocal, $dropGlobal and section Compile-Time Variables.
Syntax:
$setLocal VARNAME text
This option establishes or redefines contents of a local compile-time variable that is accessible only in the code module (source file) where it is defined. Here
VARNAME
is any user chosen variable name;text
is optional and may contain any text. The text may contain spaces. The text can not be longer than 255 characters otherwise a compilation error is triggered. Observe that local compile-time variables may be destroyed (removed from the program) with the option $dropLocal.The difference between local, scoped, and global compile-time variable is explained with the option $set.
See also $set, $setGlobal, $dropLocal and section Compile-Time Variables.
Syntax:
$setNames file filepath filename fileextension
This option establishes or redefines three scoped compile-time variables so they contain the drive subdirectory, filename and extension of a file named with full path. Here
file
is any filename,filepath
is the name of a scoped compile-time variable that will contain the name of the subdirectory where the file is located,filename
is the name of a scoped compile-time variable that will contain the root name of the file andfileextension
is the name of a scoped compile-time variable that will contain the extension of the file.Example:
$setNames "%gams.input%" filepath filename fileextension $set name %filepath%%filename%%fileextension% $log %name%
The log will show
C:\Users\default\Documents\gamside\projdir\ Untitled_1 .gms C:\Users\default\Documents\gamside\projdir\\Untitled_1.gmsNote that
file
is separated into its three components placingC:\Users\default\Documents\gamside\projdir\
intofilepath
,Untitled_1
intofilename
and.gms
intofileextension
. The three items may be recombined back into the original filename by using%filepath%%filename%%fileextension%
as shown in the example.If the file is missing a path, name, or extension the corresponding variable is defined but remains empty as demonstrated in the following example:
$onEchoV > showfileparts.gms $setNames "%1" filepath filename fileextension $log path=%filepath% $log name=%filename% $log ext=%fileextension% $offEcho $batInclude showfileparts "C:\tmp\" $batInclude showfileparts "Untitled_1" $batInclude showfileparts "Untitled_1.gms" $batInclude showfileparts "Untitled_1.gms.txt"
The log shows:
--- Untitled_1.gms(7) 2 Mb path=C:\tmp name= ext= --- .showfileparts.gms(4) 2 Mb --- Untitled_1.gms(8) 2 Mb path= name=Untitled_1 ext= --- .showfileparts.gms(4) 2 Mb --- Untitled_1.gms(9) 2 Mb path= name=Untitled_1 ext=.gms --- .showfileparts.gms(4) 2 Mb --- Untitled_1.gms(10) 2 Mb path= name=Untitled_1.gms ext=.txtNote that if a file contains multiple
.
the last one will be assigned to thefileextension
as shown in the example withUntitled_1.gms.txt
.
Syntax:
$shift
This option is similar to the command.com/cmd.exe shift operator (see [en.wikipedia.org/wiki/COMMAND.COM::Batch_file_commands] (https://en.wikipedia.org/wiki/COMMAND.COM#Batch_file_commands). It shifts the order of all parameters passed once to the left. This effectively drops the lowest numbered parameter in the list.
Example:
Scalar a, b, c ; a = 1 ; $batInclude inc.inc a b c display a, b, c ;
The batch include file
inc.inc
follows:%2 = %1 + 1 ; $shift %2 = %1 + 1 ;
The resulting listing file will contains the following echo print:
1 Scalar a, b, c ; a = 1 ; BATINCLUDE C:\Users\default\Documents\gamsdir\projdir\inc.inc 3 b = a + 1 ; 5 c = b + 1 ; 6 display a, b, c ;Note that in the first statement in the include file,
%1
is the first argument in the $batInclude call and in this case it is interpreted asa
.%2
is the second argument in the $batInclude call and is interpreted asb
. This leads to the overall assignment being interpreted asb=a+1
. The dollar control option$shift
shifts the arguments to the left. As a result,%1
is interpreted asb
, and%2
is interpreted asc
. This leads to the second assignment being interpreted asc=b+1
.Therefore the outcome generated by the display statement in the input file is as follows:
---- 6 PARAMETER a = 1.000 PARAMETER b = 2.000 PARAMETER c = 3.000See also $batInclude.
Syntax:
$show
This option causes current values of the compile-time variables plus a list of the macros and active input and include files to be shown in the compilation output, where "active" means, that
$show
was either directly in that file or that file is a parent that includes the file with$show
.Example:
$set it 1 $setLocal yy $setGlobal gg what $include myinclude $macro addx(x) x+x $show
The file
myinclude.gms
follows:$set inincs $setLocal inincsl $setGlobal inincsg $macro multx(x) x*x $show
The resulting listing file will contain the following environment reports in the compilation output:
---- Begin of Active File List Level Type Line Filename ---------------------------------- 1 INCLUDE 5 C:\Users\default\Documents\gamside\projdir\myinclude.gms 0 INPUT 4 C:\Users\default\Documents\gamside\projdir\Untitled_1.gms ---- End of Active File List ---- Begin of Compile-time Variable List Level SetVal Type Text ----------------------------------------------------- 1 inincsl LOCAL 1 inincs SCOPED 0 yy LOCAL 0 it SCOPED 1 0 gg GLOBAL what 0 inincsg GLOBAL ---- End of Compile-time Variable List ---- Begin of Macro List $macro multx(x) x*x ---- End of Macro Listand
---- Begin of Active File List Level Type Line Filename ---------------------------------- 0 INPUT 6 C:\Users\default\Documents\gamside\projdir\Untitled_1.gms ---- End of Active File List ---- Begin of Compile-time Variable List Level SetVal Type Text ----------------------------------------------------- 0 yy LOCAL 0 it SCOPED 1 0 gg GLOBAL what 0 inincsg GLOBAL ---- End of Compile-time Variable List ---- Begin of Macro List $macro multx(x) x*x $macro addx(x) x+x ---- End of Macro ListNote that only the macros and the item defined with the option $setGlobal in the included file carries over.
If one needs only parts of this report, the dollar control options $showFiles, $showMacros and $showVariables can be used.
See also section Compile-Time Variables.
Syntax:
$showFiles
This option prints the active files to the lst file as described at $show.
Syntax:
$showMacros
This option prints a list of macros to the lst file as described at $show.
Syntax:
$showVariables
This option prints a list current values of the compile-time variables to the lst file as described at $show.
Syntax:
$single
The lines following this option will be echoed single spaced in the compilation output. Note that this is the default. The option is only useful as a switch to deactivate the option $double.
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 echo print in the resulting listing file will look 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 options $double and
$single
are listed double spaced, while the lines after the option$single
revert back to being listed single spaced.See also $double.
Syntax:
$splitOption KEYVALPAIR optname optvalue
Establishes or redefines two scoped compile-time variables so they contain the name and value of an option key/value pair specified in various formats.
KEYVALPAIR
is a string formatted as-opt=val
or-opt val
(instead of-
one can also use/
).optname
is the name of a scoped compile-time variable that will contain the name of the option andoptvalue
is the name of a scoped compile-time variable that will contain the value of the option. This is useful in particular in combination with batInclude files.Example:
$onechoV > myinclude.gms * Default values for named arguments $setGlobal a1 1 $setGlobal a2 2 $setGlobal a3 nothing $setGlobal positionalArgs $label ProcessNamedArguments $ splitOption "%1" key val $ if x%key%==x $goto FinishProcessNamedArguments $ ifThenI.NamedArguments %key%==a1 $ setGlobal a1 %val% $ elseIfI.NamedArguments %key%==a2 $ setGlobal a2 %val% $ elseIfI.NamedArguments %key%==a3 $ setGlobal a3 %val% $ else.NamedArguments $ error Unkown named argument "%key%" $ endIf.NamedArguments $ shift $goTo ProcessNamedArguments $label FinishProcessNamedArguments $setGlobal positionalArgs %1 %2 %3 $offEcho $batInclude myinclude "-a3=some things" -a2=3.14 i j k $log Using named arguments a1:>%a1%< a2:>%a2%< a3:>%a3%< positionalArgs:>%positionalArgs%<
Now when calling this piece of code as a batInclude one can specify optionally some named arguments (in any order) right after the name of the batInclude file and before the positional arguments as demonstrated by the log output:
Using named arguments a1:>1< a2:>3.14< a3:>some things< positionalArgs:>i j k<
Syntax:
$stars char[char][char][char]
This option is used to redefine the **** marker in the GAMS listing file. By default, important lines like those that denote errors and the solver and model status are prefixed with ****. A new marker consists of one to four characters.
Example:
$stars *##* garbage
The resulting listing file follows:
2 garbage *##* $140 *##* $36,299 UNEXPECTED END OF FILE (1) Error Messages 36 '=' or '..' or ':=' or '$=' operator expected rest of statement ignored 140 Unknown symbol 299 Unexpected end of file
Syntax:
$sTitle text
This option sets the subtitle in the page header of the listing file to
text
. Note that the next output line will appear on a new page in the listing file.Example:
$sTitle Data tables for input/output
See also $title.
Syntax:
$stop [text]
This option stops program compilation without creating an error. Note there is a difference to the option $exit. If there is only one input file,
$stop
and$exit
will have the same effect. In an include file the option $exit acts like an end-of file on the include file. However, the option$stop
in an include file will cause GAMS to stop reading all input but continue the execution phase of the so far compiled program. The text followed by$stop
is ignored.Example:
$ifthen not set EXPORTEXCEL $ stop No export to Excel $else $ call gdxxrw ... $endif
See also $abort, $error, $exit, and $terminate.
The syntax of this dollar control option is equivalent to the syntax of $batinclude:
Syntax:
$sysinclude external_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. Note that the default directory may be reset with the command line parameter sysIncDir.
Example:
The only relevant include file in the GAMS system directory is
mpsgeset
for MPSGE models, see for example [HARMGE]:$sysInclude mpsgeset KAMIYA
Note that this call will first look for the include file
[GAMS System Directory]/mpsgeset
. If this file does not exist, it will looks for[GAMS System Directory]/mpsgeset.gms
. The argumentKAMIYA
is passed on to the include file and are interpreted as explained for the dollar control option $batInclude.Consider the following example:
$sysInclude C:\Users\default\Documents\mpsgeset KAMIYA
This call will first look specifically for the include file
C:\Users\default\Documents\mpsgeset
and next forC:\Users\default\Documents\mpsgeset.gms
.See also $batInclude.
Syntax:
$terminate [text]
This option terminates compilation and also does not execution to program compiled so far without giving an error.
Example:
$if set JUSTTERMINATE $terminate
Syntax:
$title text
This option sets the title in the page header of the listing file to
text
. Note that the next output line will appear on a new page in the listing file.Example:
$title Production Planning Model $sTitle Set Definitions
See also $sTitle.
Syntax:
$unLoad [sym1[,] sym2=gdxSym2[,] ...]
This option unloads specified items to a GDX file. Note that
$unLoad
must be used in conjunction with the option $gdxOut:$gdxOut
must precede `$unLoad`. More than one option$unload
may appear in between. Symbols can be renamed via thesym=GDXSym
syntax. A$unLoad
without arguments unloads the entire GAMS database into the GDX file.Example: Consider the following slice of code:
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 / b(j) 'demand at market j in cases' / new-york 325 chicago 300 topeka 275 / ; Table d(i,j) 'distance in thousands of miles' new-york chicago topeka seattle 2.5 1.7 1.8 san-diego 2.5 1.8 1.4 ; $gdxOut tran $unLoad i j=k $unLoad b=dem a=sup $unLoad d $gdxout tranX $unLoad
Note that the last lines will create a file named
tran.gdx
that containsi
,j
(now namedk
) andd
and the parametersa
andb
which are now nameddem
andsup
. The$unLoad
in the very last line creates a GDX filetranX.gdx
with all symbols (with their original names). The table of content (via$gdxIn
and$load
without parameters) of these two files looks as follows:Content of GDX C:\Users\default\Documents\gamsdir\projdir\tran.gdx 5 UELs Number Type Dim Count Name 1 Set 1 2 i canning plants 2 Set 1 3 k markets 3 Parameter 1 3 dem(j) demand at market j in cases 4 Parameter 1 2 sup(i) capacity of plant i in cases 5 Parameter 2 6 d(i,j) distance in thousands of miles Content of GDX C:\Users\default\Documents\gamsdir\projdir\tranX.gdx 5 UELs Number Type Dim Count Name 1 Set 1 2 i canning plants 2 Set 1 3 j markets 3 Parameter 1 2 a(i) capacity of plant i in cases 4 Parameter 1 3 b(j) demand at market j in cases 5 Parameter 2 6 d(i,j) distance in thousands of milesBoth listings show domain information for the various symbols but only the file
tranX.gdx
created with$unLoad
without arguments has consistent or full domain information whiletran.gdx
may have inconsistent or relaxed domain information. Domain matching when loading with the$load sym<[=]symGDX
, see $load for details, can be used in both cases but can become subtle with the relaxed domain information fromtran.gdx
.Starting with GAMS 34 the behavior of
$gdxOut
and$unload
changed compare to previous versions. In order to write consistent domain information and write aliases as such, the actual writing of the symbols to GDX is delayed until the GDX files is about to be closed either through an explicit$gdxOut
(potentially with a another filename) or through the end of the compilation phase. The advantage of the delayed writing is that the compiler can now better analyze the symbols and e.g. write alias symbols as aliases with the aliased set is also written to the GDX file (aliases were always written as sets before GAMS 34).This new behavior can result in different GDX files. Here are two examples:
Set i /1,2,3/; Parameter p(i); $gdxOut x.gdx $unload Parameter p(i) /1 1, 2 2, 3 3/;
In the GAMS versions before 34 the export GDX happened when the compiler processed the
$unload
command. At this point the parameterp
did not have any data yet, so the GDX symbolp
had no records. With the new behavior, the actual writing happens when the GDX file will be closed. Since there is no explicit close via a$gdxOut
the GDX file is closed at the end of the compilation phase. By then the compiler has processed the statementParameter p(i) /1 1, 2 2, 3 3/;
and has filledp
with data that will show up in the GDX file. In such a case an explicit$gdxOut
after the$unload
helps to get the old behavior back.Set i /1,2,3/; Parameter p(i) / 1 1/; $gdxOut x.gdx $unload p=p1 $onmulti Parameter p(i) / 2 2/; $unload p=p2
In the GAMS versions before 34 the GDX file
x.gdx
contains two parametersp1
with record1 1
andp2
with record1 1, 2 2
. With the new behavior the symbols are written again at the end of the compilation phase and by then the parameterp
has the records1 1, 2 2
and will write to GDX the parametersp1
andp2
with the two records each. The only way to accomplish the old behavior in this case is to writep1
andp2
to different GDX files:Set i /1,2,3/; Parameter p(i) / 1 1/; $gdxOut x1.gdx $unload p=p1 $gdxOut x2.gdx $onMulti Parameter p(i) / 2 2/; $unload p=p2
This delayed writing also influence other options like $onEpsToZero. The state of this becomes relevant when the file is actually written, not when a symbol is added to the list of symbols to be exported with
$unload
. This can be seen in the following example:Set i / i1*i3 /; Parameter p1(i) / i1 0, i2 EPS, i3 1 / p2(i) / i1 0, i2 EPS, i3 1 /; $gdxOut out.gdx $onEpsToZero $unload p1 $offEpsToZero $unload p2 $gdxOut $call.checkErrorLevel gdxdump out.gdx
Here is the output from
gdxdump
at the end:Parameter p1(*) / 'i2' Eps, 'i3' 1 /; Parameter p2(*) / 'i2' Eps, 'i3' 1 /;
Syntax:
$use205
This option sets the GAMS syntax to the syntax 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 to run such models.
Example:
$use205 Set if /1.2.3/; Scalar x ;
The word "if" is a keyword in GAMS that was introduced with the first version of Release 2.25. Setting option
$use205
allows "if" to be used as an identifier since it was not a keyword in Release 2.05.
Syntax:
$use225
This option sets the GAMS syntax to the syntax of the 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 to run such models.
Example:
$use225 Set for /1.2.3/; Scalar x ;
The word "for" is a keyword in GAMS that was introduced with the later versions of Release 2.25. Setting option
$use225
allows "for" to be used as an identifier since it was not a keyword in the first version of Release 2.25.
Syntax:
$use999
This option sets the GAMS syntax to the syntax of the latest version of the compiler. Note that this setting is the default.
Example:
$use225 Set for /1.2.3/; Scalar x ; $use999 for (x=1 to 3, display x) ;
Note that the word "for" is used as a set identifier after setting the option
$use225
and later the keywordfor
is used in a looping construct after having set the language syntax to that of the latest version using the option$use999
.
Syntax:
$version n
This issues a compilation error if
n
is greater than the current GAMS version. This can be useful to ensure that a model is run only with new versions of GAMS, because, e.g., a particular feature which did not exist in older versions is needed.Example:
* With GAMS 24.8.1 the function numCores was added to the system. * Make sure, that we use this GAMS version or newer. $version 248 Scalar nc "Number of cores"; nc = numCores; Display nc;
Syntax:
$warning text
This dollar control option issues a compilation warning to the log and listing but continues compilation and execution.
Example
$ifthen not set INPUTFILE $ set INPUTFILE default.txt $ warning Using default INPUTFILE "default.txt". Use --INPUTFILE=myfile.txt to overwrite default. $endif
The GAMS log file will issue a warning:
*** Error 332 in C:\Users\default\Documents\gamsdir\projdir\myinput.gms $Warning encountered - see listing for detailswith the details in the listing file:
3 $ warning Using default INPUTFILE "default.txt". Use --INPUTFILE=myfile.txt to overwrite default. **** $332
Conditional Compilation
GAMS offers several dollar control options that facilitate conditional compilation. In this section we will first introduce the general syntax, present an overview of all relevant options and list the conditional expressions that may be used to perform tests. Then we will give several examples to illustrate how these options are used and to demonstrate their power. This section is meant as an introduction to conditional compilation in GAMS and complements the detailed descriptions of the dollar control options listed in Table 1 below.
Conditional Compilation: General Syntax and Overviews
The dollar control option $if
and its variants provide a great amount of control over conditional processing of the input file(s). The syntax in GAMS is similar to the IF
statement of the DOS Batch language:
$if [not] <conditional expression> new_input_line
The dollar control statement begins with $if
. Note that $if
may be replaced by one of its variants that are listed in Table 1 below. The operator not
is optional and makes it possible to negate the conditional
expression
that follows. The conditional expression may take various forms, a complete list is given in Table 2. The result of the conditional test is used to determine whether to process or not the remainder of the line, new_input_line
, which may 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 the dollar control character, the line is treated as a dollar control line. Likewise, if the first character encountered is a comment character (default:
*
) the remainder of the line is treated as a comment line. If a multiplication is to be performed in the true clause instead of a comment, the $ifThen condition needs to be used:$setglobal mult on Scalar P_test; P_test = 10 $iftheni %mult%==on * 5 $endif ;
Alternatively, the new_input_line
may be placed in the next line. The corresponding syntax follows:
$if [not] <conditional expression>
new_input_line
Note that in this version the space after the conditional expression is left blank. If the conditional is found to be false, either the remainder of the line (if any) will be skipped or the next line will not be processed.
The overviews in Table1 and Table 2 conclude this subsection. Examples are given in the next subsection.
Table 1: $if
and Related Dollar Control Options
Dollar Control Option | Description |
---|---|
$if | This option is used to do case sensitive comparisons. Several examples are given in the next subsection. |
$ifE | This variant does the same as $if but allows numerical constant expression evaluation. For an example, see the detailed description of this option. |
$ifI | This variant is the same as $if, but it is case insensitive. |
$ifThen | This variant controls whether a block of statements will be processed or not. It is used to do case sensitive comparisons. Most often it is followed by one or more of the following dollar control options: $else, $elseIf, $elseIfI, $elseIfE. The option $ifThen must be matched with the option $endIf that marks the end of the block. An example is given below. |
$ifThenE | This is a variant of $ifThen and is used for numerical comparisons. Like $ifThen , it is often followed by the option $else or one of its variants and must be matched with the option $endIf that marks the end of the construct. |
$ifThenI | This is a variant of $ifThen and is used to do case insensitive comparisons. Like $ifThen , it is often followed by the option $else or one of its variants and must be matched with the option $endIf that marks the end of the construct. |
$endIf | This option must be matched with a preceding option $ifThen, $ifThenE or $ifThenI and marks the end of the if - then construct. Note that the option $endIf is not followed by a conditional expression, but it may be follwowed by a new_input_line . This GAMS input is restricted to other dollar control statements. An example is given below. |
$else | This option follows the option $ifThen, $ifThenE or $ifThenI. It is followed by an instruction which is executed if the conditional expression of the matchining $ifThen statement is not true. Note that therefore this dollar control statement does not contain a conditional expression. An example is given below. |
$elseIf | This option follows the option $ifThen, $ifThenE or $ifThenI. It is follwed by another conditional expression and instruction. Note that this option is case sensitive. An example is given below. |
$elseIfE | This is a variant of $elseIf that evaluates numerical values. |
$elseIfI | This is a variant of $elseIf that is case insensitive. |
Table 2: Conditional Expressions in Conditional Compilation
Conditional Expression | Description |
---|---|
acrType id | True if id is an acronym. |
decla_OK | True if a declaration statement is permitted in the current line. Note that declaration statements are not permitted within programming flow control structures like if statements or loop statements. An example is given below. |
declared id | True if id was declared. |
defined id | True if id was defined. An example is given below. |
dExist directoryname | True if a directory with the name directoryname exists. |
dimension n id | True if id has n dimensions. Note that n may take values from 0 to maximum number of possible indexes (see Dimensions). |
empty restOfLine | True only if restOfLine is an empty string (not even "" nor '' ), otherwise False. |
equType id | True if id is an equation. |
errorFree | True if compilation up to this point has been free of errors. |
errorLevel n | True if the return code of a program called via $call is equal to or larger than n . For lists of GAMS return codes, see chapter GAMS Return Codes. An example is given below. |
exist filename | True if a file with the name filename exists and is readable in the working directory or an input file directory. If no extension is specified, also filename.gms is checked. An example is given below. |
filType id | True if id is the name of a put file. |
funType id | True if id is a GAMS function. |
gamsVersion n | True if current GAMS version is greater than or equal to n . GAMS versions are referenced with a single number. For example, if it should be tested whether the current GAMS version is 24.7 or newer, n will equal 247 . Maintenance version numbers, e.g. 24.7.4 do not count. |
gdxDimension n id | True if id exists in a GDX file previously opened with $gdxIn and has n dimensions. Note that n may take values from 0 to maximum number of possible indexes (see Dimensions). |
gdxEquType id | True if id exists in a GDX file previously opened with $gdxIn and is an equation. |
gdxParType id | True if id exists in a GDX file previously opened with $gdxIn and is a parameter. |
gdxSetType id | True if id exists in a GDX file previously opened with $gdxIn and is a set. |
gdxSymExist id | True if id exists in a GDX file previously opened with $gdxIn. |
gdxVarType id | True if id exists in a GDX file previously opened with $gdxIn and is a variable. |
macType id | True if id is a macro. |
modType id | True if id is a model. |
onState key | True if the state of key is on (i.e. activated by $onKey ). An example is given below. |
parType id | True if id is a parameter. |
preType id | True if id is a one of the predefined symbols in GAMS. Details are given below. |
putOpen | True if both a file statement and at least one put statement have been compiled. Note that this does not guarantee that a file will be open at runtime. |
readable id | True if id was correctly initialized, i.e. the symbol has a data statement or appeared on the left-hand side of an assignment statement, and may therefore be used on the right-hand side of an assignment statement. An example is given below. |
set varname | True if the scoped compile-time variable varname was set with the dollar control option $set, $setGlobal or $setLocal. |
setEnv varname | True if the environment variable varname was set in the systems environment, e.g. with the dollar control option $setEnv. |
setGlobal varname | True if the control variable varname was set with the dollar control option $setGlobal. |
setLocal var_name | True if the control variable var_name was set with the dollar control option $setLocal. |
setType id | True if id is a set. |
solver solver_name | True if a solver named solver_name exists in the GAMS system. An example is given below. |
uelExist id | True if unique element id exists in current GAMS database. |
varType id | True if id is a variable. |
warnings | True if the compilation until this point has been free of warnings. |
xxxType id | True if id is an unknown type. For more information, see below. |
string1 == string2 | True only if string1 matches string2 exactly. Note that the strings may be quoted or unquoted. Null (empty) strings may be indicated by an empty quote: "" or '' . The case of the strings provided either explicitly or, more likely, through a parameter substitution, is preserved and therefore will affect the string comparison. Quoted strings with leading and trailing blanks are not trimmed and the blanks are considered part of the string. Note that the string may have the form %VARNAME% , where VARNAME refers to a compile-time variable including GAMS command line parameters and system attribute. An example for a string comparison with a command line parameter is given below. An example for a string comparison with a system attribute is given below. |
string | True only if string is an empty string ("" or '' ), otherwise False. |
Conditional Compilation: Examples
File Operation Test
The operator exist
may be used to test whether a given file name exists. Consider the following example:
$if exist myfile.dat $include myfile.dat
Observe that the effect of this dollar control statement is that the file myfile.dat
is included if it exists. Note that the character $
at the beginning of the option $include is the first non-blank character after the conditional expression exist myfile.dat
and therefore it is treated as the first column position. The statement above may also be written as follows:
$if exist myfile.dat
$include myfile.dat
Conditional Compilation and Batch Include Files
In the next example we will illustrate how the option $if
is used inside a batch include file where parameters are passed through the option $batInclude from the parent file:
$if not "%1a" == a $goto labelname
$if exist %1 file.ap=1;
Note that in the first line the $if
condition uses the string comparison "%1a" == a
to check if the parameter is empty. This test may also be done in the following way: %1 == ""
. If the parameter is not empty, the option $goto is processed.
- Note
- The option $label cannot be part of the conditional input line. However, if the option $label appears on the next line, the condition decides once if the label is placed or not and subsequent instances of
$goto
will find the label without reevaluating the condition.
The second line illustrates the use of standard GAMS statements if the conditional expression is valid. If the file name passed as a parameter through the $batInclude call exists already, the GAMS will execute the file.ap=1;
statement which will append to the file.
The next example demonstrates how an unknown number of file specifications may 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.gms
* include and process an unknown number of input files
$label nextfile
* Quote everything because file name might have blanks
$if exist "%1" $include "%1"
$shift
$if not "%1a" == a $goto nextfile
The call to this file in the parent file could take the following form:
$batInclude inclproc "file 1.inc" file2.inc file3.inc file4.inc
Testing Whether an Item Has Been Defined
The next example shows how to test if a named item was declared and/or defined.
Set i;
$if defined i $log First: set i is defined
$if declared i $log First: set i is declared
Set i /seattle/;
$if defined i $log Second: set i is defined
$if declared i $log Second: set i is declared
Note that after the first declaration of i
only declared i
evaluates to true when after the second declaration with a data statement both defined i
and declared i
are true.
Testing the state of a flag set by a dollar control option
The expression onState key
tests whether the state of key
is on
. So the following example could be done with any key
available as a $(on|off)Key
dollar control option:
$if onState listing $log Listing is active at checkpoint 1
$if onState listing $set reactivateListing
$offListing
* Do something which should not be seen in the listing
$if onState listing $log Listing is active at checkpoint 2
* Reactivate listing if it was active at the start only
$if set reactivateListing $onListing
$if onState listing $log Listing is active at checkpoint 3
Testing Whether an Item May Be Used in an Assignment
The expression readable id
tests whether data were assigned to an item and therefore the item may be used on the right-hand side of an assignment statement. Consider the following example:
Scalar f;
$if not readable f $log f cannot be used on the right
Scalar f /1/;
$if readable f $log f can be used on the right
$kill f
$if not readable f $log f cannot be used on the right after clear
f = 1;
$if readable f $log f can be used on the right after assignment
Note that in the first test the set f
was declared, but there was no data statement, hence it is not readable
. After a declaration with a data statement the test readable f
evaluates to TRUE
. With $kill we can revert f
to a data less state and hence not readable f
is TRUE
after the "$kill". The assignment statement f = 1;
make the scalar f
readable again.
Testing Whether an Identifier May Be Declared
In programming flow control structures, like if statements or loop statements declaration statements are not permitted. The test decla_ok
may be used to test whether the current environment allows declaration statements. Consider the following example:
$if decla_ok $log declarations are possible
if(1,
$ if not decla_ok $log declarations are not allowed
);
Note that the conditional expression in the both $if
tests will evaluate to TRUE
. However, the second test of decla_ok
itself will be FALSE
because it is processed while compiling an if
statement, but with the not
the entire expression evaluated to TRUE
. For more information, see chapter Programming Flow Control Features.
Comments in the Context of Conditional Compilation
In-line and end-of-line comments are stripped out of the input file before processing the new_input_line
. If either of these forms of comments appear, they will be treated as blanks. Consider the following example:
Parameter a ;
a=10 ;
$eolCom // inlineCom /* */
$if exist myfile.dat /* in line comments */ // end of line comments
a = 4 ;
display a;
Note that the comments on line 3 are ignored and the fourth line with the assignment statement will be processed if the conditional expression is true Hence the outcome generated by the display statement will list a
with a value of 4 if the file myfile.dat
exists and a value of 10 if the file does not exist.
Error Level Test
Consider the following example:
$call gams mymodel.gms lo=2
$if errorlevel 1 $abort one or more errors encountered
Note that the errorlevel is retrieved from the previous system call via $call. The conditional statement errorlevel 1
is true if the returned errorlevel is equal to or larger than 1. In case of calling GAMS this means that something was not quite right with the execution of GAMS (either a compilation or execution error or other more exotic errors, see GAMS return codes. If this is the case, this GAMS program will be aborted immediately at compilation time.
Usually programs return 0 on success and non-zero on failure. The $if errorlevel 1
checks for strictly positive return codes. There are rare cases with failures and negative return codes (e.g. on Windows if some DLL dependencies of the program can't be resolved). In such a case $if errorlevel 1
will evaluate to false and not continue with the $abort
instruction. It might be better to access the program return code via the errorLevel function in the following way:
$call gams mymodel.gms lo=2
$ifE errorLevel<>0 $abort one or more errors encountered
Solver Test
The following example illustrates how to check if a solver exists.
$if solver ZOOM
Note that the conditional expression is false since the solver named ZOOM
does not exists in the GAMS system (anymore).
Command Line Parameters in String Comparison Tests
Assume we include the following dollar control statements in a GAMS file called myfile.gms
:
$if not '%gams.ps%'=='' $log Page size set to %gams.ps%
$if not '%gams.pw%'=='' $log Page width set to %gams.pw%
$if not '%gams.mip%'=='' $log MIP solver default is %gams.mip%
Then we run the program with the following call:
> gams myfile pageSize=60 pageWidth=85 mip=cbc
Note that we specified values for the command line parameters pageSize, pageWidth, and MIP. We can either use the short or long name on the command line and in the compile-time variable. If we do not specify the option on the command line we will get the default value for option page size and page width. The MIP solver line will not show because %gams.mip%
remains empty. The log with option setting on the command line will include the following lines:
Page size set to 60 Page width set to 85 MIP solver default is cbc
Command line parameters are introduced in chapter The GAMS Call and Command Line Parameters.
System Attributes in String Comparison Tests
Compile-time system attributes may also be used in string comparison tests. The system attribute that is most useful in this context is .fileSys. It identifies the name of the operating system being used. Consider the following example:
$ifthen not %gams.logOption%==3
$ ifi %system.fileSys%==UNIX $set nullFile > /dev/null
$ ifi %system.fileSys%==MSNT $set nullFile > nul
$ if not set nullFile $abort %system.fileSys% not recognized
$else
$ set nullFile
$endif
$call gamslib trnsport %nullFile%
These dollar control statements allow the definition of a NULL file destination that is dependent on the operating system that is being used. Note that the control variable nullFile
contains an operating-system-dependent name. This is useful when making an external program that writes to STDOUT quiet in case the GAMS log does not go to STDOUT (logOption=3). This example could also have used the system attribute %system.nullFile%
which contains the operating-system-dependent NULL file destination:
$set nullFile
$if not %gams.logOption%==3 $set nullfile > %system.nullFile%
$call gamslib trnsport %nullfile%
System attributes in general are introduced in chapter System Attributes.
Conditional Compilation with $ifThen and $else
Consider the following example which illustrates the use of $ifThen
, $elseIf
, $else
and $endif
:
$set x a
$label test
$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 test
Note that the resulting log file will contain the following lines:
$ifthen with x=a $elseif 2 with x=c $elseif 1 with x=b $else with x=k
Observe that the options $else
and $endIf
are not followed by conditional expressions and the instruction following the option $endIf
contains a dollar control statement. Moreover, note that the ‘$set x 'c’has the text to be set in quotes. GAMS needs to know where the text ends and the next dollar control option (in this case
$log`) starts.
Type of Identifiers
The type of a symbol can be retrieved via $if ...Type
. Consider the following example:
Set diag / 1*3 /;
Parameter p(diag) / 1 1, 2 4, 3 8 /;
$if setType diag $log diag is a set
$if not varType diag $log diag is not a variable
$if preType diag $log diag is a predefined type
$if parType p $log p is a parameter
$if setType sameAs $log sameAs is a set
$if preType sameAs $log sameAs is a predefined type
Note that for predefined symbols more than one type applies (e.g. sameAs
is of set and predefined type). Please also note that diag
is a set even though there is a predefined symbol named diag
but that becomes invisible with a user defined symbol with the same name.
Normally there is no way to get a symbol into the GAMS symbols table without a proper type. However, if the dollar command line parameter multiPass is set to a value larger than zero, then the compiler will just check for some integrity and will try to deduce the symbol type from the context. If it is not able to do so, the symbol type will remain unknown. For example, compiling the following lines with multiPass=1
display x;
$if xxxType x $log x is of unknown type
result in the line x is of unknown type
in the GAMS log.
Macros in GAMS
Macros are widely used in computer science to define and automate structured text replacements. The GAMS macro processors function similarly to the popular C/C++ macro preprocessor. Note that the GAMS macro facility has been inspired by the [GAMS-F] (http://www.mpsge.org/inclib/gams-f.htm) preprocessor for function definition developed by Michael Ferris, Tom Rutherford and Collin Starkweather, 1998 and 2005. The GAMS macro facility incorporates the major features of the GAMS-F preprocessor into the standard GAMS release as of version 22.9. GAMS macros act like a standard macro when defined. However, their recognition for expansion is GAMS syntax driven.
Syntax and Simple Examples
The definition of a macro in GAMS takes the following form:
$macro name macro_body
$macro name(arg1,arg2,arg3,...) macro_body with tokens arg1, ...
The dollar symbol $
followed by macro
indicate that this line is a macro definition. The name of the macro has to be unique, similar to other GAMS identifiers like sets and parameters. The macro name is immediately followed by a list of replacement arguments arg1,arg2,arg3,...
that are enclosed in parentheses. The macro body is not further analyzed after removing leading and trailing spaces.
The recognition and following expansion of macros is directed by GAMS syntax. The tokens in the macro body to be replaced by the actual macro arguments follow the standard GAMS identifier conventions. Consider the following simple example of a macro with one argument:
$macro reciprocal(y) 1/y
Here the name of the macro is reciprocal
, y
is the argument and the macro body is 1/y
. This macro may be called in GAMS statements as follows:
$macro reciprocal(y) 1/y
scalar z, x1 /2/, x2 /3/;
z = reciprocal(x1) + reciprocal(x2);
As GAMS recognizes reciprocal(x1)
and reciprocal(x2)
as macros, the assignment statement will expand to:
z = 1/x1 + 1/x2;
Note that the macro use cannot be spread over multiple lines. Single line use with more complex arguments as in
z = reciprocal(x1+x2);
is recognized and will expanded to:
z = 1/x1+x2;
Note that z
will be equal to 3.5 in this example as division takes precedence over addition. But breaking the argument of the macro over multiple lines as follows will trigger a macro expansion error:
z = reciprocal(x1
+x2);
The next example illustrates macros with multiple arguments:
$macro ratio(x,y) x/y
scalar z, x1 /2/, x2 /3/;
z = ratio(x1,x2);
The assignment above will expand to:
z= x1/x2;
Note that the macro definition may extend over several lines with the symbol '\
' acting as a continuation string. Consider the following example:
$macro myxor(a,b) (a or b) \
and (not a or not b)
scalar z;
z = myxor(1,0);
display z;
The z
assignment expands to
z = (x1 or x2) and (not x1 or not x2);
Note that although the macro has been defined over two lines, the expansion happens by combining the lines after stripping leading white spaces of the second line as demonstrated in the next example (because and
has a higher precedence than or
we can omit the parenthesis):
$macro myxor(a,b) not a and b \
or a and not b
scalar z;
z = myxor(1,0);
display z;
The z
assignment expands to this:
z = not 1 and 0 or 1 and not 0;
The &
, explained in more detail in the next section can be used to preserve (some of the) leading white spaces (but not the line breaks) if that is desired:
$macro myxor(a,b) not a and b \
& or a and not b
Nested Macros
Macros may be nested. Consider the following example:
$macro product(a,b) a*b
$macro addup(i,x,z) sum(i,product(x(i),z))
set j /j1*j10/;
Parameter a1(j) / #j 1 /, z, x1 /5/;
z = addup(j,a1,x1);
Observe that the macro product
is nested in the macro addup
. The assignment will expand to:
z = sum(j,a1(j)*x1);
Note that nested macros may result in an expansion of infinite length. An example follows.
$macro a b,a
display a;
This will expand into:
display b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,...
In such a case GAMS will eventually refuse to do more substitutions and will issue a compilation error:
732 Too many edits on one single line - possible recursion in macro calls compilation will be terminated
Ampersands in Macro Definitions
The expansion of arguments may be more carefully controlled by the use of ampersands &
in the macro body. A single ampersand &
is used as a concatenation or separation symbol to indicate tokens that are to be replaced. Consider the following example:
$macro f(i) sum(j, x(i,j))
$macro equ(q) equation equ_&q; \
equ_&q.. q =e= 0;
set i /i/, j /j/;
variable x(i,j);
equ(f(i))
This will expand into:
equation equ_f(i);equ_f(i).. sum(j, x(i,j)) =e= 0;
Note that without the ampersand notation, GAMS would have recognized only the third occurrence of q
and hence the expansion would have been:
equation equ_q;equ_q.. sum(j, x(i,j)) =e= 0;
Two ampersands &&
immediately preceding a token will drop the most outer matching single or double quotes of the replacement argument. This makes it possible to include expressions with spaces, commas and unbalanced parentheses. The latter one is something users should really avoid doing. An example follows.
$macro d(q) display &&q;
$macro ss(q) &&q)
set i /i/, k /k/;
parameter a1(i) / i 1/, z;
d('"here it is" , i,k')
d('"(zz"')
z=ss('sum(i,a1(i)');
z=ss('prod(i,a1(i)');
Note that the expressions d
contain quotes, spaces and commas and the expression ss
has unbalanced parentheses within the quoted parts. In turn these expand to become:
display "here it is" , i,k;
display "(zz";
z=sum(i,a1(i));
z=prod(i,a1(i));
Additional Macro Features
Deeply nested macros may require aliased sets in indexed operations like sum
and prod
. A minor syntax extension allows the implicit use of aliases. The suffix .local
on a controlling set will use an implicit alias within the scope of the indexed operation. Consider the following example:
$macro ratio(a,b) a/b
$macro total(q) sum(i,q(i))
set i /i1*i15/;
parameter a(i) / #i 1 /, b(i) / #i 2 /, r(i), asum;
asum = total(a);
r(i) = ratio(total(a), b(i));
The assignment statement will expand to:
asum = sum(i,a(i));
r(i) = sum(i,a(i))/b(i);
The second line will not compile because the i
in the sum is already controlled from the i
on the left. The intention was the total
macro is to add up the elements of a parameter indexed over i
. As in the r(i)
assignment the macro might be used in a statement where i
is already controlled hence when doing the sum
in the macro we want to use an alias of i
. If we change the macro definition to
$macro total(q) sum(i.local,q(i))
The code works as expected because the i
in the sum refers to the i.local
and not the outside i
.
Note that the the modifier .local
is not limited to macros and may be used in any context. For further details and more examples, see the detailed description of the dollar command option $on/offLocal.
Another feature of macros is the implicit use of the suffix .L
in report writing and other data manipulation statements. This allows using the same algebra in model definitions and assignment statements. The following code illustrates this feature:
$macro sumIt(i,term) sum(i,term)
cost .. z =e= sumIt((i,j), (c(i,j)*x(i,j))) ;
supply(i) .. sumIt(j, x(i,j)) =l= a(i) ;
demand(j) .. sumIt(i, x(i,j)) =g= b(j) ;
Model transport /all/ ;
solve transport using lp minimizing z ;
Parameter tsupply(i) total demand for report
tdemand(j) total demand for report;
$onDotL
tsupply(i)=sumIt(j, x(i,j));
tdemand(j)=sumIt(i, x(i,j));
The option $onDotL enables the implicit suffix .L
for variables. This feature was introduced for macros with variables to be used in equation definitions as well as assignment statements. The matching option $offDotL will disable this feature. Similarly, $offDotScale will access the .scale
suffix of a variable or equation in an assignment statement.
Three more switches are relevant to macros. The option $show will list any GAMS macros defined. The option $on/$offMacro will enable or disable the expansion of macros; the default is $onMacro
. Finally, the option $on/offExpand will change the processing of macros appearing in the arguments of a macro call. The default operation is not to expand macros in the arguments. The switch $onExpand
enables the recognition and expansion of macros in the macro argument list. The option $offExpand
will restore the default behavior.
Note that macro definitions are preserved in a save/restart file and are available again for a continued compilation.
Summarizing, macros shares the name space of GAMS symbols, like sets, parameters, variables, etc. Macros are recognized and expanded anywhere a proper GAMS identifier may be used. This may be suppressed with the option $on/offMacro. The body of macros is only used during expansion. Hence, macro definitions are not order dependent. Variables in macro bodies will have an implicit suffix .L
when they are used in assignment statements. This GAMS feature needs to be activated with the option $onDotL.
Compressing and Decompressing Files
GAMS provides two dollar control options for compressing and decompressing GAMS input files:
Dollar Control Option | Description |
---|---|
$compress <source> <target> | The file source is compressed into the packed file target . |
$decompress <source> <target> | The compressed file source is decompressed into the unpacked file target . |
- Attention
- Spaces are interpreted as separators between the source and target file names, hence quotes (single or double) have to be used if the file names contain spaces.
Note that GAMS will recognize whether a file is compressed and will processes it accordingly.
- Note
- Like any other GAMS input files, all compressed files are platform-independent.
Compressing and Decompressing Files: A Simple Example
We use the well-known transportation model [TRNSPORT] to illustrate. First we copy the model from the GAMS Model Library and then we create a compressed version of the original:
> gamslib trnsport > echo $compress trnsport.gms t1.gms > t2.gms > gams t2
Alternatively, the following code snippet may be used from within a GAMS file:
$call 'gamslib trnsport'
$compress trnsport.gms t1.gms
$include t1.gms
Note that the compressed input file t1.gms
can be treated like any other GAMS input file. If it is executed, the listing file will be identical to the listing file of the original input file trnsport.gms
, since a decompressed input is reported in the echo print. As usual, the parts of the model that are marked with the dollar control option $on/offListing will not appear in the echo print.
The compressed file t1.gms
can be decompressed as follows:
> echo $decompress t1.gms. t3.gms > t4.gms > gams t4
Alternatively, from within a GAMS file:
$decompress t1.gms t3.gms
Observe that the decompressed file t3.gms
is identical to the original file trnsport.gms
. This can easily be tested with the following command:
> diff trnsport.gms t3.gms
Compressing and Decompressing Files: The Model CEFILES
The following more elaborate example is self-explanatory. It is adapted from model [CEFILES] and can easily be modified to test the use of compressed files.
* --- get model
$call gamslib -q trnsport
* --- compress and run model
$compress trnsport.gms t1.gms
$decompress t1.gms t1.org
$call diff trnsport.gms t1.org > %system.nullFile%
$if errorLevel 1 $abort files trnsport and t1 are different
* --- check to see if we get the same result
$call gams trnsport gdx=trnsport lo=%gams.lo%
$if errorLevel 1 $abort model trnsport failed
$call gams t1 gdx=t1 lo=%gams.lo%
$if errorLevel 1 $abort model t1 failed
$call gdxdiff trnsport t1 %system.reDirLog%
$if errorLevel 1 $abort results for trnsport and t1 are not equal
* --- also works with include files
$echo $include t1.gms > t2.gms
$call gams t2 gdx=t2 lo=%gams.lo%
$if errorLevel 1 $abort model t2 failed
$call gdxdiff trnsport t2 %system.reDirLog%
$if errorLevel 1 $abort results for trnsport and t2 are not equal
$terminate
Encrypting Files
When models are distributed to users other than the original developers, issues of privacy, security, data integrity and ownership arise. To address these concerns, secure work files may be used and GAMS input files may be encrypted. Note, that the encryption follows the work file security model and requires special licensing.
- Note
- Like any other GAMS input files, all compressed and encrypted files are platform-independent.
Encryption is only available if a system is licensed for secure work files. There are two way to encrypt a file: Encryption for a particular user group that is identified by a target license file or for a general wide audience. In the prior case the key for encryption and decryption is extracted from the target license (specified by command line parameter pLicense) while for the latter the key for encryption and decryption is passed to GAMS via the command line parameters encryptKey and decryptKey. Note that once a file has been encrypted it cannot be decrypted any more. GAMS provides the following dollar control option to encrypt an input file:
$encrypt <source> <target>
Here the name of the input file to be encrypted is source
and the name of the resulting encrypted file is target
.
Encrypting Files: A Simple Example
We use again the transportation model [TRNSPORT] to illustrate. First we copy the model from the GAMS Model Library and then we create an encrypted version of the original via a target license:
> gamslib -q trnsport > echo $encrypt trnsport.gms t1.gms > t2.gms > gams t2 pLicense=target lo=%gams.logOption%
Note that the first two lines are similar to the directives that we have used to compress the model above. In the third line, the command line parameter pLicense specifies the target or privacy license to be used as a user key for encrypting. Thus the new encrypted file t1.gms
is locked to the license key target
and it can only be executed with the license file target:
> gams t1 license=target dumpOpt=11
Note that the command line parameter license is used to override the default GAMS license file gamslice.txt
that can be located in various system wide and user locations. Note further that the command line parameter dumpOpt is usually used for debugging and maintenance. The value 11 causes a clean copy of the input to be written to the file t1.dmp
, where all include files and macros are expanded. Observe that if some lines have been marked with the dollar control options $on/offListing in the original file, then these lines will be suppressed in the file t1.dmp
.
An alternative approach to encrypt GAMS source file without a target license is done by the pair of command line parameters encryptKey and decryptKey:
> gamslib -q trnsport > echo $encrypt trnsport.gms t1.gms > t2.gms > gams t2 encryptKey=ThisIsAPasswordSomeoneNeedsToRunTheModel lo=%gams.logOption%
In the third line, the command line parameter encryptKey specifies the encryption key. Thus the new encrypted file t1.gms
is locked and requires this key to successfully decrypt via command line parameter decryptKey:
> gams t1 decryptKey=ThisIsAPasswordSomeoneNeedsToRunTheModel
Anyother key will result in a failure with the message Integrity check failed
.
- Note
- Once a file has been encrypted, it cannot be decrypted any more. There is no inverse mechanism to recover the original file from the encrypted file. An attempt to decompress it using $decompress will fail.
Observe that decrypting is done on the fly into memory when the GAMS system files are read. GAMS will recognize if a file is just plain text or compressed and/or encrypted and will validate and process the files accordingly.
Encrypting Files: The Model ENCRYPT
The following more elaborate example is self-explanatory; it is model [ENCRYPT] from the GAMS Model Library.
$title Input File Encryption Demo (ENCRYPT,SEQ=318)
$onText
Input files can be encrypted with an encryption key. Either the
privacy license file mechanism or the command line parameter pair
encryptKey/decryptKey can be for managing the password. Similar to
compression, we offer an $encrypt utility to lock any file to a
specific key. Once a file has been encrypted it can only be read
by a gams program that has the matching license file or the matching
decryption key. There is no inverse operation possible: you cannot recover
the original GAMS file from the encrypted version.
To create an encrypted file, we need a license file which has the
security option enabled.
Keywords: GAMS language features, input file encryption
$offText
$if not set MYPLICENSE $set MYPLICENSE "%gams.sysdir%plicense.txt"
$ifthen not exist "%MYPLICENSE%"
$ log *** Target license file "%MYPLICENSE%" does not exist.
$ log *** Specify via --MYPLICENSE=...
$ log *** Encryption only via en/decryptKey
$ drop MYPLICENSE
$endif
* --- get model
$onDollar
$call gamslib -q trnsport
$ifthen.MYPLICENSE set MYPLICENSE
* --- encrypt and try to decrypt
$call rm -f t1.gms
$echo $encrypt trnsport.gms t1.gms > s1.gms
$call gams s1 plicense="%MYPLICENSE%" lo=%gams.lo%
$ifE errorLevel<>0 $abort encryption failed
$eolCom //
$if not errorFree $abort pending errors
$decompress t1.gms t1.org // this has to fail
$if errorFree $abort decompress did not fail
$clearError
*-- execute original and encrypted model
$call gams trnsport gdx=trnsport lo=%gams.lo%
$ifE errorLevel<>0 $abort model trnsport failed
$call gams t1 license="%MYPLICENSE%" gdx=t1 lo=%gams.lo%
$ifE errorLevel<>0 $abort model t1 failed
$call gdxdiff trnsport t1 %system.reDirLog%
$ifE errorLevel<>0 $abort results for trnsport and t1 are not equal
* --- use the encrypted file as an include file
$onEcho > t2.gms
$offListing
* this is hidden
option limRow = 0, limCol = 0, solPrint = off;
$include t1.gms
$onListing
* this will show
$offEcho
$call gams t2 license="%MYPLICENSE%" lo=%gams.lo%
$ifE errorLevel<>0 $abort model t2 failed
* --- protect against viewing
* now we will show how to protect parts of an input
* file from viewing and extracting original source
* via the gams DUMPOPT parameter. We just need to
* encrypt again
* --- encrypt new model
$call rm -f t3.gms
$echo $encrypt t2.gms t3.gms > s1.gms
$call gams s1 plicense="%MYPLICENSE%" lo=%gams.lo%
$ifE errorLevel<>0 $abort encryption failed
$call gams t3 license="%MYPLICENSE%" gdx=t3 dumpopt=19 lo=%gams.lo%
$ifE errorLevel<>0 $abort model t3 failed
$call gdxdiff trnsport t3 %system.reDirLog%
$ifE errorLevel<>0 $abort results for trnsport and t3 are not equal
* --- check for hidden output
$call grep "this is hidden" t3.lst > %system.nullfile%
$if not errorLevel 1 $abort did not hide in listing
$call grep "this is hidden" t3.dmp > %system.nullfile%
$if not errorLevel 1 $abort did not hide in dump file
$endif.MYPLICENSE
* Same with encryptKey/decryptKey
* --- encrypt and try to decrypt
$call rm -f t1.gms
$echo $encrypt trnsport.gms t1.gms > s1.gms
$call gams s1 encryptKey=ThisIsMyPassword lo=%gams.lo%
$ifE errorLevel<>0 $abort encryption failed
$eolCom //
$if not errorFree $abort pending errors
$decompress t1.gms t1.org // this has to fail
$if errorFree $abort decompress did not fail
$clearError
*-- execute original and encrypted model
$call gams trnsport gdx=trnsport lo=%gams.lo%
$ifE errorLevel<>0 $abort model trnsport failed
$call gams t1 decryptKey=ThisIsMyPassword gdx=t1 lo=%gams.lo%
$ifE errorLevel<>0 $abort model t1 failed
$call gdxdiff trnsport t1 %system.reDirLog%
$ifE errorLevel<>0 $abort results for trnsport and t1 are not equal
* --- use the encrypted file as an include file
$onEcho > t2.gms
$offListing
* this is hidden
option limRow = 0, limCol = 0, solPrint = off;
$include t1.gms
$onListing
* this will show
$offEcho
$call gams t2 decryptKey=ThisIsMyPassword lo=%gams.lo%
$ifE errorLevel<>0 $abort model t2 failed
* --- protect against viewing
* now we will show how to protect parts of an input
* file from viewing and extracting original source
* via the gams DUMPOPT parameter. We just need to
* encrypt again
* --- encrypt new model
$call rm -f t3.gms
$echo $encrypt t2.gms t3.gms > s1.gms
$call gams s1 encryptKey=ThisIsMyPassword lo=%gams.lo%
$ifE errorLevel<>0 $abort encryption failed
$call gams t3 decryptKey=ThisIsMyPassword gdx=t3 dumpopt=19 lo=%gams.lo%
$ifE errorLevel<>0 $abort model t3 failed
$call gdxdiff trnsport t3 %system.reDirLog%
$ifE errorLevel<>0 $abort results for trnsport and t3 are not equal
* --- check for hidden output
$call grep "this is hidden" t3.lst > %system.nullfile%
$if not errorLevel 1 $abort did not hide in listing
$call grep "this is hidden" t3.dmp > %system.nullfile%
$if not errorLevel 1 $abort did not hide in dump file