# Term based modeling or Matrix based

Hello,

I am trying to efficiently define the following model in Gurobi. Would it be possible to help me, please?

1- I need to define a matrix P whose size depends on a parameter, n_spots. For instance, if n_spots=2, then P would look like as:

then I need to calculate F= P^m and m is another parameter. If m=2 then F would be:

Model:

1- Variables: all the elements in matrix P and should be continuous variables in [0,1].

2- Constraints:

A @ F = A'

A, A' are 1-D vectors with only one element equal to 1 and the rest are equal to zero. For instance, if A = [1,0,0] and A' = [0,0,1]. Therefore, A @ F =

and the constraints would be as below:

c1 = m.addConstr(p00**2 + p01*p10 + p02*p20 == 0)

c2 = m.addConstr(p00*p01 + p01*p11 + p02*p21 == 0)

c3 = m.addConstr(p00*p02 + p01*p12 + p02*p22 == 1)

3- Objective function:

There is matrice W with numerical elements and I want to minimize the difference between P and W, I defined this as the element wise difference to the power two :

m.setObjective

(pow(p00-W[0,0], 2) + pow(p01-W[0,1], 2) + pow(p02-W[0,2], 2)+

pow(p10-W[1,0], 2) + pow(p11-W[1,1], 2) + pow(p12-W[1,2], 2)+

pow(p20-W[2,0], 2) + pow(p21-W[2,1], 2) + pow(p22-W[2,2], 2))

The current Model that I wrote is:

from gurobipy import *

import numpy as np

n_spots = 2

initial_value = 1/(n_spots+1)

w = np.array([initial_value]*9)

m = Model()

p = m.addVars(9, name ="p")

m.update()

#Set objective functions

m.setObjective(quicksum(pow(p[i]-w[i],2) for i in range (9)))

# Add constraints

c1 = m.addConstr(p[0]**2 + p[1]*p[3] + p[2]*p[6] == 1)

c2 = m.addConstr(p[0]*p[1] + p[1]*p[4] + p[2]*p[7] == 0)

c3 = m.addConstr(p[0]*p[2] + p[1]*p[5] + p[2]*p[8] == 0)

#Solve model

m.params.NonConvex = 2

m.optimize()

My challenges:

1- how I can define the variables efficiently? Currently, I have to use the following definition:

2- I also need to calculate F and write my constraints efficiently.

3- how I can define the objective function efficiently?

I appreciate your time in advance.

Best,

Elha,

Please sign in to leave a comment.

## Comments

0 comments