Writing data to an external file using OPL script
Question
How do I write data to an external file using OPL script?
Answer
The following sample .mod file creates a trivial model, and then writes the input data along with the optimal (objective and variable) values to an external file called modelRun.txt in a post-processing execute block. In its current form, the external file will be created (if not already present) in the same folder as that of the project, but the IloOplOutputFile
can also take an absolute path location as needed by a user:
/**writeExternal.mod**/
range r=1..5;
dvar int+ x[r];
int y[i in r]=i;
minimize sum(i in r) x[i];
subject to{
forall(i in r)
x[i]>=y[i];
}
execute{
var ofile = new IloOplOutputFile("modelRun.txt");
ofile.writeln("Data:");
for(var i in thisOplModel.r){
ofile.writeln("y["+i+"]="+thisOplModel.y[i]);
}
ofile.writeln("Optimal objective value="+cplex.getObjValue());
ofile.writeln("Optimal variable values:");
for(i in thisOplModel.r){
ofile.writeln("x["+i+"]="+thisOplModel.x[i]);
}
ofile.close();
}
As an alternative, the main block of an OPL model can also be used to do similar operations. The following sample shows one such implementation, where the internal, external & solution data (without iterating through the elements) is written out to an external file:
/**writeExternal.mod**/
range r = 1..5;
int y[i in r] = i;
dvar int+ x[r];
minimize sum(i in r) x[i];
subject to {
forall(i in r)
x[i] >= y[i];
}
main {
thisOplModel.generate();
cplex.solve();
var ofile = new IloOplOutputFile("modelRun.txt");
ofile.writeln(thisOplModel.printExternalData());
ofile.writeln(thisOplModel.printInternalData());
ofile.writeln(thisOplModel.printSolution());
ofile.close();
}
Reference : http://www-01.ibm.com/support/docview.wss?uid=swg21508158