There are three primary causes of this error:

- Trying to add a two-sided constraint
- Using NumPy scalars on the left-hand side of a constraint
- Using variables or expressions in if-clauses

## Trying to add a two-sided constraint

You may see this error when trying to add two-sided constraints like 1 <= x <= 2 through the Python API. Adding two-sided constraints is not supported in Gurobi.

For example, consider the following code:

m = Model() x = m.addVar(name="x") m.addConstr(1 <= x <= 2, name="twosided")

Gurobi actively prohibits this syntax by throwing an error, preventing unexpected behavior like this. Instead, each of the two constraints can be added to the model separately:

m.addConstr(1 <= x, name="lefthandside") m.addConstr(x <= 2, name="righthandside")

## Using NumPy scalars on the left-hand side of a constraint

This error can also occur when using NumPy scalars (such as numpy.int32, numpy.int64, numpy.float32, or numpy.float64) on the left-hand side of a constraint. For example, the following code results in the "Constraint has no bool value" error:

import numpy as np import gurobipy as gp model = gp.Model() x = model.addVar() a = np.float64(5) model.addConstr(a >= x) # error!

The error is a result of Python using the __ge__ (or __le__) method from the appropriate NumPy data class, which is not meant for constructing Gurobi constraint expressions.

Two possible workarounds are:

- Recast the NumPy data structure into a standard Python numeric type like int or float. In this case, the last line becomes model.addConstr(int(a) >= x).
- Rewrite the constraint so the left-hand side expression begins with a Var or LinExpr object. With this workaround, the last line becomes instead model.addConstr(x <= a).

## Using variables or expressions in if-clauses

The error can also occur when using variable objects or expression objects (such as LinExpr or QuadExpr) in if-clauses. For example, the following code results in the titular error:

import gurobipy as gp m = gp.Model() x = m.addVars(3) y = m.addVars(2) if (gp.quicksum(x) >= 1): # error! m.addConstr(gp.quicksum(y) == 0)

The error occurs because the expression object created by the gp.quicksum(x) call does not have any value which could be used to evaluate the if-condition. In mathematical programming, one has to model such conditional statements via additional constraints and binary variables.

The Knowledge Base article How do I model conditional statements in Gurobi? explains how to model the above if-condition.

## Comments

0 comments

Article is closed for comments.