Search code examples
pythoncplex

CPLEX program with absolute values in Python


I need to write a PL in python and solve it with CPLEX library but i'm a beginner and therefore i don't know how to write it in Python.

The program is:

MIN ΣΣ abs(Ui - Uj)        with i = 1, j = i + 1
subject to:
    Ui = Σ Wj * Xji        ∀i
    Xji is 0/1 integer     ∀i,j with i < j
    0.0 =< Ui <= T

Solution

  • abs is very easy to use with docplex.

    Let me change a bit the zoo example to use abs

    Suppose I want to get as close as possible to cost 3900

    from docplex.mp.model import Model
    
    mdl = Model(name='buses')
    nbbus40 = mdl.integer_var(name='nbBus40')
    nbbus30 = mdl.integer_var(name='nbBus30')
    mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
    mdl.minimize(mdl.abs(nbbus40*500 + nbbus30*400-3900))
    
    mdl.solve()
    
    for v in mdl.iter_integer_vars():
        print(v," = ",v.solution_value)