dirkschumacher / ompr

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

Error in MIPModel construction without %>% piping #413

Closed sbmack closed 2 years ago

sbmack commented 2 years ago

I attempted to build a model with and without piping. Here is the example code:

model1 <- MIPModel() %>% 
  add_variable(x[i], i = 1:5)

model1

variable_keys(model1)

model2 <- MIPModel()
  add_variable(model2, x[i], i = 1:5)

model2

variable_keys(model2)

Here is the console stream from running the code:

> model1 <- MIPModel() %>% 
+   add_variable(x[i], i = 1:5)
> 
> model1
Mixed integer linear optimization problem
Variables:
  Continuous: 5 
  Integer: 0 
  Binary: 0 
No objective function. 
Constraints: 0 
> 
> variable_keys(model1)
[1] "x[1]" "x[2]" "x[3]" "x[4]" "x[5]"
> 
> model2 <- MIPModel()
>   add_variable(model2, x[i], i = 1:5)
Mixed integer linear optimization problem
Variables:
  Continuous: 5 
  Integer: 0 
  Binary: 0 
No objective function. 
Constraints: 0 
> 
> model2
Mixed integer linear optimization problem
Variables:
  Continuous: 0 
  Integer: 0 
  Binary: 0 
No objective function. 
Constraints: 0 
> 
> variable_keys(model2)
character(0)
> 

You can see that with piping instantiating model1 and adding the variables returns nothing to the console. The mode1 and variable_keys(model1) statements return the expected contents. However, instantiating model2 and adding variables without piping immediately returns the expected model2 object contents which appear to be correct. However, then running the model2 and variable_keys(model2) statements shows that the variables were not actually created for model2. Comments?

dirkschumacher commented 2 years ago

All operations work on values and not on references. That means that e.g. add_variable creates a new model and does not modify an existing one:

library(ompr)
model2 <- MIPModel()
model3 <- add_variable(model2, x[i], i = 1:5)
add_variable(model2, x[i], i = 1:5)
#> Mixed integer linear optimization problem
#> Variables:
#>   Continuous: 5 
#>   Integer: 0 
#>   Binary: 0 
#> No objective function. 
#> Constraints: 0
model2
#> Mixed integer linear optimization problem
#> Variables:
#>   Continuous: 0 
#>   Integer: 0 
#>   Binary: 0 
#> No objective function. 
#> Constraints: 0
variable_keys(model2)
#> character(0)

model3
#> Mixed integer linear optimization problem
#> Variables:
#>   Continuous: 5 
#>   Integer: 0 
#>   Binary: 0 
#> No objective function. 
#> Constraints: 0
variable_keys(model3)
#> [1] "x[1]" "x[2]" "x[3]" "x[4]" "x[5]"

Created on 2022-02-20 by the reprex package (v2.0.1)

Thanks for reporting that nonetheless. But I do not think there is an issue here.