Stanley Gan
Stanley Gan

Reputation: 481

Adding constraints CPLEX Python API

The data that I am handling is not as simple as the ones in the documentation. As my variables basically depends on the data input file, I will use the following simple example to explain what I am trying to achieve. I have following constraints:

x1 + x2 + x3 = 1
x4 + x5 + x6 + x7 =1
x8 + x9 = 1

I am thinking of using a for loop to repeatedly call the c.linear_constraints.add() function. Is there a better way in doing this?

Upvotes: 4

Views: 3565

Answers (1)

rkersh
rkersh

Reputation: 4465

In general, you'll get better performance if you create batches of linear constraints rather than creating them one at a time. For example (using your example above), it's better to do the following:

import cplex
c = cplex.Cplex()
c.variables.add(names=["x{0}".format(i+1) for i in range(9)])
c.linear_constraints.add(lin_expr=[[[0, 1, 2], [1.0, 1.0, 1.0]],
                                   [[3, 4, 5, 6], [1.0, 1.0, 1.0, 1.0]],
                                   [[7, 8], [1.0, 1.0]]],
                         rhs=[1.0, 1.0, 1.0],
                         names=["c{0}".format(i+1) for i in range(3)])
c.write("example.lp")

This produces the following LP file:

Minimize
 obj:
Subject To
 c1: x1 + x2 + x3  = 1
 c2: x4 + x5 + x6 + x7  = 1
 c3: x8 + x9  = 1
End

So, it would be better to read in your input file, save the constraint information in some data structure (lists or whatever), and then call c.linear_constraints.add once at the end (or every X constraints if your input file is very large).

Upvotes: 2

Related Questions