Replies: 1 comment
-
|
If you have that kind of input data, then my feeling is you should use ROI directly and build a matrix for the constraints instead of using an algebraic framework. However, with the new library(tidyverse)
library(ompr)
set.seed(7)
data <- sample(c(0, 0, 1), 70, replace = TRUE)
data <- matrix(data, nrow = 7)
data2 <- as_tibble(data)
data3 <- rownames_to_column(data2)
data4 <- pivot_longer(data3, !rowname, names_to = "var")
data5 <- filter(data4, value != 0)
data5
#> # A tibble: 24 × 3
#> rowname var value
#> <chr> <chr> <dbl>
#> 1 1 V4 1
#> 2 1 V8 1
#> 3 2 V1 1
#> 4 2 V2 1
#> 5 2 V3 1
#> 6 2 V5 1
#> 7 3 V1 1
#> 8 3 V3 1
#> 9 3 V8 1
#> 10 3 V9 1
#> # … with 14 more rows
model <- MIPModel() |>
add_variable(x[i], i = sort(unique(data5$var))) |>
add_constraint(
sum_over(
data5$value[data5$rowname == j & data5$var == i] * x[i],
i = data5$var[data5$rowname == j]
) == 1, j = unique(data5$rowname))
extract_constraints(model) # note, the second column is V10, not V2
#> $matrix
#> 7 x 10 sparse Matrix of class "dgCMatrix"
#>
#> [1,] . . . . 1 . . . 1 .
#> [2,] 1 . 1 1 . 1 . . . .
#> [3,] 1 . . 1 . . . . 1 1
#> [4,] 1 1 1 . 1 . . 1 . .
#> [5,] . . 1 . . 1 1 . . .
#> [6,] 1 . . 1 . . . . 1 .
#> [7,] . . 1 . 1 . 1 . . .
#>
#> $sense
#> [1] "==" "==" "==" "==" "==" "==" "=="
#>
#> $rhs
#> [1] 1 1 1 1 1 1 1Created on 2022-01-07 by the reprex package (v2.0.1) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Here is an example for creating a sparse row, column, value data frame (tibble) from a dense data table using the tidyverse:
If the sparse object must be a matrix then the column names could be the column numbers converted into integers (as.integer) and the sparse tibble then converted to a matrix. The user of course could write a generic function to execute all of the conversion steps and return a sparse object. ROI also has a "simple_triplet_matrix" class. Could that be integrated into MIPModel2?
Beta Was this translation helpful? Give feedback.
All reactions