Closed joepacheco closed 2 years ago
Thanks for the report! Seems to be fixed in the most recent GitHub version:
library(ompr)
library(magrittr)
setup_model <- function(cost, tau) {
model <- MIPModel() %>%
add_variable(x[t, f],
type = "binary",
t = 1:5,
f = 1:2
)
model <- model %>%
set_objective(sum_expr(sum_expr(x[t - tau[f], f] * cost[t],
t = (tau[f] + 1):5
),
f = 1:2
),
sense = "max"
)
return(model)
}
cost1 <- 1:5
tau1 <- c(0, 1)
model <- setup_model(cost1, tau1)
objective_function(model)
#> $solution
#> sparse vector (nnz/length = 9/10) of class "dsparseVector"
#> [1] 1 2 2 3 3 4 4 5 5 .
#>
#> $constant
#> [1] 0
Created on 2022-01-08 by the reprex package (v2.0.1)
Hi,
I've been working with the ompr package and have found it very useful. I'm now trying to create some functions for setting up my optimization models and am running into issues in using local variables (i.e., those defined inside a function) as external parameters for the optimization model.
See the following example:
library(ompr)
setup_model <- function(cost, tau) { model <- MIPModel() %>% add_variable(x[t, f], type = "binary", t = 1:5, f = 1:2)
model <- model %>% set_objective(sum_expr(sum_expr(x[t - tau[f],f] * cost[t] , t = (tau[f]+1):5) , f = 1:2) , sense = "max")
return(model) }
cost1 = 1:5 tau1 = c(0,1)
model = setup_model(cost1, tau1)
When I run this code, I get an error that the object 'tau' is not found. But if I run this same code and define cost and tau to be global variables, it runs just fine. Is there a way to run this code without the need to make the external parameters (i.e., cost and tau) global variables.
Thanks!