Try our new documentation site (beta).
Model-data separation in Python
Examples: diet2.py, diet3.py, diet4.py
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.py
, diet3.py
, and diet4.py
examples. These examples
illustrate alternate approaches to providing data to the optimization
model: diet2.py
embeds the
data in the source file, diet3.py
reads the data from an
SQL database (using the Python sqlite3
package),
and diet4.py
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.py
, diet3.py
, and diet4.py
.
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.py
, diet3.py
, and diet4.py
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.