Skip to main content

problem about the matrix multiplication

Answered

Comments

4 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?.
  • Jaromił Najman
    • Gurobi Staff

    Hi,

    Please provide a minimal working example as described in Posting to the Community Forum. In particular, please provide a minimal working example defining the sets \(\mathcal{A},\mathcal{S}\), and the variables/scalars \(x_s^a, P_{is}^a, x_i^a, \bar{w}_s, \gamma\).

    Best regards,
    Jaromił

    0
  • Shutian Li
    • Gurobi-versary
    • First Question
    • First Comment

    I need to code \[ \sum_{i \in S} \sum_{a \in A} P_{is}^{a}x_{i}^{a}\] 

    I wrote it as follows, it works well in a separate python file but when I use the gurobi, it does not make sense. Here is my code: 

    for s in range(cardS): 
    px[s] = sum(P[a,i,s]*x[a,i] for a in range(cardA) for i in range(cardS)) 

    The error message is TypeError: float() argument must be a string or a number, not 'MLinExpr'. 

    SetA is a set, and range(A)= cardA

    SetS is a set, and range(S)=cardS 

    Decision variable: \[x_{s}^{a}, s\in S, a\in A\]: I define it through addMVar : 

    x = gurobipy. addMVar(shape = (cardA,cardS), lb=0, vtype=GRB.CONTINUOUS)

    The parameter \[P_{i,s}^{a}, \quad i,s \in S, a \in A\] is a 3d numpy array with the shape \[A\times S\times S\]. 

    The parameter \[\bar{w}_{s}, s \in S \] is a 1d numpy array: 

    w = np.ones(shape = cardS) 

    \[\gamma\] is a scalar.  

    0
  • Jaromił Najman
    • Gurobi Staff

    Hi,

    I am not sure if the Python Matrix API is the best way to go here. Please have a look at our Matrix API webinar, Matrix API example, and Matrix API Knowledge Base articles. Without the Matrix API, you can model your constraints, e.g., as

    import gurobipy 
    from gurobipy import *
    import numpy as np

    m = Model("test")
    A = [0,1,2,3]
    S = [0,1,2,3,4]
    P = np.random.rand(len(A),len(S),len(S))
    gamma = 42
    w = np.ones(shape = len(S))

    x = m.addVars(A, S, lb=0, vtype=GRB.CONTINUOUS, name="x")

    px = m.addConstrs((quicksum(x[a,s] for a in A) - quicksum(quicksum(gamma*P[a,i,s]*x[a,i] for a in A) for i in S) == w[s] for s in S), name="myConstr")

    For more details on the functions used, have a look at the documentation of quicksum, addConstrs, and addVars.

    Best regards,
    Jaromił

    0

Post is closed for comments.