Friday, July 1, 2011

Sorting in GAMS

This question came up during a workshop I taught at a large power company:

I want to generate a number of load-duration and price-duration curves, but it takes too long.

Here is a small example demonstrating some formulations for sorting a 1d parameter:

option profile=1;
set i /i1*i10000/
;
parameter
p(i);
p(i) = uniform(1,100);

display
p;

execute_unload "p"
,p;
execute "gdxrank p.gdx p2.gdx"
;

parameter
pindex(i);
execute_load "p2.gdx"
,pindex=p;
display
pindex;


* slow

parameter p2(i);
alias
(i,j);
p2(i)=
sum(j$(ord
(i)=pindex(j)),p(j));
display
p2;

* almost as slow

parameter p3(i);
alias
(i,j);
loop((i,j)$(ord
(i)=pindex(j)),
   p3(i)=p(j);
);

display
p3;

* fast using trick:

parameter p4(i);
p4(i+(pindex(i)-
ord
(i))) = p(i);
display
p4;

The timings are:

Method Time (seconds)
SUM (assignment to p2) 28.407
LOOP (assignment to p3) 22.230
TRICK (assignment to p4) 0.265