dirkschumacher / ompr

R package to model Mixed Integer Linear Programs
https://dirkschumacher.github.io/ompr/
Other
269 stars 35 forks source link

interactions: "Quadratic expression are not supported" #444

Open seschaub opened 1 year ago

seschaub commented 1 year ago

dear all,

first of all, thank you Drik for creating and maintaining the package.

Today, I was trying to solve a model with "interaction terms". However, I received an error message: "Quadratic expression are not supported"

Bellow, you find a simplified version of the model. In this model the interaction is "* (1 + x[i])". Does someone know how to solve this? do i simply miss something?

define parameters

soil_coef <- c(2, -1) manage_coef <- c(0.5, -.1)

number of plots

n = 100

information about land properties

dz <- data.frame( soil = runif(n, min = 5, max = 10)) cov.mat_me <- dz %>% as.matrix()

model definition

model_1 <- MIPModel() %>%

define variable that we optimize over

add_variable(x[i], i = 1:n, type = "binary") |>

set objective function

set_objective( sum_over(

output 1

  (as.numeric(cov.mat_me[i,1]) * soil_coef[1] + x[i] * manage_coef[1] ) * (1 + x[i]) +
    # output 2 
    (as.numeric(cov.mat_me[i,1]) * soil_coef[1] + x[i] * manage_coef[1]) * (1 + x[i]), 
  i = 1:n),
"max") |>

add the constraint

add_constraint(sum_over(x[i], i = 1:n) <= 5 ) %>%

solve_model(with_ROI(solver = "glpk")) |> get_solution(x[i]) model_1

benwatsoncpa commented 1 year ago

Hi, first off, big thank you for developing this library. I'm running into the same issue but it may be that I'm setting up something incorrectly.

Here is a reproducible example:

`x <- c(1, 2, 3, 4, 5) y <- c(3, 9)

m <- length(x) n <- length(y)

model <- MIPModel() %>% add_variable(x[i],i=1:m,type="integer") %>% add_variable(y[j],j=1:n,type="integer") %>% add_variable(d[i,j],i=1:m,j=1:n,type="binary") %>% set_objective(1,sense="min") %>% add_constraint(sum_over(d[i,j],j=1:n)<=1,i=1:m) %>% add_constraint(sum_over(d[i,j]*x[i],i=1:m)==y[j],j=1:n) `

Update: I reformulated my code to work, seems that I didn't need to add x & y:

X <- c(1, 2, 3, 4, 5) Y <- c(9,5,0)

x <- length(X) y <- length(Y)

model <- MIPModel() %>% add_variable(D[x,y],x=1:x,y=1:y,type="binary") %>% set_objective(1,sense="min") %>% add_constraint(sum_over(D[x,y],y=1:y)<=1,x=1:x) %>% add_constraint(sum_over(D[x,y]*X[x],x=1:x)==Y[y],y=1:y) %>% solve_model(with_ROI("glpk", verbose = TRUE))

sbmack commented 1 year ago

The ompr documentation does not suggest a non-linear optimization capability. However the R ROI package allows the formulation of non-linear models: http://roi.r-forge.r-project.org/index.html

dirkschumacher commented 1 year ago

Yes quadratic terms are not supported. It wouldn't be too much work though to add them at this point. Right now though I don't have a lot of time. The infrastructure is there. rmpk supports it.