R: ompr package constraints



我在R中使用ompr包来解决省略问题。 书面优化问题如下所示:

闽维 * xi

xi ε {0,1}

XI ≤ XJ , j 的追随者

如果距离矩阵(distmatrix(中有一个值可用,则 i 是 j 的跟随者。如果值为 inf,则无法从 i 到 j 连接

目标是分析物料清单,为了使我的示例更容易一些,我创建了一个更简单的示例,其中包含更少的材料。

vertices_undef <- data.frame(matrix(ncol=3, nrow=5))
vertices_undef$X1 <- c("3","5","9","7","2")
vertices_undef$X3 <- c(12, -8, 8, 3, -9)
rownames(vertices_undef) <- vertices_undef$X1
distMatrix <- data.frame(matrix(ncol=5, nrow=5))
rownames(distMatrix) <- vertices_undef$X1
colnames(distMatrix) <- vertices_undef$X1
distMatrix$`3` <- c("inf", 0.7, "inf", "inf", 0.3)
distMatrix$`5` <- c(3, "inf", "inf", "inf", 0.3)
distMatrix$`9` <- c("inf", 0.7, "inf", 0, 3)
distMatrix$`7` <- c("inf", "inf", "inf", 0.3, "inf")
distMatrix$`2` <- c("inf", 7, "inf", "inf", 0.3)

w <- vertices_undef$X3
w <- t(w)
colnames(w)<- vertices_undef$ID
w <- t(w)
    result <- MIPModel() %>%
      add_variable(x[i], type = "binary", i = as.integer(as.character(vertices_undef$X1))) %>%
      set_objective(sum_expr(x[i]*w[i,1], i = as.integer(as.character(vertices_undef$X1))), "min") %>%
      add_constraint(x[i]<=x[j], i = as.integer(as.character(vertices_undef$X1)), j = as.integer(as.character(vertices_undef$X1)), is.finite(distMatrix[i,j])==TRUE)%>%
      solve_model(with_ROI(solver = "glpk"))
    get_solution(result, x[i])

如果我划掉约束,我得到的结果是我会扩展的结果(考虑到没有使用约束(。如何在约束中分别解决 i 和 j ?

add_constraint调用中的筛选条件会产生错误。ij是向量,使用向量索引矩阵不会产生add_constraint所要求的单个逻辑向量,而是另一个矩阵。此外,某些i/j组合不是distMatrix矩阵的一部分。

内部发生的事情基本上是这样的:

x <- expand.grid(i = as.integer(as.character(vertices_undef$X1)),
                 j = as.integer(as.character(vertices_undef$X1)))
is.finite(distMatrix[x$i, x$j])

过滤条件(即表达式 is.finite(distMatrix[i,j])==TRUE (需要返回一个长度为 i/j 的逻辑向量,该向量指示模型中应包含哪一行,哪些不应包含在模型中。

最新更新