linear goal programming in R unable to find solutions

空扰寡人 提交于 2019-12-24 06:33:31

问题


I have the following linear goal programming problem that I'm trying to solve using R:

I tried formulating using R in the following matrix format:

Below is the reproducible example:

library("lpSolve")
a <- matrix(c(1,2,5,
              1/2,1,3,
              1/5,1/3,1),nrow=3,byrow=T)

f.obj <- c(rep(1,6),rep(0,3))

f.cons <- matrix(c(c(1,-1,0,0,0,0,1,-1,0,
                     0,0,1,-1,0,0,1,0,-1,
                     0,0,0,0,1,-1,0,1,-1,
                     1,0,0,0,0,0,0,0,0,
                     0,1,0,0,0,0,0,0,0,
                     0,0,1,0,0,0,0,0,0,
                     0,0,0,1,0,0,0,0,0,
                     0,0,0,0,1,0,0,0,0,
                     0,0,0,0,0,1,0,0,0,
                     0,0,0,0,0,0,1,0,0,
                     0,0,0,0,0,0,0,1,0,
                     0,0,0,0,0,0,0,0,1)
),nrow=12,byrow=T)

f.dir <- c(rep("=",3),rep(">",9))

f.rhs <- c(c(log(a[1,2]),log(a[1,3]),log(a[2,3])),rep(0,9))

g <- lp ("min", f.obj, f.cons, f.dir, f.rhs)
g$solution

> g$solution
[1] 0.1823216 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 1.6094379 1.0986123 0.0000000

Below are my questions:

  1. The solution is incorrect ? Is there anything that I formulated is incorrect ?
    1. How can I formulate for an nxn matrix using R for the above goal programming.

回答1:


Here is a solution which uses the lpSolveAPI package. It gives the same result for n=3. The code should work for larger n (and matrix A) as well:

library(lpSolveAPI)
n <- 3
a <- matrix(c(1,2,5,1/2,1,3,1/5,1/3,1),nrow=n,byrow=T)
num_entries <- n*(n-1)/2

# set up lp    
lprec <- make.lp(0, ncol=2*num_entries+n) 
set.objfn(lprec, obj=c(rep(1,2*num_entries), rep(0,n)))

# add constraints
dim2idx <- function(xy, i, j, n=3) ifelse(xy=="x", 0, n*(n-1)/2) + n*(n-1)/2 - (n-i)*(n+1-i)/2 + (j-i)    
for (i in seq(1,n-1))
    for (j in seq(i+1,n)) 
        add.constraint(lprec, xt=c(1,-1,1,-1), indices=c(dim2idx("x", i,j), dim2idx("y", i,j), 2*num_entries+c(i,j)), type="=", rhs=log(a[i,j]))

# solve
solve(lprec)
exp(get.variables(lprec)) # solved for log x, so exp here


来源:https://stackoverflow.com/questions/41027092/linear-goal-programming-in-r-unable-to-find-solutions

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