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.

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.