Lpsolve package in R

I use the lpsolve package for linear programming, but have read its tutorial, which only permits non-negative variables.

Here is my code:

 library(lpSolve) #linear programming solver c = c(30, 18, 20, 23, 24, 26) a = scan(text="66 89 82 14 35 72") b = 50 con.qual.s1=scan(text="64 98 17 55 27 80") con.qual.s2=scan(text="16 59 88 89 60 47") qual.cons=c(53,82) n=6 #activities m=3 #resources f.rhs = c(b,qual.cons) f.con <- matrix (rbind(a,con.qual.s1,con.qual.s2,diag.p),nrow=m+nrow(diag.p)) f.obj.d <- c(50,53,82) diag.d=diag(x = 1, m, m) #non-negativity f.con.d <- matrix (rbind(t(f.con[1:m,]),diag.d),nrow=n+nrow(diag.d)) f.dir.d <- c(rep("<=",7),rep(">=",2)) f.rhs.d <- c(c,rep(0,m)) of.d=lp ("max", f.obj.d, f.con.d, f.dir.d, f.rhs.d,compute.sens=TRUE) 

Note that it ignores the fact that restriction number 7 is not positive.

EDIT: I added new code for the lpSolveAPI package. To check what works, I prepared another code for the primary problem and the double problem.

DATA:

 c = c(30, 18, 20, 23, 24, 26) a = scan(text="66 89 82 14 35 72") b = 50 con.qual.s1=scan(text="64 98 17 55 27 80") con.qual.s2=scan(text="16 59 88 89 60 47") qual.cons=c(53,82) n=6 #activities m=3 #resources 

PRIMAL PROBLEM: (here we have no problems, because all variables must be non-negative)

 library(lpSolveAPI) lprec.p <- make.lp(0, n) f.con <- matrix (rbind(a,con.qual.s1,con.qual.s2),nrow=m) set.objfn(lprec.p, c) add.constraint(lprec.p, f.con[1,], "<=", f.rhs[1]) for (i in 2:m) { add.constraint(lprec.p, f.con[i,], ">=", f.rhs[i]) } ColNames <- c("x1", "x2", "x3", "x4","x5","x6") RowNames <- c("pi1", "pi2", "pi3") dimnames(lprec.p) <- list(RowNames, ColNames) lprec.p solve(lprec.p) get.objective(lprec.p) 

DOUBLE PROBLEM: (here we need the first variable to be non-positive, so use set.bounds )

 library(lpSolveAPI) lprec.d <- make.lp(0, m) lp.control(lprec.d,sense="max") f.con.d=matrix (cbind(a,con.qual.s1,con.qual.s2),ncol=m) set.objfn(lprec.d, f.rhs) for (i in 1:n) { add.constraint(lprec.d, f.con.d[i,], "<=", c[i]) } set.bounds(lprec.d, lower = c(-Inf), upper = c(0),columns = c(1)) RowNames <- c("x1", "x2", "x3", "x4","x5","x6") ColNames <- c("pi1", "pi2", "pi3") dimnames(lprec.d) <- list(RowNames, ColNames) lprec.d solve(lprec.d) get.objective(lprec.d) 
+4
source share
1 answer

If you use the lpSolveAPI library, as suggested on the lpsolve R page , it's pretty simple to use set.bounds / set_bounds to assign negative ratings to your variables.

For example, if you have three variables x1 , x2 and x3 with the following bounds:

 x1 >= 0 x2 <= 0 -5 <= x3 <= 10 

When using lpSolveAPI in R and assuming your problem is identified as lprec , you should specify this as:

 set.bounds(lprec, lower = c(0, -Inf, -5), upper = c(Inf, 0, 10), columns = c(1, 2, 3)) 
+6
source

Source: https://habr.com/ru/post/1481772/


All Articles