简体   繁体   English

如何在R中复制excel求解器

[英]How to replicate excel solver in R

I used excel solver to solve an optimization problem, and I am trying to replicate it in R. 我使用excel求解器来解决优化问题,我试图在R中复制它。

I found many packages like optim, ROI etc., but it seems all of them only take a vector as the object to optimize and allow the variables to take any continuous value. 我找到了许多软件包,如optim,ROI等,但似乎所有这些软件包只将一个向量作为优化对象并允许变量采用任何连续值。 In my case, I have a constraint matrix that also needs to be satisfied and my variables can only take binary values. 在我的例子中,我有一个约束矩阵,也需要满足,我的变量只能采用二进制值。

Here is problem I want to solve: 这是我想要解决的问题:

AD are machines, 1-3 are tasks and the number in the first matrix is the value generated by using X machine to do Y task. AD是机器,1-3是任务,第一个矩阵中的数字是使用X机器执行Y任务生成的值。 The constraints are: AD can do and only can do one task (cannot split); 约束是:AD可以做,只能做一个任务(不能拆分); each task can be worked and only be worked by one machine. 每个任务都可以工作,只能由一台机器完成。

Here is the code I am using: 这是我正在使用的代码:

par = rep(c(0,1),6)

mat <- matrix(c(9,10,11,4,5,10,1,3,5,7,5,4), nrow = 3)

fr <- function(x) {  
  y= matrix(x,nrow = 4)
  sum(mat %*% y)
}

a = optim(par, fr)

Some questions: How can I optimize maximum, seems this function default optimize minimum? 一些问题:如何优化最大值,这个函数默认优化最小值? How can I add constraints into it? 如何在其中添加约束? How can I limit to binary variables? 我怎样才能限制二进制变量?

You need to construct a vector for the objective function and a constraint matrix, finally solving with one of the R LP solvers: 您需要为目标函数和约束矩阵构造一个向量,最后使用其中一个R LP求解器求解:

library(lpSolve)
costs <- matrix(c(9, 10, 11, 4, 5, 10, 1, 3, 5, 7, 5, 4), nrow=3)
nr <- nrow(costs)
nc <- ncol(costs)
columns <- t(sapply(1:nc, function(x) rep(c(0, 1, 0), c(nr*(x-1), nr, nr*(nc-x)))))
rows <- t(sapply(1:nr, function(x) rep(rep(c(0, 1, 0), c(x-1, 1, nr-x)), nc)))
mod <- lp("max", as.vector(costs), rbind(columns, rows), "<=", rep(1, nr+nc), binary.vec=rep(TRUE, nr*nc))

Now you can grab the solution and the objective function: 现在您可以获取解决方案和目标函数:

mod$objval
# [1] 27
matrix(mod$solution, nrow=nr)
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    1
# [2,]    1    0    0    0
# [3,]    0    1    0    0

Note that functions like optim are not well suited for this problem both because they don't consider matrices of constraints and also because they cannot limit to binary variable values. 请注意,像optim这样的函数不适合这个问题,因为它们不考虑约束矩阵,也因为它们不能限制为二进制变量值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM