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

问题描述 投票:0回答:1

我正在使用'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

我如何得到它也让我回归所有这些?

r linear-programming lpsolve
1个回答
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'包中内置的另一种方法,我仍然很想知道。

© www.soinside.com 2019 - 2024. All rights reserved.