4

I'm trying to solve a linear program with large number of variables and constraints. I need to dynamically generate the constraint matrices and build the lp in python. The only tutorial i can find on Cplex for Python is the official one from IBM, which isn't quite elaborated. So my questions are: First, a general question, is there a better tutorial or something that is well documented? Second, a more specific question, in the official tutorial, there is an example showing different method to populate a lp, the problem statement is:

Maximize
x1  + 2x2 + 3x3
subject to
–x1 +  x2 + x3 <= 20
x1 – 3x2 + x3 <= 30
with these bounds
0 <= x1 <= 40
0 <= x2 <= infinity
0 <= x3 <= infinity

and populate by row looks like:

def populatebyrow(prob):
    prob.objective.set_sense(prob.objective.sense.maximize)

# since lower bounds are all 0.0 (the default), lb is omitted here
prob.variables.add(obj = my_obj, ub = my_ub, names = my_colnames)

# can query variables like the following:

# lbs is a list of all the lower bounds
lbs = prob.variables.get_lower_bounds()

# ub1 is just the first lower bound
ub1 = prob.variables.get_upper_bounds(0) 

# names is ["x1", "x3"]
names = prob.variables.get_names([0, 2])

rows = [[[0,"x2","x3"],[-1.0, 1.0,1.0]],
        [["x1",1,2],[ 1.0,-3.0,1.0]]]


prob.linear_constraints.add(lin_expr = rows, senses = my_sense,
                            rhs = my_rhs, names = my_rownames)

# because there are two arguments, they are taken to specify a range
# thus, cols is the entire constraint matrix as a list of column vectors
cols = prob.variables.get_cols("x1", "x3")

So, what is the variable rows taking? I can get the second part for the coefficients, but what does the first part [0,"x2","x3"] mean? and similar thing is in the other method to populate (by column).

Thanks in advance!

mattmilten
  • 6,242
  • 3
  • 35
  • 65
user3800276
  • 91
  • 1
  • 4
  • When I see this sort of example my answer is "just use Gurobi for Python MIP work". Cmon CPLEX... is it really that hard to implement the overrides so that you can write out legible math equations with Python code? – Pete Cacioppi Aug 29 '15 at 00:19

1 Answers1

5

So I've figured out the code above, just posting it in case it help others: the first part of the variable 'row',[0,"x2","x3"],is just specifying the variable names to be assigned a value,[-1.0, 1.0,1.0], which is listed in the second part. There are 2 ways to specify the variable name, one is by its index, 0 in this case, and the other is by name directly, "x2" here, these names are previously added to the model using variables.add().

user3800276
  • 91
  • 1
  • 4
  • I was just staring at this for like an hour. Thank you so much! Btw, in case you get this wrong, cplex seems to just produce a very much not helpful "MemoryError". – srs Jul 08 '15 at 14:37