mobook / MO-book

Hands-On Optimization with Python
MIT License
153 stars 40 forks source link

Provide style advice about index sets #49

Closed leonlan closed 11 months ago

leonlan commented 1 year ago

In the style guide, there's currently no advice on how to create different index sets. For example, given a set of nodes $V$, a common occurrence is that we want to construct a specific set of constraints for a subset $U \subseteq V$. I've seen a lot of people do this:

model.U = pyo.Set([v for v in model.V if v not in U]) # Create a new set

@model.Constraint(model.U)
def constraint(model, v):
  return expression(v) == 1

My personal preference is to keep the number of sets as small as possible. Instead, add conditionals in the constraint rule together with pyo.Constraint.Skip:

@model.Constraint(model.V)
def constraint(model, v):
  if v in U:
     return expression(v) == 1
  else:
     return pyo.Constraint.Skip

What are your thoughts on this?

jckantor commented 1 year ago

Guilty as charged! Yes, I do that, too. A typical case is have an index set for grid points, then another index set that might leave out the end points. This comes up in differential algebraic equations when distinguishing between interior points and boundary points.

I think your solution is a good one. It's explicit and self-contained. So let's insert some language with an example or two.

leonlan commented 1 year ago

I won't be available next week, but the week after I'll try to make a proposal.

alessandrozocca commented 11 months ago

Added to the Pyomo style guide.