简体   繁体   中英

How to include matrix multiplication in constraint?

I am trying to make run this model. I am trying to maximize:x[4]

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

But I have 2 problems, first matrix multiplication.

    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)

I got the following error.

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

Second, I am trying to set the bounds in a vectorized way, but I don't know how to do that. I tried the following:


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

This gives:

object 'i' not found

Any help would be very useful!

Works like this, but the solution is (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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM