Problem with constraint in CQM

I'm having a quadratic objective function which needs to be minimized. I also need to enforce cardinality constraint on that objective function such that there must be at-least 'K' variables whose value should be non-zero.

The objective function and constraints are:

min_{x}  x^T Q x

such that:

\sum_{i} x_{i} = 100

\sum_{i} z_{i} = 6

LB*z_{i} <= x_{i} <= UB*z_{i}  for all i

where LB and UB are lower and upper bounds on variable x_{i} for all i.

I'm stuck on enforcing the 3rd constraint.

The code is written below:

cqm = ConstrainedQuadraticModel()

x = {}  # weight variable
z = {}  # Selection of variable
for i in range(10):
  x[i] = Integer(label=f'x_{i}', lower_bound =lb, upper_bound=ub )
  z[i] = Binary(label=f'z_{i}')

cqm.add_constraint(quicksum(z[i] for i in range(10))==6 , label = 'cardinality_cons')
cqm.add_constraint(quicksum(x[i] for i in range(10)) == 100, label = 'weights_cons')

for i in range(10):
  cqm.add_constraint(lb*z[i] <= x[i]) # Setting cardinality constraint
  cqm.add_constraint(x[i] <= ub*z[i])

obj = 0
for i in range(10):
for j in range(i,10):
obj += x[i]*x[j]*Q[i][j]

cqm.set_objective(obj) # Minimizing objective function x^T Q x

While running the code, I get the following error:

'<=' not supported between instances of 'BinaryQuadraticModel' and 'QuadraticModel'

Any hints on  how to write the 3rd constraint?



  • I got the problem. The error was due to the variables being on both sides of the equation. They must be on same side of the equation. So the constraint must be like

    LB*z_{i} - x_{i} <= 0   for all i

    0 <= UB*z_{i} - x_{i}  for all i

    The code is:

    for i in range(10):
      cqm.add_constraint(lb*z[i] - x[i] <= 0) # Setting cardinality constraint
      cqm.add_constraint(0 <= ub*z[i] - x[i])
    Comment actions Permalink
  • That's great!
    I was just about to post the following. Maybe the links will be helpful:


    It looks like you have an Integer on the right hand side of the comparison, which is causing the error. The Integer object is of type QuadraticModel, which explains:

    'BinaryQuadraticModel' and 'QuadraticModel'

    The documentation for add_constraint_from_comparison under the comp parameter mentions that the right hand side must be of type integer or float, which refers to the primitive data types (i.e. int and float). It does seem a little confusing, so maybe this could be clarified in the documentation.

    There are some examples showing how to use the Symbolic Math here:

    You will note that all of the examples use int values on the right hand side of the comparison operators.

    I hope this helps to explain the error you are seeing.
    Please let us know if you have any questions.

    Comment actions Permalink

Please sign in to leave a comment.

Didn't find what you were looking for?

New post