【问题标题】:Python equivalent to R's lpSolve for Linear ProgrammingPython 等价于 R 的 lpSolve 用于线性规划
【发布时间】:2019-06-20 06:20:28
【问题描述】:

我正在将代码从 R 转换为 Python,并且正在寻找解决线性规划问题的最简单方法的帮助。找了很久,似乎没有对最好用的模块达成共识。

在此示例中,我只想选择 5 个选项中的 3 个,最大化 obj,同时确保约束列高于 0:

obj = [np.random.uniform(0, 100) for _ in range(5)]
col1 = [1] * 5
col2 = [np.random.uniform(0, 100) for _ in range(5)]
col3 = [np.random.uniform(0, 100) for _ in range(5)]
col4 = [np.random.uniform(0, 100) for _ in range(5)]
col5 = [np.random.uniform(0, 100) for _ in range(5)]
col6 = [np.random.uniform(0, 100) for _ in range(5)]

ConstraintMatrix = pd.DataFrame(data = {'col1': col1, 'col2': col2, 'col3': col3, 'col4': col4, 'col5': col5, 'col6': col6})
ConstraintDirections = ['==', '>=', '>=', '>=', '>=', '>=']
ConstraintValues = [3, 0, 0, 0, 0, 0]

在 R 中,为了获得最大化目标的 3 个项目,我只需运行:

library(lpSolve)
sol <- lpSolve::lp("max",
                   objective.in = obj,
                   const.mat    = t(ConstraintMatrix), # Transpose matrix
                   const.dir    = ConstraintDirections,
                   const.rhs    = ConstraintValues,
                   all.bin      = T # decision variables are all binary
)

ConstraintMatrix$selected <- sol$solution[1:nrow(ConstraintMatrix)]
ConstraintMatrix <- ConstraintMatrix[ConstraintMatrix$selected == 1,]

显然,这个问题不需要线性规划来解决,但它说明了我正在从 Python 中寻找什么来解决我更大的问题。有没有像我的lpSolve:lp 一样接受目标、约束矩阵、方向向量和值向量并输出解决方案的 Python 函数?

【问题讨论】:

    标签: python linear-programming lpsolve


    【解决方案1】:

    我猜Pulp 会很好地为您服务。

    当您尝试解决二进制问题时,请检查以下内容:

    1. 纸浆的set partitioning example
    2. 纸浆的Sudoku example
    3. 相关SO question

    【讨论】:

    • 另外值得一试的是pyomo
    • @abhiieor 哇,我从来没有听说过这个。看起来不错。谢谢!
    猜你喜欢
    • 2017-04-22
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多