Search code examples
pythoncplexdocplex

print the result in decision binary variables


i have the following code developed in python using the library Docplex to solve an optimal model:

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

now I want to print the results of the binary decision variable, like a[1,1] = 1 a[1,2] = 0 ... but when I print this:

print (a[t,i])

I have the name of the variables and no the binary valeu like 1 or 0:

x_0_0

can someone help me?

thakyou.


Solution

  • in your model if you add

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

    you ll get

    x_1_1  =  1.0