0

在使用 docplex 解决优化问题后,我实际上在访问解决方案时遇到了问题。

下面我发布我正在使用的完整代码,只要我得到的结果(结果被注释):

优化问题在这篇文章优化问题中得到了充分的解释

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=[1,1,0];
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}

Ug ={"Product11":1,"Product12":4, "Product21":1,"Product22":3,"Product23":2,"Product31":4,"Product32":2,
                    "Product41":1,"Product42":3, "Product51": 1,"Product61":2,"Product62":1}
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='%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[p]  for c in allcategories for g in Categories_groups[c] for p in Groups_Products[g] ))

    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()

        '''
        Solution displayed using the line of code above
        * model solved as function:
        objective: 4.000
            "Product21"=1
            "Product11"=1
            "Product41"=1
        '''
        solution = mdl.solution

        for index, dvar in enumerate(solution.iter_variables()):
            print index, dvar.to_string()

        '''
        Solution displayed using the lines of code above
        0 Product21
        1 Product11
        2 Product41
        3 [Product12+Product11 ..]
        4 [Product22+Product21+..]
        5 [Product41+Product42 ..]
        6 [[Product12+Product11..]
        7 [[Product31+Product32..]

        '''

        # Save the CPLEX solution as "solution.json" program output
        with get_environment().get_output_stream("solution.json") as fp:
            mdl.solution.export(fp, "json")

所以我有两个问题:

  • 我不明白为什么函数 mdl.print_solution() 给出的结果与我在 mdl.solution 中枚举解决方案时不同
  • 实际上 mdl.print_solution() 给出了正确的解决方案,我的问题是如何获得解决方案列表,例如 [Product21,Product11,Product41]。这是我在 mdl.solution 中迭代解决方案时尝试做的事情,但它给了我与 mdl.print_solution() 不同的值

预先感谢您的帮助。问候。

4

1 回答 1

2

您的问题来自您访问解决方案对象上的变量值的方式。应该使用其中一个solution[dvar]solution.get_var_value(dvar)来检索变量值。这是一个示例来说明您的模型的输出:

for index, dvar in enumerate(solution.iter_variables()):
    print index, dvar.to_string(), solution[dvar], solution.get_var_value(dvar)

使用上面的代码行显示的解决方案:

    0 Product21 1.0 1.0
    1 Product11 1.0 1.0
    2 Product41 1.0 1.0
    3 [Product12+Product11 ..] 1.0 1.0
    4 [Product22+Product21+..] 1.0 1.0
    5 [Product41+Product42 ..] 1.0 1.0
    6 [[Product12+Product11..] 1.0 1.0
    7 [[Product31+Product32..] 1.0 1.0

模型对象上的print_solution()方法是漂亮打印解决方案的辅助方法。

问候。

于 2018-09-10T07:36:56.700 回答