当前位置: 首页 > 知识库问答 >
问题:

如何使用docplex(python)在优化问题中建模约束?

梁建德
2023-03-14

我需要解决一个类似背包问题的最佳化问题。我在这篇文章中详细描述了最佳化问题:动态变量背包优化我实际上需要使用python而不是OPL,所以我安装了docplex和clpex包,以便使用cplex优化框架

这是我想用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);
}

这是我的第一次代码尝试:

from collections import namedtuple

from docplex.mp.model import Model


# -------------------------------------------------------------------- 

# Initialize the problem data
# --------------------------------------------------------------------

Categories_groups = {"Carbs": ["Meat","Milk"],"Protein":["Pasta","Bread"], "Fat": ["Oil","Butter"]}
Groups_Products = {"1":["Product11","Product12"], "2": ["Product21","Product22","Product23"], "3":["Product31","Product32"],"4":["Product41","Product42"], "5":["Product51"],"6":["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=[1,1,0];
Ug=[0.8,0.2,0.1,1,0.01,0.6];
budget=3;



def build_diet_model(**kwargs):


    allcategories = Categories_groups.keys()
    allgroups = Groups_Products.keys()
    prices=Products_Prices.values()

    # Model
    mdl = Model(name='summary', **kwargs)


    for g, products in Groups_Products.items():
        xg = mdl.sum(z[p] for p in products)# this line is not correct as I dont know how to add the condition like in the OPL code, and I was unable to model the variable z and add it as decision variable to the model.


   mdl.add_constraint(mdl.sum(Products_Prices[p] * z[p] for p in Products_Prices.keys() <= budget)
   mdl.maximize(mdl.sum(Uc[c] * xc[c] for c in Categories_groups.keys()) + 
   model.sum(xg[g] * Uc[c] * Ug[g] for c, groups in Categories_groups.items() for g in groups))
   mdl.solve()

if __name__ == '__main__':


    build_diet_model()

我实际上不知道如何正确地建模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_<hostname>.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")

我希望这能帮助像我这样的初学者解决同样的问题。

共有1个答案

朱鹏
2023-03-14

如果我正确理解了您的数据模型(我不确定您的示例中的数据是否一致(类别\u组和组\u产品没有相同的“组”值集合),决策变量和表达式的定义如下所示:

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}

这里,“z”决策变量被定义为字典。然后可以很容易地对其进行索引。

您还可以在此处找到有关编写docplex模型的文档:https://rawgit.com/IBMDecisionOptimization/docplex-doc/master/docs/mp/creating_model.html

请注意,如果您需要构建处理大型数据集的模型,那么使用pandas来定义复杂的切片可能更有效。

 类似资料:
  • 以这个二次约束为例: 注意,在CPLEX Python API中,上述约束的形式如下: 如何使用DOcplex而不是CPLEX Python API将上述二次约束添加到模型中?

  • 由于 PLY 从文档字串中获取信息,语法解析和词法分析信息必须通过正常模式下的 Python 解释器得到(不带 有-O 或者 -OO 选项)。不过,如果你像这样指定 optimize 模式: lex.lex(optimize=1) yacc.yacc(optimize=1) PLY 可以在下次执行,在 Python 的优化模式下执行。但你必须确保第一次执行是在 Python 的正常模式下进行,一旦

  • 问题内容: Python可以在优化模式(-O)下运行脚本,该脚本可以关闭诸如assert之类的调试,并且如果我记得还可以删除文档字符串。我没有看到它真正使用过,也许这只是过去时代的产物。正在使用吗?做什么的? 为什么在Python 3中没有删除这个无用的东西? 问题答案: 如果您分发仅包含文件的任何存档形式,它将节省少量内存和少量磁盘空间。(如果您使用很多,并且可能在复杂的条件下使用,那么节省下来

  • 我想找到配对的数量,一个很大的数字。如果我给数字n,并要求确定配对的数量,这样 <代码>S(x) 而constants是

  • 问题内容: 我已经在python中编写了一个函数来计算高斯扩展中的Delta函数,该函数涉及4级循环。但是,效率非常低,以类似方式比使用Fortran慢约10倍。 我删除了一些常量以使其看起来更简单。 有谁能帮助我优化此脚本以提高效率? 问题答案: 只需编译 为了获得最佳性能,我建议使用Numba(易于使用,性能良好)。另外,Cython可能是一个好主意,但是对您的代码进行了更多更改。 实际上,您

  • 在不同的限制条件下,我试图挑选最好的梦幻足球队。我的目标是挑选能够最大化其预测积分总和的球员。 制约因素是: 1) 团队必须包括: -1个QB -2苏格兰皇家银行 -2个WRs -1 TE 2)玩家的风险不得超过6 3) 球员的费用总额不得超过300英镑。 如何做到这一点?R中优化这些约束的最佳包/函数是什么?在给定这些约束的情况下,最大化投影点的函数调用会是什么样子?仅供参考,我将搜索100-3