1

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

最小 wi * xi

xi ε {0,1}

xi ≤ xj , i 的 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])

如果我划掉约束,我会得到我会expext的结果(考虑到没有使用约束)。如何在 i 和 j 的约束内分别处理?

4

1 回答 1

0

您调用中的过滤条件add_constraint会产生错误。i和是向量,j使用向量索引矩阵不会产生 所需的单个逻辑向量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表示模型中应该包含哪一行,不应该包含哪一行。

于 2018-08-12T13:36:33.650 回答