使用Cplex在Python中构建线性规划问题

4
我正在尝试解决一个具有大量变量和约束条件的线性规划问题。我需要动态生成约束矩阵并在Python中构建lp。我能找到的唯一关于Cplex的Python教程是IBM官方提供的,但不是很详细。所以我的问题是: 首先是一个一般性问题,是否有更好的教程或者文档? 其次,更具体地说,在官方教程中,有一个示例展示了填充lp的不同方法,问题陈述如下:
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

并按行填充的样子如下:
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")

那么,变量rows取什么值呢?我可以得到系数的第二部分,但是第一部分[0,“x2”,“x3”]代表什么意思呢?另一种按列填充方法也有类似的情况。
谢谢提前!

当我看到这种示例时,我的答案是“只需在Python MIP工作中使用Gurobi”。加油CPLEX,难道实现覆盖以便您可以用Python代码编写可读的数学方程式真的那么困难吗? - Pete Cacioppi
1个回答

5
所以我已经理解了上面的代码,只是为了帮助其他人而发布它: 变量'row'的第一部分[0,“x2”,“x3”]只是指定要分配值的变量名称,[-1.0, 1.0,1.0]在第二部分中列出。有两种指定变量名称的方法,一种是通过其索引,本例中为0,另一种是直接通过名称,“x2”在这里,这些名称是先前使用variables.add()添加到模型中的。

我只是盯着这个看了一个小时。非常感谢!顺便说一下,如果你犯错了,cplex似乎只会产生一个非常不可靠的“MemoryError”。 - srs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接