Search code examples
gams-math

Writing loop within GAMS and printing the results on one excel file


I am solving a model in GAMS, which is a large model, call it "profit", but in which I wish to vary a particular parameter, call it alpha(j), where alpha represents parameters defined over different values of a set `j', and then see how the results for key variables change with it.

Call the loop index `i', and I wish to run the model by increasing alpha(j) by 0.05 each time, from the initial values of the full vector alpha(j), and then look at how the variables X and Y change:

Set        i          / 1*20/  ;

*In the above, I set the index from 1 to 20, and then the initial value of alpha for the first iteration as 0.

*I then write the loop

    loop(i, alpha(j,i+1)  =alpha(j)+0.05
    solve mymodel using lp maximizing profit;
);

*I then wish to write the results to an excel GDX file.

*Baseline

execute_unload "resultsloop.gdx"
X Y ; 

execute 'gdxxrw.exe resultsloop.gdx var=XXX rng=XXX   !a1'

execute 'gdxxrw.exe resultsloop.gdx var=X.L rng=X!a1'
execute 'gdxxrw.exe resultsloop.gdx var=Y.L rng=Y!a1'

;

There are two problems with this- one of which I have and the other which I can foresee.

  1. The first issue is that I get an error "Dimension different - The symbol is referenced with more/less indices as declared". I am not sure how to address this issue.

  2. The second issue (which I can foresee) is in the writing of the excel results. Ideally, I would like the results for each variable be stacked in a column, by loop number. As it currently stands, I will simply get a single excel file, with only the results corresponding to the end of the loop.

Any help on this is much appreciated!!


Solution

  • About the first issue: That problem is probably caused by the assignment alpha(j,i+1) =alpha(j)+0.05. As the error message says, for alpha you reference it with two dimensions on the left (j,i+1) and with one on the right (alpha(j)). One of this must be wrong. Compare it to your declaration (you did not share that here).

    About the second issue: I would collect the results in one parameter in GAMS and write this all at once to Excel at the end, like in this dummy code:

    parameter profitI(i)
              someIndexedOverJVarI(i,j);
    loop(i, 
        alpha(j)  =alpha(j)+0.05;
        solve mymodel using lp maximizing profit;
        profitI(i) = profit.l;
        someIndexedOverJVarI(i,j) = someIndexedOverJVar.l(j);
    );
    execute_unload "results.gdx" profitI;
    execute 'gdxxrw.exe results.gdx par=profitI rng=XXX!a1';