I'm trying to create two constraints in CPLEX (using python): one using the variable X, and the other using abs(X). Something like:
x > 0
abs(x) > 0
Should I create a new constraint Y that receives the value of abs(X), or is it possible to include abs(X) directly in "linear_constraints.add"?
The code below is not functional:
from cplex import Cplex, SparsePair
constraints = [{'abs(X)': 1},{'X': 1}]
exprs = [SparsePair(ind=list(constr.keys()), val=list(constr.values())) for constr in constraints]
model.linear_constraints.add(lin_expr=exprs, names=['constr_1','constr_2'])
Any ideas? Thank you.
CodePudding user response:
tiny example with docplex python API
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')
#absolute value of nbBus40 - nbBus30
mdl.add_constraint(mdl.abs(nbbus40-nbbus30)<=2)
mdl.minimize(nbbus40*500 nbbus30*400)
mdl.solve(log_output=True,)
for v in mdl.iter_integer_vars():
print(v," = ",v.solution_value)