如何将lp对象写入lp文件?

时间:2014-04-24 20:53:18

标签: r mathematical-optimization lpsolve

我一直在使用lpSolve和lpSolveAPI。我构建我的约束矩阵,目标函数等,并提供给lp函数,这很好用。我想使用write.lp将问题保存为lp文件,但我遇到了麻烦。我不断收到错误,告诉我该对象不是lp对象。有任何想法吗?

> x1 = lp(direction = "min", cost, A , ">=",r,,3:13, , , ,FALSE)
> class(x1)
[1] "lp"
>write.lp(x1, filename, type = "lp",use.names = c(TRUE, TRUE))

Error in write.lp(x1, filename, type = "lp", use.names = c(TRUE, TRUE)) : 
the lp argument does not appear to be a valid linear program record

1 个答案:

答案 0 :(得分:5)

我认为您可以在这两个软件包之间混合使用(lpSolveAPI无法导入或依赖lpSolve)。考虑lpSolve中的简单LP:

library(lpSolve)
costs <- c(1, 2)
mat <- diag(2)
dirs <- rep(">=", 2)
rhs <- c(1, 1)
x1 = lp("min", costs, mat, dirs, rhs)
x1
# Success: the objective function is 3

根据lpSolveAPI的{​​{3}},您可以使用以下内容执行相同的操作:

library(lpSolveAPI)
x2 = make.lp(0, ncol(mat))
set.objfn(x2, costs)
for (idx in 1:nrow(mat)) {
  add.constraint(x2, mat[idx,], dirs[idx], rhs[idx])
}

现在,我们可以解决并观察解决方案:

x2
# Model name: 
#             C1    C2       
# Minimize     1     2       
# R1           1     0  >=  1
# R2           0     1  >=  1
# Kind       Std   Std       
# Type      Real  Real       
# Upper      Inf   Inf       
# Lower        0     0       
solve(x2)
# [1] 0
get.objective(x2)
# [1] 3
get.variables(x2)
# [1] 1 1

回到这个问题,我们现在可以把它写到一个文件中:

write.lp(x2, "myfile.lp")

这里是文件的内容:

/* Objective function */
min: +C1 +2 C2;

/* Constraints */
R1: +C1 >= 1;
R2: +C2 >= 1;