python中do的用法,如何使用docplex(python)对优化问题中的约束进行建模?
我需要解决一个优化问题,类似于背包问题。我在这篇文章中详细介绍了优化问题:
knapsack optimization with dynamic variables
实际上,我需要使用python而不是OPL,所以为了使用cplex优化框架,我安装了docplex和clpex包。在
下面是我想用docplex转换成python的OPL代码{string} categories=...;
{string} groups[categories]=...;
{string} allGroups=union (c in categories) groups[c];
{string} products[allGroups]=...;
{string} allProducts=union (g in allGroups) products[g];
float prices[allProducts]=...;
int Uc[categories]=...;
float Ug[allGroups]=...;
float budget=...;
dvar boolean z[allProducts]; // product out or in ?
dexpr int xg[g in allGroups]=(1<=sum(p in products[g]) z[p]);
dexpr int xc[c in categories]=(1<=sum(g in groups[c]) xg[g]);
maximize
sum(c in categories) Uc[c]*xc[c]+
sum(c in categories) sum(g in groups[c]) Uc[c]*Ug[g]*xg[g];
subject to
{
ctBudget:
sum(p in allProducts) z[p]*prices[p]<=budget;
}
{string} solution={p | p in allProducts : z[p]==1};
execute
{
writeln("solution = ",solution);
}
这是我的第一次代码尝试:
^{pr2}$
实际上我不知道如何正确地建模OPL代码中的xg、xc和z变量?在
关于如何正确建模的任何想法。
提前谢谢你
编辑:这是@HuguesJuille建议后的编辑,我已经清理了代码,现在它可以正常工作了。在from docplex.mp.model import Model
from docplex.util.environment import get_environment
# ----------------------------------------------------------------------------
# Initialize the problem data
# ----------------------------------------------------------------------------
Categories_groups = {"Carbs": ["Meat","Milk"],"Protein":["Pasta","Bread"], "Fat": ["Oil","Butter"]}
Groups_Products = {"Meat":["Product11","Product12"], "Milk": ["Product21","Product22","Product23"], "Pasta": ["Product31","Product32"],
"Bread":["Product41","Product42"], "Oil":["Product51"],"Butter":["Product61","Product62"]}
Products_Prices ={"Product11":1,"Product12":4, "Product21":1,"Product22":3,"Product23":2,"Product31":4,"Product32":2,
"Product41":1,"Product42":3, "Product51": 1,"Product61":2,"Product62":1}
Uc={"Carbs": 1,"Protein":1, "Fat": 0 }
Ug = {"Meat": 0.8, "Milk": 0.2, "Pasta": 0.1, "Bread": 1, "Oil": 0.01, "Butter": 0.6}
budget=3;
def build_userbasket_model(**kwargs):
allcategories = Categories_groups.keys()
allgroups = Groups_Products.keys()
allproducts = Products_Prices.keys()
# Model
mdl = Model(name='userbasket', **kwargs)
z = mdl.binary_var_dict(allproducts, name='z([%s])')
xg = {g: 1 <= mdl.sum(z[p] for p in Groups_Products[g]) for g in allgroups}
xc = {c: 1 <= mdl.sum(xg[g] for g in Categories_groups[c]) for c in allcategories}
mdl.add_constraint(mdl.sum(Products_Prices[p] * z[p] for p in allproducts) <= budget)
mdl.maximize(mdl.sum(Uc[c] * xc[c] for c in allcategories) + mdl.sum(
xg[g] * Uc[c] * Ug[g] for c in allcategories for g in Categories_groups[c]))
mdl.solve()
return mdl
if __name__ == '__main__':
"""DOcplexcloud credentials can be specified with url and api_key in the code block below.
Alternatively, Context.make_default_context() searches the PYTHONPATH for
the following files:
* cplex_config.py
* cplex_config_.py
* docloud_config.py (must only contain context.solver.docloud configuration)
These files contain the credentials and other properties. For example,
something similar to::
context.solver.docloud.url = "https://docloud.service.com/job_manager/rest/v1"
context.solver.docloud.key = "example api_key"
"""
url = None
key = None
mdl = build_userbasket_model()
# will use IBM Decision Optimization on cloud.
if not mdl.solve(url=url, key=key):
print("*** Problem has no solution")
else:
mdl.float_precision = 3
print("* model solved as function:")
mdl.print_solution()
# Save the CPLEX solution as "solution.json" program output
with get_environment().get_output_stream("solution.json") as fp:
mdl.solution.export(fp, "json")
我希望这能帮助像我这样有同样问题的初学者。在
python中do的用法,如何使用docplex(python)对优化问题中的约束进行建模?相关推荐
- python中的浮点数用法_如何利用Python在运算后得到浮点数值的方法详解
在python中进行两个整数相除的时候,在默认情况下都是只能够得到整数的值,而在需要进行对除所得的结果进行精确地求值时,想在运算后即得到浮点值,那么如何进行处理呢? 1.修改被除数的值为带小数点的形式 ...
- python的messagebox的用法_Python GUI编程学习笔记之tkinter中messagebox、filedialog控件用法详解...
本文实例讲述了Python GUI编程学习笔记之tkinter中messagebox.filedialog控件用法.分享给大家供大家参考,具体如下: 相关内容: messagebox 介绍 使用 fi ...
- [转载] python中for语句用法_详解Python中for循环的使用_python
参考链接: 在Python中将else条件语句与for循环一起使用 这篇文章主要介绍了Python中for循环的使用,来自于IBM官方网站技术文档,需要的朋友可以参考下 for 循环 本系列前面 &q ...
- python中for语句用法_详解Python中for循环的使用_python
这篇文章主要介绍了Python中for循环的使用,来自于IBM官方网站技术文档,需要的朋友可以参考下 for 循环 本系列前面 "探索 Python,第 5 部分:用 Python 编程&q ...
- python中str.format用法_详解Python中的str.format方法
字符串的内置方法大致有40来个,但是一些常用的其实就那么20几个,而且里面还有类似的用法,区分度高比如:isalpha,isalnum,isdigit,还有一些无时不刻都会用到的split切分,joi ...
- python中case的用法_如何在Python中使用TestCase实现一个断言功能
如何在Python中使用TestCase实现一个断言功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题. Python TestCase断 ...
- python中translate的用法_如何在python中利用translate模块实现一个翻译功能
如何在python中利用translate模块实现一个翻译功能 发布时间:2020-12-18 14:16:00 来源:亿速云 阅读:86 这期内容当中小编将会给大家带来有关如何在python中利用t ...
- python中floor的用法_Python floor() 函数 - Python 教程 - 自强学堂
Python floor() 函数 描述 floor() 返回数字的下舍整数. 语法 以下是 floor() 方法的语法:import math math.floor( x ) 注意:floor()是 ...
- python中exec的用法_如何在Python中安全地使用exec()?
我的任务是构建一个应用程序,在该应用程序中最终用户可以使用自定义规则来评估返回的查询是警告还是警报(基于自己的阈值). 我为用户建立了逻辑模板的方法.一个示例如下所示: if (abs(<< ...
最新文章
- vs2012 智能提示消失解决办法
- Spring学习(五)bean装配详解之 【XML方式配置】
- HDU - 5015 233 Matrix(矩阵快速幂)
- 360容器平台监控实践
- inventor 波纹阵列_Inventor技巧之草图驱动的阵列图文教程
- 架构师架构蓝图《UML精粹》 UML Distilled读后感
- (转载)C++面试宝典2011版
- HTML单选框-多选框-按钮
- C语言链表详解附实例
- 计算机应该怎样复制桌面,电脑全屏复制快捷键是什么(史上最全电脑快捷键集合)...
- windows远程桌面登录不允许空密码
- 2023-04-18_面试题复盘笔记(121)
- 武魂显示无法连接服务器,武魂天下进不去连接服务器失败解决方法
- python爬虫好友图片_Python爬取所有微信好友头像,制作微信好友图片墙
- KindEditor 图片粘贴上传,实现图文粘贴,图片自动上传
- win10照片查看器_win10系统,图片查看器不见了咋办?教你调出传统图片查看器。...
- 三星T7装Linux系统,Ubuntu已成为三星ARTIK 5/7的主力GNU/Linux系统
- 肖秀荣:考研政治选择题最完整答题技巧总结
- 数据分析师入门_数据分析师入门基础指南
- 今日头条创始人张一鸣:独特定位是我们的优势