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

标签 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"] 是什么意思?类似的事情是在另一种方法中填充(按列)。

提前致谢!

最佳答案

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

关于python - 使用 Cplex 在 Python 中构建线性程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24546313/

相关文章:

java - 如何用Java设计一个资源关联问题

oop - 如何以面向对象的方式对商店的营业时间进行建模?

python - 解决没有变量的Python Pulp

optimization - 如何加速 GLPK 求解 MIP 模型

python-2.7 - Pyomo 找不到 GLPK 求解器

Python MIME 文本格式

python - 在python中交换字符串中的字母

python - 拟合分布、拟合优度、p 值。是否可以使用 Scipy (Python) 做到这一点?

Python TKInter 破坏不工作

java - Ecore 建模生成一个 HashMap dto 持有一个 HashMap