Search code examples
optimizationampl

how I can initialize a parameter in AMPL when it is defined on multiple sets?


Suppose I have

param m; #number of modes
 param n; #number of individual
param a; #number of alternatives
param f; #number of household
set M, default{1..m}; #set of modes
set N, default{1..n}; #set of individuals
set A, default{1..a}; #set of alternatives
set F, default{1..f}; #set of family
set E, within F cross N

How I can initialize param X{E,M,A} ?

Suppose

a:=2 , m:=3 , n:= 4 f:=2;

and set E is defined:

 set E:= 1 1   1 2    2 3    2 4 ; 

Solution

  • You can declare the parameter just as you suggested:

    param X{E,M,A};
    

    Now, if you want to provide a default value (which I assume is what you are asking), you can do it in the usual way:

    param X{E,M,A} default 0;
    

    Then provide some non-default values in the .dat file, e.g.,:

    param: X :=
        1 1 1 2   5
        2 3 2 1   6;
    

    Note that AMPL doesn't fill the default values into the parameter until you call solve. From the AMPL book, p. 120:

    The expression that gives the default value of a parameter is evaluated only when the parameter’s value is first needed, such as when an objective or constraint that uses the parameter is processed by a solve command.

    So if you type display X; after you have issued the model and data commands but before you have issued the solve command, you'll only get the non-default values, e.g.:

    X :=
    1 1 1 2   5
    2 3 2 1   6
    ;
    

    But if you use display X; after you call solve, you'll get the full list:

    X [1,*,*,1] (tr)
    :   1   2    :=
    1   0   0
    2   0   0
    3   0   0
    
     [1,*,*,2] (tr)
    :   1   2    :=
    1   5   0
    2   0   0
    3   0   0
    
     [2,*,*,1] (tr)
    :   3   4    :=
    1   0   0
    2   6   0
    3   0   0
    
     [2,*,*,2] (tr)
    :   3   4    :=
    1   0   0
    2   0   0
    3   0   0
    ;
    

    For completeness, here are the .mod and .dat files I used for this answer:

    .mod:

    param m; #number of modes
    param n; #number of individual
    param a; #number of alternatives
    param f; #number of household
    set M, default{1..m}; #set of modes
    set N, default{1..n}; #set of individuals
    set A, default{1..a}; #set of alternatives
    set F, default{1..f}; #set of family
    set E, within F cross N;
    
    param X{E,M,A} default 0;
    var myVar{E,M,A} >= 0;
    
    minimize Obj: sum {(i,j) in E, mm in M, aa in A} X[i,j,mm,aa] * myVar[i,j,mm,aa];
    

    .dat:

    param a:=2;
    param m:=3;
    param n:= 4;
    param f:=2;
    set E:= 1 1   1 2    2 3    2 4 ; 
    
    param: X :=
        1 1 1 2   5
        2 3 2 1   6;