How to convert a float to a binary variable in docplex?

Viewed 336

After creating a model and solving the LP with some specialized cuts, I want to solve the IP version of the problem but changing the type of certain variables. In JAVA this uses the function:

IloConversion conversion(IloNumVar var, IloNumVarType type) throws IloException

What is the equivalent in DOCPLEX?

2 Answers

The corresponding API in DOcplex is not documented yet, as it is not well tested enough. This said, you can try

myvar.set_vartype('I')

To switch a variable to integer type (or 'B') for binary. This code is provided as-is for now. Le us know if this works for you. This method accepts either variable type instances (e.g. model.binary_vartype) or one-letter string ('B', 'I', 'C', 'S' for semi continuous, 'N" for semi-integer)

In this sample, I maximize the sum of four binaries , whose sum is less than 3.5.
When I change their type to continuous, one of them is set to 0.5 and the objective is equal to 3.5

code:

def test_vartype():
    m = Model()
    m.environment.print_information()
    bs = m.binary_var_list(4, name='b')
    sumbs = m.sum(bs)
    m.add(sumbs <= 3.5)
    m.maximize(m.sum(bs))
    s1 = m.solve()
    assert s1
    s1.display()

    # now switch
    for b in bs:
        b.set_vartype(m.continuous_vartype)
    # m.print_information()
    s2 = m.solve(log_output=False)
    m.report()
    s2.display()

and the output is:

* Python version 3.7.7, located at: C:\python\anaconda2020.02\envs\docplex_dev37\python.exe
* docplex is present, version is 2.19.0
* CPLEX library is present, version is 20.1.0.0, located at: C:\OPTIM\cplex_distrib\cplex2001R1\python\3.7\x64_win64
* pandas is present, version is 1.0.3
* numpy is present, version is 1.18.1
solution for: docplex_model1
objective: 3
b_0 = 1
b_1 = 1
b_2 = 1
* model docplex_model1 solved with objective = 3.500
solution for: docplex_model1
objective: 3.500
b_0 = 1.000
b_1 = 1.000
b_2 = 1.000
b_3 = 0.500
Related