如何在约束中包含矩阵乘法?

How to include matrix multiplication in constraint?

我正在尝试制作 运行 这个模型。我正在尝试 maximize:x[4]

w.r.t    Mv = c(0,0,0,0)
         lb < v < ub

但是我有两个问题,第一个是矩阵乘法。

    library(ompr)
    lb <- c(-200, 0, -200, -200)
    ub <- c(1000, 1000, 1000, 1000)
    M <- matrix(rbind(
      c(-1, 0, -1, 0), # A
      c(-1, 0, 0, -2), # B
      c(1, -2, 0, 0), # C
      c(1, 0, 0, 2), # D
      c(0, 2, -1, 0), # E
      c(0, 0, 1, -1) # F
    ), nrow = 6)
    n <- 4
    rhs <- rep(0, n)
    
    model <- MIPModel() %>%
      add_variable(x[i], i = 1:n, type = "continuous") %>%
      set_objective(x[4]) %>%
      add_constraint(M[i, ] %*% x == rhs[i], i = 1:n)

我收到以下错误。

Error in M[i, ] %*% x : requires numeric/complex matrix/vector arguments

其次,我正在尝试以矢量化方式设置边界,但我不知道该怎么做。我尝试了以下方法:


    set_bounds(x[i], ub = ub[i], lb = lb[i], i = 1:n)

这给出:

object 'i' not found

任何帮助都会非常有用!

像这样工作,但解决方案是 (0, 0, 0, 0):

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

lb <- c(-200, 0, -200, -200)
ub <- c(1000, 1000, 1000, 1000)
M <- matrix(rbind(
  c(-1, 0, -1, 0), # A
  c(-1, 0, 0, -2), # B
  c(1, -2, 0, 0), # C
  c(1, 0, 0, 2), # D
  c(0, 2, -1, 0), # E
  c(0, 0, 1, -1) # F
), nrow = 6)
n <- 4
rhs <- rep(0, n)

model <- MIPModel() %>%
  add_variable(x[i], i = 1:n, type = "continuous") %>%
  set_objective(x[4], "max") %>%
  add_constraint(sum_over(M[i, j] * x[j], j = 1:4) == rhs[i], i = 1:n) %>%
  add_constraint(x[i] <= ub[i], i = 1:n) %>%
  add_constraint(x[i] >= lb[i], i = 1:n) %>%
  solve_model(with_ROI(solver = "glpk"))

get_solution(model, x[i])