5

I have been using lpSolve and lpSolveAPI. I build my constraint matrix, objective function etc and feed to the lp function and this works just fine. I want to save the problem as an lp file using write.lp and am having trouble. I keep getting an error telling me that the object is not an lp object. Any ideas?

> 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
4

1 回答 1

5

我认为您不能在这两个包之间混合使用(lpSolveAPI不导入或依赖lpSolve)。考虑一个简单的 LP lpSolve

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您可以通过以下方式执行相同的操作:

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;
于 2014-04-24T21:14:09.753 回答