model solve status in conditional statement

Hello,

I would like to use the model and solve status in a conditional statement. My initial thought was to create a global variable based on a condition and then use this global variable in a second condition statement. I am having trouble getting the first condition to work. My code:

$setglobal solved
$if mymodel.solveStat == %solveStat.Normal Completion% and mymodel.modelStat == %modelStat.Solved% $setglobal solved 1

$ifthen %solved%==1
run some code
$else
run some other code
$endif

The problem is with the first conditional statement. Even if the conditions are met, the global variable “solved” is never set to 1. Any insight would be appreciated.

Thanks in advance,
Christine

Dear Christine,

GAMS doesn’t work this way as GAMS distinguishes between compiltation and exectution time, see: https://www.gams.com/latest/docs/UG_GamsCall.html#UG_GamsCall_TwoPass
Control variables (e.g. $setglobals) are executed at compile time and the solve statment is executed at execution time. However, there are other possibilities, for example:

Abort$(mymodel.modelstat <> %modelstat.Optimal%) 'Non-optimal solution';

or

if(mymodel.modelstat eq %modelstat.Optimal% and mymodel.solveStat eq %solveStat.Normal Completion%,
<some code>
);

Hope this helps.

Cheers,
GFA

Thanks, GFA.

Indeed. I was trying to set a compile time global variable with a run time mymodel.solveStatus. Using your second option works great. thanks for your help.

Kind regards,
Christine

Hi,

I want to write results to an external .csv file, but only in the case where the solution is optimal. These are the commands I used:

Solve mymodel min objvar using nlp ;

if(mymodel.modelstat eq %modelstat.Optimal% and model.solveStat eq %solveStat.Normal Completion%,

execute_unload ‘results.gdx’;
put results;
results.nd = 3;
put_utilities ‘ren’/ ‘results_mymodel.csv’:0;

);

Unfortunately, I was unsuccessful in creating the CSV file. Would it be possible for someone to assist me in identifying the error? Thank you in advance for your help.

Warm Regards,
Shih

Here you find some info to export from GAMS to text files (including CSV): https://www.gams.com/latest/docs/UG_DataExchange_ASCII.html#UG_DataExchange_ASCII_Export

-Michael

Thanks Michael. But I only want to export the file when the solution is optimal. Is there a way of doing it? Thanks. Shih

Sure, then just put the logic to create CSV files described in the section I linked to in the if statement you already have. Declarations, like file fx /x.csv/, need to be done outside control structures though.

-Michael

Got it and thanks Michael!

Shih