Model-data separation in Python#
When building an optimization model in a modeling language, it is typical
to separate the optimization model itself from the data used to create an
instance of the model. These two model ingredients are often stored in
completely different files. We show how a similar result can be achieved in
our Python interface with our diet2 example, diet3 example
and diet4 example. These examples
illustrate alternate approaches to providing data to the optimization
model: diet2 example embeds the data in
the source file, diet3 example reads the
data from an SQL database (using the Python sqlite3
package), and
diet4 example reads the data from an Excel
spreadsheet (using the Python xlrd
package). dietmodel.py contains the optimization model itself. The
same model is used by diet2 example,
diet3 example and diet4 example.
The key construct that enables the separation of the model from the data is
the Python module. A module is simply a set of functions and variables,
stored in a file. You import a module into a program using the import
statement. diet2 example, diet3
example and diet4 example all populate a set of variables, and then pass
them to the solve
function of the dietmodel module using the following pair of statements:
import dietmodel
dietmodel.solve(categories, minNutrition, maxNutrition, foods, cost, nutritionValues)
The first statement imports the dietmodel module, which must be stored in file
dietmodel.py in the current
directory. The second passes the model data to the solve
function in
the newly imported module.