【问题标题】:linear goal programming in R unable to find solutionsR中的线性目标编程无法找到解决方案
【发布时间】:2016-12-07 20:48:50
【问题描述】:

我尝试使用R 解决以下线性目标规划问题:

我尝试使用R 以以下矩阵格式进行公式化:

下面是可重现的例子:

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

以下是我的问题:

  1. 解决方案不正确?我制定的有什么不正确的吗?
    1. 如何使用R 为上述目标编程制定nxn 矩阵。

【问题讨论】:

  • wi 有定义吗?

标签: r loops mathematical-optimization linear-programming


【解决方案1】:

这是一个使用lpSolveAPI 包的解决方案。对于 n=3,它给出了相同的结果。该代码也适用于较大的 n(和矩阵 A):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多