使用Cplex在Python中构建线性程序

时间:2014-07-03 06:21:57

标签: python modeling linear-programming cplex

我正在尝试解决具有大量变量和约束的线性程序。我需要动态生成约束矩阵并在python中构建lp。我可以在Cplex for 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"]是什么意思?类似的东西在另一种填充方法(按列)。

提前致谢!

1 个答案:

答案 0 :(得分:5)

所以我已经找到了上面的代码,只是发布它以防其他人: 变量的第一部分&#39; row&#39;,[0,&#34; x2&#34;,&#34; x3&#34;]只是指定要赋值的变量名称,[ -1.0,1.0,1.0],列在第二部分。有两种方法可以指定变量名,一种是通过索引,在这种情况下是0,另一种是直接命名,&#34; x2&#34;这里,这些名称以前是使用variables.add()。

添加到模型中的