在Python中使用Cplex构建线性规划
我正在尝试解决一个包含大量变量和约束的线性规划问题。我需要在Python中动态生成约束矩阵并构建线性规划模型。我找到的关于IBM Cplex在Python中使用的教程只有官方的那个,但内容并不是很详细。所以我有几个问题:
首先,我想问一下,是否有更好的教程或者文档更完善的资料?
其次,我有一个更具体的问题。在官方教程中,有一个示例展示了不同的方法来填充线性规划模型,问题描述是:
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 个回答
5
我已经搞明白了上面的代码,发出来希望能帮到其他人:变量 'row' 的第一部分,[0,"x2","x3"],其实就是在指定要赋值的变量名,第二部分是这些变量要赋的值,[-1.0, 1.0, 1.0]。指定变量名有两种方法,一种是通过索引,这里是0,另一种是直接用名字,这里是"x2"。这些名字之前是通过 variables.add() 添加到模型里的。