It is always a good idea to revisit existing GAMS code and see if we can improve it. Here is an example of an actual model.
The problem is that we want to set up a mapping set between two sets based on the first two characters. If they are the same, the pair should be added to the mapping. The old code looked like:
To verify this indeed generates the correct result for set rs, we look at the output:
- The function ord(string, pos) returns the ASCII value of the character at position pos of the string.
- The suffix .TL is the text string of the set element (internally GAMS does not work with the strings but rather an integer id for each set element; here we make it explicit we want the string).
- The loops are not really needed. We could have used:
value('1',R) = 100*ord( R.tl,1) + ord( R.tl,2);
value('2',S) = 100*ord( S.tl,1) + ord( S.tl,2);
- The mapping set is a very powerful concept in GAMS. It is somewhat like a dict in Python, except it is not one way. It can map from r to s but also from s to r.
This gives the same result:
- No need for the auxiliary parameter value.
- No loops.
- We could add a check that we have no unmapped subregions. E.g. by:
abort$(card(rs)<>card(s)) "There are unmapped subregions";
- This will also catch cases where the casing does not match.
- Critical note: GAMS has very poor support for strings. This should have been rectified a long time ago. There is no excuse for this deficiency.