How to get lpsolveAPI to return all possible solutions?

♀尐吖头ヾ 提交于 2019-12-20 05:52:23

问题


I am using 'lpSolveAPI' to solve multiple binary linear programming problems in R. How do I get it too return ALL the variable combinations for a maximizing problem.

Ive searched the documentation and can not find a command for this. Trying to switch from package 'lpSolve' as it inconsistently crashes R.

Here's an example problem:

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)

This returns:

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

I know that this problem has 6 possible solutions:

[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

How do I get it too return all of these too me?


回答1:


Discovered that this was dupe with: Get multiple solutions for 0/1-Knapsack MILP with lpSolveAPI

Here is the code I used to solve this adapted from the link:

# 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

This finds all six solutions:

> 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   

Sorry for the dupe everyone. If anyone knows another way built into the 'lpSolveAPI' package I'd still love to know.



来源:https://stackoverflow.com/questions/55445759/how-to-get-lpsolveapi-to-return-all-possible-solutions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!