Search code examples
pythongurobi

How to define an objective function with multiplication of 2-d matrices in Gurobipy


I am trying to set as an objective function a product of 4 matrices.

In mathematical terms, my objective function looks as this:

where u is a unit vector of length n, D is a matrix mxn, C is a matrix nxn and delta is a variable of length 3.

I defined it as:

D = np.array([[50, 50, 0, 0, 0, 0], [0, 0, 100, 10, 0, 0], [0, 0, 0, 0, 80, 100]])
c = np.array([10, 4, 9, 5, 6, 8])
C = np.diag(c)

m = gp.Model("relaxation")
delta = m.addMVar(shape=(6,1), lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name='delta')
m.setObjective(u@(D @ C @ delta))

But I get this error which states gurobipy.GurobiError: Variable is not a 1D MVar object, my question is how do I define it properly, also a place where I can find a suitable example would be greatly appreciated.


Solution

  • There are some issues here:

    1. u must be a vector of length m
    2. delta should be a vector of length n

    Here is some corrected code:

    import numpy as np
    import gurobipy as gp
    from gurobipy import GRB
    
    D = np.array([[50, 50, 0, 0, 0, 0], [0, 0, 100, 10, 0, 0], [0, 0, 0, 0, 80, 100]])
    c = np.array([10, 4, 9, 5, 6, 8])
    C = np.diag(c)
    u = np.ones(3)
    
    m = gp.Model("relaxation")
    delta = m.addMVar(6, lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name='delta')
    m.setObjective(u @ D @ C @ delta)