4

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I pre-generated the indices and fit into a single c.linear_constraints.add() fuction.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.