如何获得lpsolveAPI返回所有可能的解决方案?

时间:2019-03-31 21:48:07

标签: r linear-programming lpsolve

我正在使用'lpSolveAPI'解决R中的多个二进制线性编程问题。如何获得它也返回所有变量组合以解决最大化问题。

我已经搜索了文档,但找不到用于此的命令。试图从软件包lpSolve切换,因为它不一致地导致R崩溃。

这是一个示例问题:

library(lpSolveAPI)

#matrix of constraints
A <- matrix(rbind(            
  c(1,1,0,0,0,0,0,0),        
  c(1,0,0,0,1,0,0,0),        
  c(0,0,1,0,0,1,0,0),         
  c(0,0,1,0,0,0,1,0),       
  c(0,0,1,0,0,0,0,1),        
  c(0,0,0,1,1,0,0,0),         
  c(0,0,0,0,0,0,1,1)), 7, 8)

#create an LP model with 7 constraints and 8 decision variables
num_con <- nrow(A)
num_points <- ncol(A)

lpmodel <- make.lp(num_con,num_points)

# all right hand
set.constr.type(lpmodel,rep("<=",num_con))

set.rhs(lpmodel, rep(1,num_con))

set.type(lpmodel,columns = c(1:num_points), "binary")

# maximize 
lp.control(lpmodel,sense="max")

# add constraints 
for (i in 1:num_points){
set.column(lpmodel,i,rep(1,length(which(A[,i]==1))),which(A[,i]==1))
}

set.objfn(lpmodel, rep(1,num_points))

solve(lpmodel)

get.variables(lpmodel)

这将返回:

"[1] 0 1 0 0 1 1 0 1"

我知道此问题有6种可能的解决方案:

[1]    0    1    0    0    1    1    0    1
[2]    1    0    0    1    0    1    0    1
[3]    1    0    0    1    0    1    1    0
[4]    0    1    0    1    0    1    0    1
[5]    0    1    0    1    0    1    1    0
[6]    0    1    0    0    1    1    1    0

我怎么也把所有这些都还给我?

1 个答案:

答案 0 :(得分:1)

发现这是由于以下原因造成的: Get multiple solutions for 0/1-Knapsack MILP with lpSolveAPI

这是我用来解决此问题的代码,摘自链接:

# find first solution
status<-solve(lpmodel) 
sols<-list() # create list for more solutions
obj0<-get.objective(lpmodel) # Find values of best solution (in this case four)
counter <- 0 #construct a counter so you wont get more than 100 solutions

# find more solutions
while(counter < 100) {
  sol <- get.variables(lpmodel)
  sols <- rbind(sols,sol)
  add.constraint(lpmodel,2*sol-1,"<=", sum(sol)-1) 
  rc<-solve(lpmodel)
  if (status!=0) break;
  if (get.objective(lpmodel)<obj0) break;
  counter <- counter + 1
}
sols

这找到所有六个解决方案:

> sols
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
sol 1    0    0    1    0    1    0    1   
sol 1    0    0    1    0    1    1    0   
sol 0    1    0    1    0    1    0    1   
sol 0    1    0    1    0    1    1    0   
sol 0    1    0    0    1    1    1    0   
sol 0    1    0    0    1    1    0    1   

对不起,每个人都被骗了。如果有人知道“ lpSolveAPI”包中内置的另一种方法,我仍然很想知道。