我在 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 的约束内分别处理?