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,, and examples. These examples illustrate alternate approaches to providing data to the optimization model: embeds the data in the source file, reads the data from an SQL database (using the Python sqlite3 package), and reads the data from an Excel spreadsheet (using the Python xlrd package). contains the optimization model itself. The same model is used by,, and

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.,, and 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 in the current directory. The second passes the model data to the solve function in the newly imported module.