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.

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.

Search