5

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.objective.set_sense(my_prob.objective.sense.minimize)
my_prob.linear_constraints.add(lin_expr = rows, senses = ["LLL"], rhs = my_rhs)
my_prob.solve()
my_prob.solution.get_values()

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...

independentvariable
  • 3,980
  • 10
  • 36
  • CVXPY might suit your needs. It supports CPLEX. amomg other solvers. Example LP at https://www.cvxpy.org/examples/basic/linear_program.html . – Mark L. Stone Jan 08 '20 at 18:30
  • The reason I am trying this is that CVXPY is slow. – independentvariable Jan 08 '20 at 18:30
  • 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) – EhsanK Jan 08 '20 at 18:55
  • May I ask you the difference of CPLEX and doCPLEX modules? Both are from IBM aren't they? Also, which is faster? I really need speed at this point. – independentvariable Jan 08 '20 at 19:00
  • 2
    Someone actually asked the same over SO ;). You can also check what IBMers said here – EhsanK Jan 08 '20 at 19:23
  • 1
    @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 – independentvariable Jan 08 '20 at 19:44

1 Answers1

5

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')

mdl.minimize(x1+x2)

mdl.solve()

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

which gives

x1  =  3.5
x2  =  2.0
Alex Fleischer
  • 4,000
  • 5
  • 11