Question

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
Was it helpful?

Solution

I don't think you can mix between these two packages (lpSolveAPI doesn't import or depend on lpSolve). Consider a simple LP in 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

Based on the project website for lpSolveAPI, you do the same thing with something like:

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])
}

Now, we can solve and observe the solution:

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

Getting back to the question, we can now write it out to a file:

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

Here's the contents of the file:

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

/* Constraints */
R1: +C1 >= 1;
R2: +C2 >= 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top