0

I have an MIP model, which includes some sets of binary variables, e.g., y_{rnt}. Instead of having a loop over each index (like below), I would like to only print (an store) variables such that y_{rnt}=1. Does the docplex offer any function in python?

The example for identifying with multiple loops (inefficient):

# R, N, and T are inputs. We also have the solution as the output of the MIP model
x = 0
for r in range(1, R+1):
    for n in range(1, N+1):
        for t in range(1, T+1):
            if solution.get_value(y[r, n, t]) == 1:
                x = x + 1
mdslt
  • 155
  • 1
  • 10

1 Answers1

1

Assuming your y variables are defined as a variable dict, Docplex provides the get_value_dict method on a solution object. This method converts the variable dictionary into a value dictionary, with identical keys. In addition, if you pass keep_zeros=False then zero values are discarded.

Note that zero values are tested with a precision (default is 1e-6) as all values in Cplex are floating-point, including binary variable values. This means your above code might well "miss" binary variables the value of which would be output as 0.99999 by Cplex.

To summarize:

xd = sol.get_value_dict(vd, keep_zeros=False)

where vd is a variable dictionary, returns a new dictionary with identical keys, where values are non-zero values from sol. If you're only interested in the variables, use the keys of this dict.

Philippe Couronne
  • 826
  • 1
  • 5
  • 6