首页 > 解决方案 > 如何在使用 R 和 lpSolve 的混合整数线性程序中编码 .. 选择 Y 中的最佳 X 选择(最小值或最大值)..

问题描述

我正在尝试使用二元约束来解决与优化相关的练习。下面是问题的描述。

供应链 - 基本 BIP

对于我正在使用的这个问题R-lpSolveAPI到目前为止,我设法将问题转换为约束列表并为问题构建正确的目标函数,但是我的程序没有产生正确的输出,因为我将三个Y变量(yEyTyN放入我的目标函数。我的目标函数不应该包含三个尾随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。

标签: roptimizationlpsolve

解决方案


如果您要运行:

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的目标。


推荐阅读