Thursday, July 31, 2008

GAMS optimizing assignments

The following fragment shows an unexpected performance problem. I thought all these assignments should be fast (i.e. only over the nonzero elements).

   1  set i /i1*i300/;
2 alias (i,j,k);
3
4 parameter p(i,j,k);
5 p(i,i,i) = 3.14;
6
7 parameter p1(i,j,k),p2(i,j,k);
8
9 p1(i,j,k) = -p(i,j,k);
10 p2(i,j,k)$p(i,j,k) = -p(i,j,k);

---- 1 ExecInit 0.000 0.000 SECS 3 Mb
---- 5 Assignment p 0.000 0.000 SECS 4 Mb 300
---- 9 Assignment p1 2.683 2.683 SECS 4 Mb 300
---- 10 Assignment p2 0.000 2.683 SECS 4 Mb 300


We see here the assignment to p1 is slow (GAMS runs through the carthesian product i x j x k) while the assignment to p2 is fast. I would expect the assignment to p1 to be fast as well.

An assignment of the form
p1(i,j,k) = (-1)*p(i,j,k)
would be optimized by GAMS while
p1(i,j,k) = -1*p(i,j,k)
would be slow again.

The profiler can help you detect these situations and optimize the assignments manually like I did for p2.