Conditional statements

<< Click to Display Table of Contents >>

Navigation:  Gekko User Guide > Data Management User Guide > Gekko programs >

Conditional statements

Previous pageReturn to chapter overviewNext page

Note: If you are running one of the examples interactively in the Gekko input window, you should mark the code from if to the corresponding end, followed by [Enter]. Executing an IF statement line by line in the Gekko input window will not work.

 

The IF statement is used to execute statements if a certain condition is met (and an optional ELSE statement will execute other statements if not). The syntax is pretty standard for programming languages, for instance:

 

%x1 = 2; %x2 = 3;
if (%x1 < %x2);
  tell 'true';
else;
  tell 'false';
end;

 

If the condition is true, the following statements are executed, and if the condition is false, ELSE can be used to execute alternate statements. You normally compare scalar expressions via one of the following comparison operators: <, <=, ==, >=, > or <>, and these operators can also be combined with the logical keywords and, or, and not.

 

You may also compare two whole timeseries, but beware that there are some special rules in play in that case, and there are also special rules when one or both of the values contain missing values (more here or here).

 

Several terms can be combined with and, or, and not, like in the following example:

 

if (not(x[%t] > 100 or %== 'yes') and (%x1 > %x2));
  tell 'true';
end;

 

Below is an example of a part of a program where the program file interrupts, if the variable fvar has a zero value in the period %t.

 

if (fvar[%t] == 0);
  pause 'A price cannot be calculated';
  stop;
else
  //continue normally 
end;

 

You can also combine ACCEPT and IF to control the flow of a program interactively:

 

accept string %yesno 'Do you want to multiply x by 1000?';
if (%yesno == 'yes');
  x *= 1000;
else;
  if (%yesno <> 'no');
    tell 'You must answer "yes" or "no"';
    stop;
  end;
end;

 

When comparing, you may need to convert between variable types. In the following example, %s is a text string, %d is a date, and %v is a value.

 

%= '2012';
%= date(%s);
%= val(%d);
mem;  //show these scalars

 

When comparing those, you will need to convert %s and %d to values, for instance:

 

if (val(%s) == val(%d) and val(%s) == %v and val(%d) == %v);
  tell 'true';
else
  tell 'false';
end;

 

It should be mentioned that Gekko supports $-conditionals, similar to how these work in GAMS. These are a kind of inline if-conditions, an example:

 

time 2010 2013;
x1 = 100;
x2 = 90, 110, 80, 120;
= x2 $ (x2 > x1);  //0, 110, 0, 120

 

In the last statement, Gekko checks the condition for each period, and if it is true, x2 is used, otherwise the value is 0. Also see the iif() function with similar capabilities.