r-opt / rmpk

Mixed Integer Linear and Quadratic Programming in R
https://r-opt.github.io/rmpk/
Other
44 stars 4 forks source link

Error: non-numeric argument to binary operator #38

Closed mcanigueral closed 4 years ago

mcanigueral commented 4 years ago

Hi Dirk, Last week I discovered ompr and rmpk packages. Excellent work! I was testing rmpk with a quadratic optimization using quadprog as a solver.

My random environment variables are:

v <- c(20, 15, 10, 15, 10, 20)
pv <- c(0, 10, 40, 40, 10, 0)
n <- length(v)
V <- sum(v)

Where v could be an electricity demand profile and pv a solar generation profile. I want an optimal v (i.e. v_opt) that consumes the most as possible solar energy, so as example, my desired objective function would be:

where I need to square the difference between demand-generation in order to only obtain positive values and point out the corresponding difference.

Then, when I configure my model I obtain the following error:

model <- MIPModel(solver = ROI_solver("quadprog"))
opt_v <- model$add_variable(i = 1:n, type = "continuous", lb = 0)
model$add_constraint(sum_expr(opt_v[i], i = 1:n) == V)
model$set_objective(sum_expr((opt_v[i] - pv[i])^2, i = 1:n), "min")
# Error in (opt_v[i] - pv[i])^2 : non-numeric argument to binary operator

I guess that quadprog can't handle the square of a subtraction, since the square of just one variable is possible, but I have not found any other solver (from ROI plugins) that allows this objective function. Is it a problem of the solver? Is this objective function possible with rmpk?

Thanks in advance!

mcanigueral commented 4 years ago

I've seen now in file /R/quadratic-expression-methods.R the function:

ensure_quadratic_expression <- function(expr) {
  if ("RMPKQuadraticExpression" %in% class(expr)) {
    return(expr)
  }
  if ("RMPKQuadraticVariableTuple" %in% class(expr)) {
    return(expr + 0)
  }
  stop("expr is not well-formed", call. = FALSE)
}

And the error message comes from:

class(expr)

So, I see that it's not a matter of the solver. Let me reformulate the question: Is it possible to square any arithmetic operation in rmpk?

Thanks again!

dirkschumacher commented 4 years ago

Ah thanks. It's a bug. Will look into it.

dirkschumacher commented 4 years ago

Thanks for the report. I think it is fixed now. Let me know if you find any other issues (which there probably are :))

mcanigueral commented 4 years ago

Hi, it works now, thanks! I have another problem but I'll open another issue since it's not related to the error of this one.