I am trying to run the following optimization problem at Python by using the CPLEX API: $$\min \{x_1 + x_2\ | \ x_1 \geq 3, x_2 \geq 2, 2x_1 + x_2 \geq 9\} $$

I just want to give a matrix of coefficients and implement the problem as simple as possible. However, the easiest way I was able to do was:

import cplex
my_prob = cplex.Cplex()
my_obj = [1,1]
rows = [[["x1","x2"],[-1, 0]], [["x1","x2"],[0, -1]], [["x1","x2"],[-2,-1]]]
my_colnames = ["x1", "x2"]
my_rhs = [-3, -2, -9]
my_prob.variables.add(obj = my_obj, names = my_colnames)
my_prob.linear_constraints.add(lin_expr = rows, senses = ["LLL"], rhs = my_rhs)

My questions are:

  1. I really don't want to define each constraint of form [["x1","x2"],[1,0]], is there any way I can get rid of the naming? Because I will give huge matrices to CPLEX and I just want to have all the coefficients! I mean, my matrix will include all the variables' coefficients, so I really don't need to give which coefficient is for which variable.
  2. I don't want to give senses["LLL"] all the time, but default should stay $\leq$.

Edit for the first case, obviously I can define my_colnames in the beginning and all ["x1","x2"] can be replaced by my_colnames. But still...

  • $\begingroup$ CVXPY might suit your needs. It supports CPLEX. amomg other solvers. Example LP at cvxpy.org/examples/basic/linear_program.html . $\endgroup$ Commented Jan 8, 2020 at 18:30
  • $\begingroup$ The reason I am trying this is that CVXPY is slow. $\endgroup$ Commented Jan 8, 2020 at 18:30
  • $\begingroup$ You're using cplex. Try docplex (not that I know much about cplex package but I've only tried docplex and I've never had any problem with it defining my variables and constraints the way I wanted them and I had thousands of them) $\endgroup$
    – EhsanK
    Commented Jan 8, 2020 at 18:55
  • 2
    $\begingroup$ Someone actually asked the same over SO ;). You can also check what IBMers said here $\endgroup$
    – EhsanK
    Commented Jan 8, 2020 at 19:23
  • 1
    $\begingroup$ @EhsanK Perfect, seems like CPLEX API is faster. In the meantime, I fixed the code and solved my main problem. It is running way faster than with CVXPY $\endgroup$ Commented Jan 8, 2020 at 19:44

1 Answer 1


with the cplex docplex API you may write

from docplex.mp.model import Model

mdl = Model(name='test')

x1 = mdl.continuous_var(name='x1')
x2 = mdl.continuous_var(name='x2')

mdl.add_constraint(x1>=3, 'ct1')
mdl.add_constraint(x2>=2, 'ct2')
mdl.add_constraint(2*x1+x2>=9, 'ct3')



for v in mdl.iter_continuous_vars():
    print(v," = ",v.solution_value) 

which gives

x1  =  3.5
x2  =  2.0
  • $\begingroup$ Great! This is exactly what I’m used to do in GUROBI $\endgroup$ Commented Jan 15, 2020 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.