Skip to main content

How to refactor binary quadratic constraint to linear form when using MVar

Answered

Comments

1 comment

  • Simranjit Kaur
    • Gurobi Staff Gurobi Staff

    Hi Hancheng,

    If \(x,y\) and \(z\) are (a,c), (c,b) and (a,b) dimensional matrices, and \(z  = x*y\), then each term of z will be a sum of k terms \[ z_{ij} = \sum_{k=0}^{c-1} x_{i,k} y_{k,j} \]

    We can write \( z = w0 + w1 +...+ w(c-1) \), where \(wn\) is a (a,b) dimensional matrix obtained from multiplying the nth column and nth row of matrices x and y, respectively. 

    For example, if a,b and c are 2, then \( z = w0 + w1 \), where \[ w0 = \begin{bmatrix} x_{00} \\  x_{10} \end{bmatrix} * \begin{bmatrix} y_{00} & y_{01} \end{bmatrix}  = \begin{bmatrix}x_{00}y_{00} & x_{00}y_{01}\\ x_{10}y_{00} & x_{10}y_{01}\end{bmatrix}\]

    \[ w1 =  \begin{bmatrix} x_{01} \\ x_{11} \end{bmatrix} * \begin{bmatrix} y_{10} & y_{11} \end{bmatrix}  = \begin{bmatrix}x_{01}y_{10} & x_{01}y_{11}\\ x_{11}y_{10} & x_{11}y_{11}\end{bmatrix}\]

    Once expressed in this form, we can linearise the terms of w matrices using the logic of this post as follows:

    import gurobipy as gp
    from gurobipy import GRB
    import numpy as np
    a = 2
    b = 3
    c = 2

    m = gp.Model()

    Z = m.addMVar((a,b), vtype=GRB.BINARY, name="z" )
    X = m.addMVar((a,c), vtype=GRB.BINARY, name="x" )
    Y = m.addMVar((c,b), vtype=GRB.BINARY, name="y" )

    # add auxillary variables W to linearise the products in Z
    W = dict()
    for i in range(c):
      W[i] = m.addMVar((a,b), vtype=GRB.BINARY, name="w"+str(i) )

      # get ith column of X and ith row of Y
      Xi = X[:,i]
        Yi = Y[i,:]

      # add linearization constraints to linearise terms
      m.addConstr( W[i] <= Xi[:,np.newaxis] )
      m.addConstr( W[i] <= Yi )
      m.addConstr( W[i] >= Xi[:,np.newaxis] + Yi - 1)

    # add constraint Z = W0 + W1 + .. + W(c-1)
    m.addConstr( Z == sum( W[i] for i in range(c) ) )
    Another option is to keep the quadratic constraint without linearizing the terms 
    m.addConstr( Z == X @ Y )
    and solve the quadratic model with the parameter setting NonConvex=2. 
     
    Regards,
    Simran
    1

Please sign in to leave a comment.