pythonnumpybinarysolverxpress-optimizer

Invalid Constraint when using the addConstraint with the xpress library in python


When running this code

import numpy as np
import xpress as xp

z = np.array([xp.var () for i in range (200)]).reshape (4,5,10)
t = np.array([xp.var (vartype = xp.binary) for i in range (200)]).reshape (4,5,10)
p = xp.problem()
p.addVariable(z,t)
p.addConstraint(z <= 1 + t)

I get the following error

Invalid constraint
---------------------------------------------------------------------------
ModelError                                Traceback (most recent call last)
      3 p = xp.problem()
      4 p.addVariable(z,t)
----> 5 p.addConstraint(z <= 1 + t)
      6 p.addConstraint(xp.Sum(z[i][j][k] for i in range (4) for j in range (5)) <= 4 for k in range (10))
ModelError: Invalid constraint

Any help would be greatly appreciated, since I'm not sure how to fix it!


Solution

  • The dtype of the np arrays must be explicitly set to xp.npvar. This is stated here:

    The NumPy arrays must have the attribute dtype equal to xpress.npvar (abbreviated to xp.npvar here) in order to use the matricial/vectorial form of the comparison (<=, =, >=), arithmetic (+, -, *, /, **), and logic (&, |) operators.

    If you don't set the type to npvar, the wrong overloads for these operators will be used and z <= 1 - t will just be an array of booleans.

    This is the correct way to create your arrays:

    z = np.array([xp.var () for i in range (200)], dtype=xp.npvar).reshape (4,5,10)
    t = np.array([xp.var (vartype = xp.binary) for i in range (200)], dtype=xp.npvar).reshape (4,5,10)