Search code examples
glpk

How to read single parameter from a file?


Chapter 9, page 163, of the AMPL book gives an example of reading a single parameter from a file:

For example, if you want to read the number of weeks and the hours available each week for our simple production model (Figure 4-4),

param T > 0;

param avail {1..T} >= 0;

from a file week_data.txt containing

4

40 40 32 40

then you can give the command

read T, avail[1], avail[2], avail[3], avail[4] <week_data.txt;

This command fails in GLPK with error colon missing where expected. The Modeling Language GNU MathProg Language reference only contains table data IN, which serves for reading tabular data. Can GLPK read a single parameter from a file?


Solution

  • AMPL and GMPL are related functional languages. GMPL contains a subset of the AMPL syntax but differs in several areas like the table statement.

    One way to read a single parameter is to write the data into a file with a certain syntax, e.g. the contents below show a single parameter and a table:

    param T := 4;
    
    param avail :=
          1 0
          2 1
          3 1
          4 0;
    
    end;
    

    To verify the syntax, consider this code in the file problem.mod:

    param T > 0;
    
    param avail {1..T} >= 0;
    
    var use {1..T} >= 0;
    
    maximize usage: sum {t in 1..T} avail[t];
    
    subject to constraint {t in 1..T}: use[t] <= avail[t];
    
    solve;
    
    end;
    

    The result shows that it worked:

    > glpsol -m problem.mod -d problem.dat
    GLPSOL: GLPK LP/MIP Solver, v4.65
    Parameter(s) specified in the command line:
     -m problem.mod -d problem.dat
    Reading model section from problem.mod...
    13 lines were read
    Reading data section from problem.dat...
    9 lines were read
    Generating usage...
    Generating constraint...
    Model has been successfully generated
    glp_mpl_build_prob: row usage; constant term 2 ignored
    GLPK Simplex Optimizer, v4.65
    5 rows, 4 columns, 4 non-zeros
    Preprocessing...
    ~     0: obj =   2.000000000e+00  infeas =  0.000e+00
    OPTIMAL SOLUTION FOUND BY LP PREPROCESSOR
    Time used:   0.0 secs
    Memory used: 0.1 Mb (110236 bytes)
    Model has been successfully processed