【问题标题】:How to get lpsolveAPI to return all possible solutions?如何让 lpsolveAPI 返回所有可能的解决方案?
【发布时间】:2019-03-31 21:48:07
【问题描述】:

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

我如何得到它也将所有这些都归还给我?

【问题讨论】:

  • 嗨@chinsoon12。不完全重复。这是针对包“lpSolve”的。我正在尝试使用包“lpSolveAPI”执行相同的过程,因为 R 也因“lpSolve”而崩溃(我相信它是内存问题)。尽管名称非常接近,但它们在输入方面的工作方式却大不相同。我无法对该线程发表评论,否则我会询问“lpSolveAPI”是否存在类似的过程。谢谢。

标签: r linear-programming lpsolve


【解决方案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”包中内置的另一种方法,我仍然很想知道。

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    相关资源
    最近更新 更多