如何从文件中读取单个参数?

How to read single parameter from a file?

AMPL book 的第 9 章第 163 页给出了从文件中读取单个参数的示例:

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;

此命令在 GLPK 中失败,错误为 colon missing where expected。建模语言 GNU MathProg 语言参考仅包含 table data IN,用于读取表格数据。 GLPK 可以从文件中读取单个参数吗?

您可以使用 table 语句从 CSV 文件或 SQL tables 中读取参数。

您可以使用数据文件来传递参数,例如参见 this example of writing data files in AWK and Visual Basic

AMPL 和 GMPL 是相关的函数式语言。 GMPL 包含 AMPL 语法的一个子集,但在几个方面有所不同,例如 table 语句。

读取单个参数的一种方法是使用特定语法将数据写入文件,例如下面的内容显示了一个参数和一个 table:

param T := 4;

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

end;

要验证语法,请考虑文件 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;

结果表明成功了:

> 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