Skip to main content

I need help with LinExpr

Answered

Comments

3 comments

  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Hi Amogh,

    The fastest way is to use the LinExpr() constructor or the addTerms() function, where you provide 2 lists. The first list holds the coefficients and the second one holds the variables. The code

    import gurobipy
    from gurobipy import *

    m = Model("test")
    coeff = [1,2,3]
    x = m.addVars(3,name="x")
    lexpr = LinExpr(coeff,x.select('*'))

    would produce the term \(\texttt{lexpr =}\) \(1\cdot x_1 + 2 \cdot x_2 + 3 \cdot x_3\). The select() function is required to convert a tupledict to a tuplelist.
    Please note that the Community can only help in a more specific way if you provide enough details on your code to make it reproducible. In best case, try to provide a minimal working example.

    Best regards,
    Jaromił

    0
  • Amogh Bhosekar
    Gurobi-versary
    Conversationalist
    Curious

    Hello Jaromił,

    Thank you for your response. I believe my question is very straightforward. I am not able to find any code with two dimensional list coefficient and dictionary variable. 

    Can you provide the same example with 2*2 coefficient matrix ?

     

     

    import gurobipy
    from gurobipy import *

    m = Model("test")
    coeff = [[1,2],[4,5]]
    x = {}

    for i in range(2):
    for j in range(2):
    print(i,j)
    print(coeff[i][j])
    x[(i,j)] = m.addVar(vtype = GRB.BINARY, name="x%d,%d" % (i,j))

    lexpr = LinExpr(coeff,x.select('*'))

    The final expression does not work with error,

    dict' object has no attribute 'select'

    Thanks

     

    Amogh

    0
  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Hi Amogh,

    This will not work with multi-dimensional matrices. However, you can just flatten your matrix.

    import gurobipy 
    from gurobipy import *

    m = Model("test")
    coeff = [[1,2],[4,5]]
    I=[0,1]
    J=[0,1]

    x = m.addVars(I, J, vtype = GRB.BINARY, name="x")

    lexpr = LinExpr([c for c1 in coeff for c in c1],x.select('*'))
    m.setObjective(lexpr)
    m.write("myLP.lp") # writes LP file for sanity check

    This way you keep your \(\texttt{coeff}\) object as a 2D list. You can access the variables \(\texttt{x}\) via \(\texttt{x[i,j]}\).

    Best regards,
    Jaromił

    0

Please sign in to leave a comment.