r - 如何在使用 R 和 lpSolve 的混合整数线性程序中编码 .. 选择 Y 中的最佳 X 选择(最小值或最大值)..
问题描述
我正在尝试使用二元约束来解决与优化相关的练习。下面是问题的描述。
对于我正在使用的这个问题R
-lpSolveAPI
到目前为止,我设法将问题转换为约束列表并为问题构建正确的目标函数,但是我的程序没有产生正确的输出,因为我将三个Y
变量(yE
和yT
)yN
放入我的目标函数。我的目标函数不应该包含三个尾随0
(参见上图目标函数的定义)。
我的问题是,如何定义变量y
,使它们是二进制的并且仅用作约束的一部分(因此它们不会出现在目标函数中)?
# SELECT FROM ....
require(lpSolveAPI)
# Set the decision variables
obj <- c(21, 22.5, 22.5, 24.5, 23, 25.5, 0, 0, 0)
# Set the constrains parameters
# EG,EK,TG,TK,NG,NK,yE,yT,yN
LHS <- matrix(c(1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 0, 1, 0, 1, 0, 0, 0, 0,
0, 1, 0, 1, 0, 1, 0, 0, 0,
1, 1, 0, 0, 0, 0, -425, 0, 0,
0, 0, 1, 1, 0, 0, 0, -400, 0,
0, 0, 0, 0, 1, 1, 0, 0, -750,
0, 0, 0, 0, 0, 0, 1, 1, 1), nrow=9, byrow = TRUE)
RHS <- c(425, 400, 750, 550, 450, 0, 0, 0, 2)
constranints_direction <- c("<=", "<=", "<=", ">=", ">=", "<=", "<=", "<=", "<=")
# Set 9 constraints and 9 decision variables ==> THERE SHOULD BE ONLY 6 !!!
lprec <- make.lp(nrow = 9, ncol = 9)
# Set the type of problem we are trying to solve
lp.control(lprec, sense="min")
set.type(lprec, 7:9, c("binary"))
set.objfn(lprec, obj)
add.constraint(lprec, LHS[1, ], constranints_direction[[1]], RHS[1])
add.constraint(lprec, LHS[2, ], constranints_direction[[2]], RHS[2])
add.constraint(lprec, LHS[3, ], constranints_direction[[3]], RHS[3])
add.constraint(lprec, LHS[4, ], constranints_direction[[4]], RHS[4])
add.constraint(lprec, LHS[5, ], constranints_direction[[5]], RHS[5])
add.constraint(lprec, LHS[6, ], constranints_direction[[6]], RHS[6])
add.constraint(lprec, LHS[7, ], constranints_direction[[7]], RHS[7])
add.constraint(lprec, LHS[8, ], constranints_direction[[8]], RHS[8])
add.constraint(lprec, LHS[9, ], constranints_direction[[9]], RHS[9])
# Display the LPsolve matrix
lprec
get.type(lprec)
# Solve problem
solve(lprec)
# Get the decision variables values
get.variables(lprec)
# Get the value of the objective function
get.objective(lprec)
此代码产生目标输出 22850
> # Get the decision variables values
> get.variables(lprec)
[1] 0 425 0 0 550 25 1 0 1
> # Get the value of the objective function
> get.objective(lprec)
[1] 22850
但是,对于相同的变量分配,它必须产生 22850.50。
解决方案
如果您要运行:
obj <- c(21, 22.5, 22.5, 24.5, 23, 25.5)
x <- c(0, 425, 0, 0, 550, 25)
obj %*% x
你会看到:
[,1]
[1,] 22850
即这个分配给出了22850的目标。
推荐阅读
- javascript - 顶点交互式网格中的金额值
- javascript - 如何将数组显示为选项标签
- javascript - 我如何创建“临时 html”并加载它?
- google-cloud-platform - 我们可以使用基于用户地理位置的 GCP 的 L7 HTTPS 负载均衡器对后端进行地理定位吗?
- android - Firebase 消息传递组件不存在
- python - 从 pptx 获取超链接文本
- python - 在 for 循环中运行函数
- karate - 空手道 UI:运行多个功能文件时出现驱动程序配置/启动失败错误
- javascript - 如何设置有条件的多个细节面板?
- visual-studio - 以编程方式在 Visual Studio 中禁用断点