lundi 9 septembre 2019

R: Convert an if-else constraint in linear model

How can I convert a constraint with if-else condition in linear (mixed integer) programming?

Hi, when I try to run the following script, error message: Unexpected operator 'ifelse' found. Issue is probably the last constraint.

appr <- c(0.15, 0.11, 0.10, 0.13, 0.18, 0.20, 0.18, 0.11, 0.07, 0.06, 0.07, 0.08, 0.12, 0.13, 
          0.06, 0.03, 0.04, 0.06, 0.07, 0.08, 0.09, 0.07, 0.04, 0.04, 0.05, 0.07, 0.07, 0.07)

leng <- c(1:28)

Payment_Model <- MIPModel() %>%
  add_variable(x[i], i = 1:28, type = "binary") %>%
  set_objective(sum_expr(x[i] * appr[i], i = 1:28), "max") %>%
  add_constraint(sum_expr(x[i], i = 1:7) == 1) %>%
  add_constraint(sum_expr(x[i], i = 8:14) == 1) %>%
  add_constraint(sum_expr(x[i], i = 15:21) == 1) %>%
  add_constraint(sum_expr(x[i], i = 22:28) == 1) %>%

  # This constraint needs to be modified; 
  add_constraint(sum_expr(x[i] * leng[i], i = 1:7) 
               + sum_expr(ifelse(x[i]==0, 0, ifelse(x[i]== 1 & j<= (i+7), x[j]*(leng[j]- i), x[j]*(leng[j]-(i+7)))), i = 1:7, j = 8:14) 
               + sum_expr(ifelse(x[j]==0, 0, ifelse(x[j]== 1 & k<= (j+7), x[k]*(leng[k]- j), x[k]*(leng[k]-(j+7)))), j = 8:14, k = 15:21) 
               + sum_expr(ifelse(x[k]==0, 0, ifelse(x[k]== 1 & l<= (k+7), x[l]*(leng[l]- k), x[l]*(leng[l]-(k+7)))), k = 15:21, l = 22:28) 
               <= 16)


Payment_Model

Thanks!

Aucun commentaire:

Enregistrer un commentaire