use*_*652 5 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
Run Code Online (Sandbox Code Playgroud)
我不认为你可以在这两个包之间混合(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
Run Code Online (Sandbox Code Playgroud)
基于对项目网站的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])
}
Run Code Online (Sandbox Code Playgroud)
现在,我们可以解决并观察解决方案:
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
Run Code Online (Sandbox Code Playgroud)
回到问题,我们现在可以将其写入文件:
write.lp(x2, "myfile.lp")
Run Code Online (Sandbox Code Playgroud)
这是文件的内容:
/* Objective function */
min: +C1 +2 C2;
/* Constraints */
R1: +C1 >= 1;
R2: +C2 >= 1;
Run Code Online (Sandbox Code Playgroud)