【问题标题】:print the result in decision binary variables在决策二元变量中打印结果
【发布时间】:2020-12-10 23:19:09
【问题描述】:

我使用 Docplex 库在 python 中开发了以下代码来求解最佳模型:

import docplex.mp.model as cpx
import docplex
import cplex
import random
import pandas as pd


C = 10
I = 5
T = 10
R = [[2, 3, 4, 5, 6],[3, 4, 5, 6, 7],[4, 5, 6, 7, 8],[5, 6, 7, 8, 9],[6, 7, 8, 9, 10],[2, 3, 4, 5, 6],[3, 4, 5, 6, 7],[4, 5, 6, 7, 8],[5, 6, 7, 8, 9],[6, 7, 8, 9, 10],[0, 0, 0, 0, 0]]
lambd = [[1, 2, 1, 3, 2],[3, 2, 3, 1, 4],[2, 4, 2, 1, 3],[3, 4, 2, 4, 1],[2, 3, 4, 1, 3],[1, 2, 1, 3, 2],[3, 2, 3, 1, 4],[2, 4, 2, 1, 3],[3, 4, 2, 4, 1],[2, 3, 4, 1, 3],[0, 0, 0, 0, 0]]

alpha = 0.5
n = {(t,i): 0 for i in range(I) for t in range(T)}

print (n)
print("\n")

#generation ni e vi
for t in range(T):
    for i in range(I):
        if R[t][i] == 0:
            n[(t,i)] = 0
        else:
            n[(t,i)] = (alpha*(R[t][i]/C))+((1-alpha)*((R[t][i]-lambd[t][i])/R[t][i]))

print (n)
print("\n")

opt_model = cpx.Model(name="MAB model")

#define decision variables
a  = {(t,i): opt_model.binary_var(name="x_{0}_{1}".format(t,i)) for i in range(I) for t in range(T)}

#define constraints
constraints = {t:opt_model.add_constraint(ct=opt_model.sum(lambd[t][i] * a[t,i] for i in range(I)) <= C, ctname="constraint_{0}".format(t)) for t in range(T)}

objective = opt_model.sum(a[t,i] * n[t,i] for i in range(I) for t in range(T))

# for maximization
opt_model.maximize(objective)


# solving with local cplex
opt_model.solve()


opt_model.print_information()

if not opt_model.solve():
    print("*** Problem has no solution")
    print("\n")
else:
    print("* model solved as function with objective: %g" % opt_model.objective_value)
    print("\n")

现在我想打印二元决策变量的结果,例如 a[1,1] = 1 a[1,2] = 0 ... 但是当我打印这个时:

print (a[t,i])

我有变量的名称,但没有像 1 或 0 这样的二进制值:

x_0_0

有人可以帮我吗?

谢谢你。

【问题讨论】:

  • 我也有同样的问题...
  • 这种模式下的结果是:``` x_0_0 x_1_0 x_2_0 x_3_0 x_4_0 x_5_0 x_6_0 x_7_0 x_8_0 x_9_0 x_0_1 x_1_1 x_2_1 x_3_1 ... ```
  • 在纸浆中我有一个返回这个值的函数:``` a[(t, i)].varValue ``` 但这在使用 Docplex 时不起作用
  • 您可以使用solution_value 属性访问变量的值

标签: python cplex docplex


【解决方案1】:

在你的模型中添加

sol = opt_model.solution
print (a[1,1]," = ",sol.get_value(a[1,1]))

你会得到

x_1_1  =  1.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多