Reading and writing CPLEX models to files with Python
Read models from files and write models to files in an application using the CPLEX Python API.
In general, the methods of the class Cplex query, add, or modify data comprising an optimization problem.
Moreover, the class Cplex provides output streams for general log messages, results, warning
messages, and error messages. A user sets those output streams by
means of the methods set_log_stream
, set_results_stream
, set_warning_stream
,
and set_error_stream
. These methods take
either a file object or a filename as an argument; they also accept
the argument None
to disable their output.
These methods can also take, as an optional second argument, a parsing function that takes a string as input and returns a string as output. If the user specifies a parsing function, CPLEX uses that function to process the output to that stream.
By default, the log and results streams
are set to sys.stdout
and the error and
warning streams are set to sys.stderr
.
The sample lpex1.py
contains
one more line that deserves explanation in the context of reading
and writing files:
my_prob.write("lpex1.lp")
That statement causes my_prob
to
write the data it has stored to the file named lpex1.lp
.
In this sample, the file is written in LP format.
The reference manual, File formats supported by CPLEX, documents
that file format with respect to CPLEX in the topic LP file format: algebraic representation.
Other formats supported for writing problems to a file are MPS and SAV (also documented by the reference manual, File formats supported by CPLEX, in the topic MPS file format: industry standard and in SAV file format: numerically accurate binary files.
The CPLEX Python API decides which file format to write based on the extension of the file name; you can also use an optional format string as an additional argument to specify a file format.
The class Cplex also
supports reading of files through its method read and
through its constructor. For example, if cpx
is
an instance of the class Cplex,
then a call like this:
cpx.read("file.lp")
or like this:
cpx = cplex.Cplex("file.lp")
causes the CPLEX Python API to read a problem from the
formatted file named file.lp
.
The method read
replaces
all data currently stored in the object cpx
.
MPS and SAV format files are also supported in a similar way.