dirkschumacher / ompr

R package to model Mixed Integer Linear Programs
https://dirkschumacher.github.io/ompr/
Other
269 stars 35 forks source link

Solution ordering in R 3.x #404

Closed dkutner closed 2 years ago

dkutner commented 2 years ago

I'm running into an issue where ompr 1.0.1 sorts the resulting data frame by i treated as a character in R version 3.6.2. Here x[10] should be 2 with the remaining values 1, but instead x[2] is 2. The same code in R 4.0.3 behaves as expected.

> library(dplyr)
> 
> model <- ompr::MIPModel() %>% 
+     ompr::add_variable(x[i], i = 1:10, type = "continuous", ub = 2) %>% 
+     ompr::add_constraint(x[i] <= 1, i = 1:9) %>% 
+     ompr::set_objective(sum_over(x[i], i = 1:10))
> soln <- ompr::solve_model(model, ompr.roi::with_ROI(solver = "glpk"))
> ompr::get_solution(soln, x[i])
   variable  i value
1         x  1     1
10        x  2     2
2         x  3     1
3         x  4     1
4         x  5     1
5         x  6     1
6         x  7     1
7         x  8     1
8         x  9     1
9         x 10     1
dirkschumacher commented 2 years ago

Thanks a lot for reporting this. Will look at it asap (probably tomorrow).

dirkschumacher commented 2 years ago

Ok, the problem is due to stringsAsFactors not being explicitly set to FALSE when created the data.frame. As the CI tests only run on R 4.x, the tests did not fail. They would have failed if R 3.x was enabled.

What I will do to fix and prevent it:

library(magrittr)
library(ROI.plugin.glpk)
model <- ompr::MIPModel() %>% 
   ompr::add_variable(x[i], i = 1:10, type = "continuous", ub = 2) %>% 
   ompr::add_constraint(x[i] <= 1, i = 1:9) %>% 
   ompr::set_objective(sum_over(x[i], i = 1:10))
 soln <- ompr::solve_model(model, ompr.roi::with_ROI(solver = "glpk"))
 ompr::get_solution(soln, x[i])
#>    variable  i value
#> 1         x  1     1
#> 2         x  2     1
#> 3         x  3     1
#> 4         x  4     1
#> 5         x  5     1
#> 6         x  6     1
#> 7         x  7     1
#> 8         x  8     1
#> 9         x  9     1
#> 10        x 10     2

Created on 2022-01-31 by the reprex package (v2.0.1)