5

有没有办法让 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 包提供所有可能的解决方案。为什么当所有变量都是整数时它不能重复相同...

4

1 回答 1

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.
于 2015-09-29T01:45:50.393 回答