# Build sparse models with filter guards
# this problem arises in network models where you have a variable for each
# pair of nodes. However if your graph is not fully connected, you end up
# creating a lot of useless variables if you have all combinations in your MIP Model
# and then set the invalid edges to 0.
# Below is a toy example with 1 millionen edges, but only 36 are actually being used.
library(rmpk)
is_adjacent <- function(i, j) {
i < j & j < 10 # just a dummy function indicating when two nodes are adjacent
}
n <- 1000
system.time({
model <- MIPModel(ROI_solver("glpk"))
x <- model$add_variable(x[i, j], i = 1:n, j = 1:n, is_adjacent(i, j))
model$set_objective(sum_expr(x[i, j], i = 1:n, j = 1:n, is_adjacent(i, j)))
model$add_constraint(x[i, j] <= 1, i = 1:n, j = 1:n, is_adjacent(i, j))
})
#> user system elapsed
#> 0.409 0.069 0.748
model
#> MIP Model:
#> Variables: 36
#> Constraints: 36
Created on 2020-01-03 by the reprex package (v0.3.0)