弄清楚了。在约束中使用矩阵代数需要一点技巧。如果你需要,祝你好运弄清楚如何在目标函数中使用矩阵代数。
将 MIPModel 与 MILPModel 进行比较的示例如下。
library(tidyverse)
library(magrittr)
library(ompr)
library(ompr.roi)
library(ROI.plugin.glpk)
rm(list=ls())
numvec1 <- runif(10)
numvec2 <- runif(10)
matrix_a <- matrix(nrow=10,ncol=20,data=runif(10*20))
my_mip_model <- MIPModel() %>%
add_variable(x[i], i=1:10, type='binary') %>%
add_variable(y[i], i=1:10, type='binary') %>%
add_constraint(sum_expr(numvec1[i]*x[i],i=1:10) <= 5) %>%
add_constraint(sum_expr(2*y[i],i=1:10) <= 3) %>%
add_constraint(
sum_expr( x[i]* numvec1[i] * matrix_a[i,j],i=1:10) <=
sum_expr( 2* y[i]* numvec1[i] * numvec2[i] * matrix_a[i,j],i=1:10),
j=1:20) %>%
set_objective( sum_expr(3*x[i]*numvec1[i],i=1:10),sense='max')
my_mip_model_solve <- my_mip_model %>% solve_model(with_ROI(solver='glpk'))
#functionally equivalent using MILPmodel----
my_milp_model <- MILPModel() %>%
add_variable(x[i], i=1:10, type='binary') %>%
add_variable(y[i], i=1:10, type='binary') %>%
add_constraint(sum_expr( colwise(numvec1[i]) * x[i],i=1:10) <= 5) %>%
add_constraint(sum_expr( colwise(2) * y[i],i=1:10) <= 3) %>%
set_objective(sum_expr( colwise(3*numvec1[i]) * x[i],i=1:10),sense='max')
#now to add the matrix constraints, add a loop on the matrix column index j.
#with MIPModel we could just iterate on j in a single constraint, but here it appears
#we need to add the same constraint multiple times, and use the value of j to
#calculate the indices in as.numeric(matrix_a) that we want to use.
for(j in 1:ncol(matrix_a)){
my_milp_model %<>% add_constraint(
sum_expr( x[i]* colwise(numvec1[i] *
as.numeric(matrix_a)[(i + (nrow(matrix_a)*j -nrow(matrix_a)))]),i=1:10) <=
sum_expr( y[i]* colwise(2* numvec1[i] * numvec2[i] *
as.numeric(matrix_a)[(i + (nrow(matrix_a)*j -nrow(matrix_a)))]) ,i=1:10) )
}
my_milp_model_solve <- my_milp_model %>% solve_model(with_ROI(solver='glpk'))
#objective value and results should be equal...
my_mip_model_solve
my_milp_model_solve