Rank

Top  Previous  Next

One may also use Rutherford and van der Eijk's RANK libinclude procedure to obtain an array giving the relative sorted position of elements.  This procedure implements an O(nlog(n)) algorithm for ranking one-dimensional numeric data within a GAMS program.  The routine uses the GDX facility and an external program to sort the data.

The syntax for using rank is

 

$LIBINCLUDE rank arraytosort setofelements rankofitem optionalpercentile

 

The first three arguments are required. The last is optional.  These are defined as following:

arraytosortName of one dimensional parameter of values to be ranked which defined over the set setofelements
setofelementsName of one-dimensional set which is the domain of array arraytosort.
RankofitemName of one dimensional parameter that after execution will contain integers giving the rank order of each element ranking from smallest to largest.
optionalpercentileName of one dimensional parameter that after execution will contain linearly interpolated percentiles.

Example:

GAMS code implementing RANK appears at the bottom of sorted.gms and is as follows

 

$LIBINCLUDE rank unsort i rankdata

put // 'After rank which sorts low' //;

loop(asord,

 loop(i$(rankdata(i)=ord(asord)),

  put 'In place ' asord.tl:0 ' with value of ' unsort(i):0:0 ' is item ' 

         @42 i.tl:0/));

display r;

 

The resultant output is

 

After rank which sorts low

 

In place 1 with a value of 12 is item    a3

In place 2 with a value of 15 is item    a4

In place 3 with a value of 22 is item    a6

In place 4 with a value of 22 is item    a1

In place 5 with a value of 33 is item    a2

In place 6 with a value of 47 is item    a5

Notes:

Rutherford and van der Eijk state:

RANK only works for numeric data.  You cannot sort sets.
The first invocation must be outside of a loop or if block.  This routine may be used within a loop or if block only if it is first initialized with blank invocations.
The names rank_tmp, rank_u, and rank_p are used within these routines and may not be used in the calling program:
This routine returns rank values and does not return sorted vectors, however rank values may be used to produce a sorted array.  This can be done using computed "leads" and "lags" in GAMS' ordered set syntax, as illustrated in their examples.