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 示例, diet3 示例
and diet4 示例. These examples
illustrate alternate approaches to providing data to the optimization
model: diet2 示例 embeds the data in
the source file, diet3 示例 reads the
data from an SQL database (using the Python sqlite3
package), and
diet4 示例 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 示例,
diet3 示例 and diet4 示例.
实现模型与数据分离的关键结构是Python模块。模块简单来说就是一组函数和变量,存储在文件中。你可以使用import
语句将模块导入到程序中。diet2 示例、diet3 示例和diet4 示例都填充了一组变量,然后通过以下一对语句将它们传递给dietmodel模块的solve
函数:
import dietmodel
dietmodel.solve(categories, minNutrition, maxNutrition, foods, cost, nutritionValues)
第一条语句导入了dietmodel模块,该模块必须存储在当前目录中的dietmodel.py文件中。第二条语句将模型数据传递给新导入模块中的solve
函数。