【问题标题】:Error creating MIP problem using ompr package in R在 R 中使用 ompr 包创建 MIP 问题时出错
【发布时间】:2021-11-02 22:18:47
【问题描述】:

我目前正在使用 R 中的 ompr 和 roi 包来解决 IP 类型问题。我已经设法解决了一个简单的版本,但是,我现在正在尝试扩展问题,我只想在 1 个背包中包含一个项目(不要让它多次出现在背包中)。下面是我正在使用的示例数据集(称为 KP):

Itemid ItemType Value Weight
1 A 114 24
2 B 557 136
3 B 543 136
4 B 10 136
5 B 4 136
6 C 161 152
7 A 184 24
8 A 751 24
9 A 184 24
10 A 150 24

我使用以下代码解决了我最初版本的背包(背包容量为 240):

library(tidyverse)
library(ROI)
library(ROI.plugin.glpk)
library(ompr)
library(ompr.roi)

# Create variables from data to use in model
n <- nrow(KP)
v <- KP$Value
w <- KP$Weight
c <- 240


solution <- MIPModel() %>%
  add_variable(x[i], i = 1:n, type = "binary") %>%
  set_objective(sum_expr(v[i] * x[i], i = 1:n), "max") %>%
  add_constraint(sum_expr(w[i] * x[i], i = 1:n) <= c) %>%
  solve_model(with_ROI(solver = "glpk")) %>% 
  get_solution(x[i]) 
  #filter(value > 0)

# Now join solution to original dataframe
df <- cbind(KP,capacity=240,solution[,3,drop=FALSE])
ouput <- df %>% filter(value > 0) 

我现在想使用容量向量 (200, 150) 求解扩展版本。这是我使用的代码,现在合并了一个 x[i, j] 二进制变量,如果项目 i 被添加到 c[j],则该变量设置为 1:

# Create variables from data to use in model
n <- nrow(KP)
v <- KP$Value
w <- KP$Weight
c <- c(240,150)
m <- length(c)

# Now solve the model
solution <- MIPModel() %>%
  add_variable(x[i, j], i = 1:n,j=1:m, type = "binary") %>%
  set_objective(sum_expr(v[i] * x[i, j], i = 1:n, j=1:m), "max") %>%
  add_constraint(sum_expr(w[i] * x[i, j], i = 1:n, j=1:m) <= c[j]) %>% #This constraint ensures that the weight of the items must be less than the capacity
  add_constraint(sum_expr(x[i, j], i = 1:n, j=1:m) <= 1) %>% #This constraint ensure that an item can only be included in a single knapsack - not across multiple knapsacks
  solve_model(with_ROI(solver = "glpk")) %>% 
  get_solution(x[i, j]) 
#filter(value > 0)

我已经尝试调试代码,它本质上是没有正确生成的约束(这是发生错误的地方)。这是我得到的错误:

check_for_unknown_vars_impl(model, the_ast) 中的错误: 该表达式包含一个不属于模型的变量。

我已经尝试了各种方法来解决这个问题,但似乎无法弄清楚我的约束有什么问题。

【问题讨论】:

    标签: r optimization knapsack-problem mixed-integer-programming ompr


    【解决方案1】:

    对于任何感兴趣的人,我需要在右侧索引 j。所以我设法找到了一个解决方案,并将每个项目限制为只能添加到背包中一次:

    # Create variables from data to use in model
    n <- nrow(KP)
    v <- KP$Value
    w <- KP$Weight
    c <- c(240,150)
    m <- length(c)
    
    # Now solve the model
    solution <- MIPModel() %>%
      add_variable(x[i, j], i = 1:n,j=1:m, type = "binary") %>%
      set_objective(sum_expr(v[i] * x[i, j], i = 1:n, j=1:m), "max") %>%
      add_constraint(sum_expr(w[i] * x[i, j], i = 1:n) <= c[j], j = 1:m) %>%
      add_constraint(sum_expr(x[i, j], j = 1:m) <= 1, i=1:n) %>%
      solve_model(with_ROI(solver = "glpk")) %>% 
      get_solution(x[i, j]) %>%
      filter(value > 0)
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多