r-opt / rmpk

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

Minimizing the sum of square error #41

Closed mcanigueral closed 4 years ago

mcanigueral commented 4 years ago

Hi, as a continuation of issue #38 , I apply the following objective function in order to obtain an optimal variable (Vopt) the most similar as possible to PV vector (like Sum of square error, SSE):

I use quadprog solver with the following code:

v <- c(20, 15, 10, 15, 10, 20)
pv <- c(0, 10, 40, 40, 10, 0)
n <- length(v)
V <- sum(v)
model <- MIPModel(solver = ROI_solver("quadprog"))
opt_v <- model$add_variable(i = 1:n, type = "continuous", lb = 0)
model$set_objective(sum_expr((opt_v[i] - pv[i])^2, i = 1:n), "min")
model$add_constraint(sum_expr(opt_v[i], i = 1:n) == V)
model$optimize()
ov <- model$get_variable_value(opt_v [i]) %>% pull(value)

And I obtain: image

However, this is not the optimal solution since the curve that fits better the objective goal is that one (my_ov): image

my_ov <- c(0, 10, 40, 40, 0, 0)
sum((ov - pv)^2)
# 3025
sum((my_ov - pv)^2)
# 100

Is this a problem of the solver? I have tested the same with alabama and qpoases and I get the same. To be honest, I have never done it with other languages like Matlab or Python, so I don't have a reference. I'm just testing and learning now.

Thanks!

dirkschumacher commented 4 years ago

Thanks a lot. Will investigate!

dirkschumacher commented 4 years ago

The variables from get_variable_value have an undefined sorting. This will give you the correct ordering and a better solution than my_ov.

ov <- model$get_variable_value(opt_v [i])
ov <- ov[order(ov$i), "value"]
mcanigueral commented 4 years ago

Oh! Perfect, sorry for that!

dirkschumacher commented 4 years ago

Thanks for testing out the package!