Skip to content

Instantly share code, notes, and snippets.

@dirkschumacher
Last active January 3, 2020 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirkschumacher/658de0f24006f130d5d2cf1f0102fec8 to your computer and use it in GitHub Desktop.
Save dirkschumacher/658de0f24006f130d5d2cf1f0102fec8 to your computer and use it in GitHub Desktop.
# 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment