簡體   English   中英

在 R 中設置線性規划調度問題

[英]Setting Up a Linear Programming Scheduling Problem in R

我在 Excel 中構建了一個線性規划調度問題,我想在 R 中重新創建它。

我有七個項目要安排在五個時期。 示例(非最佳)計划可能如下所示:

S <- matrix(c(0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0), nrow=5, ncol=7, byrow=TRUE)

> S
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0    0    1    0    0    0    0
[2,]    0    1    0    0    0    0    1
[3,]    1    0    0    0    0    0    0
[4,]    0    0    0    0    1    0    0
[5,]    0    0    0    1    0    1    0

其中每一列是一個項目,每一行是一個句點。 它們必須是已安排或未安排的二元選擇。

每個項目/期間選擇都帶有相關的“獎勵”。 這些獎勵是預先定義的,例如:

R <- matrix(c(1.78, .080, .46, 1.85, .18, .13, 2.65, 1.78, .080, .46, 3.15, .16, .13, 2.66, 1.78, .080, .40, 3.15, .16, .13, 2.17, 1.63, .072, .40, 3.06, .16, .12, 2.22, 1.66, .072, .40, 3.34, .16, .13, 2.19), nrow=5, ncol=7, byrow=TRUE)

> R
     [,1]  [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1.78 0.080 0.46 1.85 0.18 0.13 2.65
[2,] 1.78 0.080 0.46 3.15 0.16 0.13 2.66
[3,] 1.78 0.080 0.40 3.15 0.16 0.13 2.17
[4,] 1.63 0.072 0.40 3.06 0.16 0.12 2.22
[5,] 1.66 0.072 0.40 3.34 0.16 0.13 2.19

因此,在上面的示例[R]中,如果第一個[,1]項目安排在第五個周期[5,]中,它將獲得獎勵 = 1.66。

每個時期項目的獎勵是

> R*S
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0.00 0.00 0.46 0.00 0.00 0.00 0.00
[2,] 0.00 0.08 0.00 0.00 0.00 0.00 2.66
[3,] 1.78 0.00 0.00 0.00 0.00 0.00 0.00
[4,] 0.00 0.00 0.00 0.00 0.16 0.00 0.00
[5,] 0.00 0.00 0.00 3.34 0.00 0.13 0.00

我想將每個項目只安排一次,並且在一段時間內安排不超過兩個項目。 我想最大化獎勵。 IE,

max_select <- 2
# 
# maximize reward:
# maximize: sum([R]*[S])
# s.t.
# each item is only selected once:
# sum(S[,j]) = 1
# no more than two items selected per period:
# sum(S[i,]) <= max_select

我在使用lpSolveAPI進行設置時遇到了一些困難。

將目標 function 設置為 c(R),並將每個行索引 i 的約束設置為 c(row(R) == i),每個列索引 j 設置 c(col(R) == j)。 還將變量設置為二進制。

library(lpSolveAPI)

nr <- nrow(R)
nc <- ncol(R)
L <- make.lp(nr+nc, nr*nc)

set.objfn(L, c(R))
control <- lp.control(L, sense = "max")
for(i in 1:nr) add.constraint(L, c(row(R) == i), "<=", 2)
for(j in 1:nc) add.constraint(L, c(col(R) == j), "=", 1)
for(k in seq_along(R)) set.type(L, k, type = "binary")

solve(L) # 0 means succeeded
## [1] 0

matrix(get.variables(L), nr, nc)
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
## [1,]    0    1    0    0    1    0    0
## [2,]    0    0    1    0    0    0    1
## [3,]    1    0    0    0    0    1    0
## [4,]    0    0    0    0    0    0    0
## [5,]    0    0    0    1    0    0    0

get.objective(L)
## [1] 8.63

# check that we got a larger objective value than S
sum(R * S)
## [1] 8.61

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM