dirkschumacher / ompr

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

Index required for single (non-vector) variable #312

Closed snestler closed 4 years ago

snestler commented 4 years ago

Recently, I was trying to add 2 binary variables and 1 constraint that ensures eactly one of them is selected, as follows:

  add_variable(ypg, type = "binary") %>%
  add_variable(ysg, type = "binary") %>%
  add_constraint(sum_expr(ypg + ysg) == 1)

Eventually, between a colleague and I, we figured out that it this works:

  add_variable(ypg[i], i = 1, type = "binary") %>%
  add_variable(ysg[i], i = 1, type = "binary") %>%
  add_constraint(sum_expr(ypg[i] + ysg[i], i = 1) == 1)

The [i], i=1 indexing seems superfluous, but apparently it is not.

There are no examples that show simple variables and constraints like this. Suggest adding it somewhere to the documentation. Thank you.

sbmack commented 4 years ago

I don't think that:

add_constraint(sum_expr(ypg + ysg) == 1)

is required because you are not using an index.

add_constraint(ypg + ysg == 1)

Should suffice.

snestler commented 4 years ago

Thanks, Steve. I believe that I had actually tried that first, but it didn't work either. Will double-check and confirm. However, I believe that the point still holds that I couldn't find any examples of non-indexed variables in the documentation or example projects.

snestler commented 4 years ago

Just tried again and found that it worked. My error. But I would ask for there to be an example of non-indexed variables provided to prevent wondering whether or not it is possible.

sbmack commented 4 years ago

Glad it worked Scott. A common non-indexed example is a fixed charge binary auxiliary variable. E.g. opening a single warehouse. So for example, if you have a budget constraint, then that variable is added to the LHS without an index.

snestler commented 4 years ago

Yes. I have an OR background and am aware of when these types of variables are supposed to be used in models (from many years of writing optimization models in AMPL, GAMS, RASON with solvers like CPLEX, Gurobi, KNITRO, MOSEK, XPRESS, ...) My point is that I don't actually see any examples of the syntax for doing so in the 'ompl' documentation or example code. Perhaps I missed it yesterday.

sbmack commented 4 years ago

Scott, always good to interact with a fellow math programming aficionado. I've been mesmerized by the stuff since LINDO. As an FYI, Dirk has examples of simple non-indexed constraints here:

https://dirkschumacher.github.io/ompr/index.html

See: "A simple example:"

snestler commented 4 years ago

Well, shoot ... somehow I read right past that. Thank you for pointing it out.