Pass a string for objective function in CVXR

81 views Asked by At

I am trying to write a wrapper function around CVXR, such that the 'objective' and 'constraint' can be passed by a function. I using the following example:

Example:

x1 <- Variable(1)      # a scalar
x2 <- Variable(1)      # a scalar

objective   <- Minimize( x1^2 + x2^2 ) 
constraints <- list(x1 <= 0, x1 + x2 == 0)
problem     <- Problem(objective, constraints)

## Checking problem solution

solution <- solve(problem) 

My attempt so far:

foo <- function(vars, const, obj) {
# for testing these values are passed inside
 vars = c("x1", "x2")
 obj = "x1^2 + x2^2"
 const = "(x1 <= 0, x1 + x2 == 0)"

  for(i in 1:length(vars)) {assign(vars[i], Variable(1, name = vars[i]))}

 objective <- eval(paste("Minimize(", obj, ")"))
}

Problem:

The objective variable does not evaluate as x1^2 + x2^2, but with quotes. I have tried as.formula, eval, substitute etc.

1

There are 1 answers

0
ThomasIsCoding On BEST ANSWER

Maybe you can try parse with eval like below

foo <- function(vars, const, obj) {
    # for testing these values are passed inside
    vars <- c("x1", "x2")
    obj <- "x1^2 + x2^2"
    const <- "(x1 <= 0, x1 + x2 == 0)"

    for (i in 1:length(vars)) {
        assign(vars[i], Variable(1, name = vars[i]))
    }

    objective <- eval(parse(text = paste("Minimize(", obj, ")")))
    constraints <- eval(parse(text = paste("list", const)))
    problem <- Problem(objective, constraints)
    solve(problem)
}