GLPK/Output to GMPL data file

It may be desirable to output the result of a computation to a GMPL data file to use is as the input for another optimization. The example below shows how this can be accomplished using the printf command.

# Outputing results as GMPL data file
# Save model file as test.mod
# 1st run: glpsol -m test.mod
# 2nd run: glpsol -m test.mod -d test.dat

param f, symbolic := "test.dat";
set S, dimen 3 := { (0, 0, 1), (0, 1, 0), (1, 0, 0), (1, 1, 1) };
param p{(i, j, k) in S} := i + 2 * j + 4 * k;

set T, dimen 3;
param q{T};
param r;

# Begin file output
printf "data;\n" > f;
# Output simple parameter
printf "param r := %f;\n", card(S) >> f;

# Output set
printf "set T :=\n" >> f;
for {(i,j,k) in S} {
  printf "%d, %d, %d%s", i, j ,k,
  if card(setof{(l, m, n) in S : l > i or m > j or n > k }(l, m, n)) > 0
  then ","
  else ";" >> f;
  printf "\n" >> f;
}

# Output indexed parameter
printf "param q :=\n" >> f;
for {(i,j,k) in S} {
  printf "[%d, %d, %d] %f%s", i, j ,k, p[i, j, k],
  if card(setof{(l, m, n) in S : l > i or m > j or n > k }(l, m, n)) > 0
  then ","
  else ";" >> f;
  printf "\n" >> f;
}

printf "end;\n" >> f;
# File output is completed

# Display input from data file
display T;
display q;
display r;
end;