R lpsolve查看完整LP的所有可能解决方案

时间:2015-02-19 00:52:58

标签: r optimization linear-programming lpsolve

有没有办法让lpSolve返回多个解决方案?在下面的情况下,我想要(5,0)和(0,5)两者。

如果lpSolve无法做到这一点,那么还有其他R包将返回积分线性优化程序的所有可能解决方案吗?

 library("lpSolve")
  A=matrix (c(1, 1), nrow=1, byrow=TRUE)

  b=(5)
  signs='=='
  c_=c(1,1)
  res = lpSolve::lp('max', c_, A, signs, b,  all.int = TRUE)
  res$solution

=============================================== ========================

我还想知道为什么lpSolve包提供所有可能的解决方案,如果所有决策变量都是二进制的。当所有变量都是整数时,为什么不能重复相同...

1 个答案:

答案 0 :(得分:3)

代码:

library(lpSolveAPI)

vBiv_of_v <- function (nbits,v){
   taillev<-length(v)
   taillevBivalent<-nbits*taillev
   vBivalent<-rep(0,taillevBivalent)

   for(iLg in seq(1,taillev)) {
     iCoef<-1
     for(iDelta in seq(1,nbits)){
       vBivalent[(iLg-1)*nbits+iDelta]<- iCoef*v[iLg]
       iCoef<-iCoef*2
     }
   }
   vBivalent
}

vBiv_to_v <- function (nbits,vBivalent) {
   taillevBivalent<-length(vBivalent)
   taillev<-taillevBivalent/nbits

   v<-rep(0,taillev)
   for(iLg in seq(1,taillev)) {
     for(iDelta in seq(1,nbits)){
       v[iLg]<-v[iLg]+2^(iDelta-1)*vBivalent[(iLg-1)*nbits+iDelta]
     }
   }
   v
}
nbVariable<-2
nbBits=3
nbVariableBivalentes<-nbVariable*nbBits
f.obj<-rep(0,nbVariableBivalentes)
mylp <- make.lp(0, nbVariableBivalentes)
set.objfn(mylp,f.obj)
add.constraint(mylp, vBiv_of_v(nbBits,c(1,1)), "=", 5)
set.type(mylp, 1:nbVariableBivalentes , type = "binary")

repeat {
  status<-solve(mylp)

  if(status == 0) {
    last_sol<-get.variables(mylp)

    vRes<-vBiv_to_v(nbBits,last_sol)
    cat(vRes[1],vRes[2],"\n")

    #add cutting
    new_rhs <- 0;
    f.condSup<-rep(0,nbVariableBivalentes)
    for (iCol in 1:nbVariableBivalentes) {
      f.condSup[iCol] <-  2 * last_sol[iCol] - 1
      new_rhs <- new_rhs + last_sol[iCol];
    }
    add.constraint(mylp, f.condSup, "<=", new_rhs - 1)
  }
  else if(status == 2) {
    cat("No more solution.\n") 
    break
  }
}

结果:

5 0
4 1
3 2
1 4
2 3
0 5
No more solution.