Search code examples
python-3.xcplexdocplex

Implementing Soft rules on CPLEX


I have a model that I need to add a new constriant to it but I want this rule to be implemented "only" if it is possible. Is there a way to implement this with cplex or docplex ?


Solution

  • You may use slacks to make a constraint soft:

    from docplex.mp.model import Model
    
    mdl = Model(name='buses')
    nbbus40 = mdl.integer_var(name='nbBus40')
    nbbus30 = mdl.integer_var(name='nbBus30')
    slack=mdl.integer_var(name='slack')
    mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
    mdl.add_constraint(nbbus40+nbbus30<=7+slack,'softconstraint')
    
    mdl.minimize(nbbus40*500 + nbbus30*400+10000*slack)
    
    mdl.solve()
    
    mdl.export("c:\\temp\\buses.lp")
    
    for v in mdl.iter_integer_vars():
        print(v," = ",v.solution_value)
    

    which gives

    nbBus40  =  6.0
    nbBus30  =  2.0
    slack  =  1.0
    

    why not trying logical constraints if then ?

    https://github.com/AlexFleischerParis/zoodocplex/blob/master/zooifthen.py

    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(nbbus40*500 + nbbus30*400)
    
    mdl.solve()
    
    for v in mdl.iter_integer_vars():
       print(v," = ",v.solution_value)
    
    print()
    print("with if nb buses 40 more than 3  then nbBuses30 more than 7")
    
    #if then constraint
    mdl.add(mdl.if_then(nbbus40>=3,nbbus30>=7))
    mdl.minimize(nbbus40*500 + nbbus30*400)
    
    mdl.solve()
    
     
    
    for v in mdl.iter_integer_vars():
        print(v," = ",v.solution_value) 
    
    '''
    which gives
    nbBus40  =  6.0
    nbBus30  =  2.0
    with if nb buses 40 more than 3  then nbBuses30 more than 7
    nbBus40  =  0
    nbBus30  =  10.0
    '''