Model.addConstrs()


Model.addConstrs()

addConstrs ( genexpr, name="" )

Add multiple constraints to a model using a Python generator expression. Returns a Gurobi tupledict that contains the newly created constraints, indexed by the values generated by the generator expression.

The first argument is a Python generator expression, a special feature of the Python language that allows you to iterate over a Python expression. For addConstrs, the expression should be a valid Gurobi constraint, and the result will be that a new constraint is added to the model for each iteration of the generator expression.

To give an example, if x is a Gurobi variable, then

  m.addConstr(x <= 1, name='c0')
would add a single linear constraint involving this variable. In contrast, if x is a list of Gurobi variables, then
  m.addConstrs((x[i] <= 1 for i in range(4)), name='c')
would add four constraints to the model. The entire first argument is a generator expression, where the indexing is controlled by the statement for i in range(4), The first constraint that results from this expression would be named c[0], and would involve variable x[0]. The second would be named c[1], and would involve variable x[1].

Generator expressions can be much more complex than this. They can involve multiple variables and conditional tests. For example, you could do:

  m.addConstrs((x[i,j] == 0 for i in range(4)
                            for j in range(4)
                            if i != j), name='c')

Note that if you supply a name argument, the generator expression must be enclosed in parenthesis. This requirement comes from the Python language interpreter.

Arguments:

genexpr: A generator expression, where each iteration produces a constraint.

name: Name pattern for new constraints. The given name will be subscripted by the index of the generator expression (so, for example, c would become c[0], c[1], etc.).

Return value:

A dictionary of Constr objects, indexed by the values specified by the generator expression.

Example usage:

  model.addConstrs(x.sum(i, '*') <= capacity[i] for i in range(5))
  model.addConstrs(x[i] + x[j] <= 1 for i in range(5) for j in range(5))