Add constraint using model.addConstr() using variables in Python

343 views
Skip to first unread message

David Lanier

unread,
Mar 28, 2018, 1:50:17 PM3/28/18
to Gurobi Optimization
Hello,

I am new to using Gurobi and Python. I am working on a course project implementing an IP branch and bound algorithm using Python. As i am creating branching nodes from the parent node, I want to copy the parent model and then add constraints. I want to pass the lhs, rhs, and name using addConstr ( lhs, sense, rhs=None, name="" ) as variables created in my Python script. This method doesn't seem to accept those types of arguments so I try to use the LinExpr() method and it doesnt seem to work for my needs either. See below for a snippet of code and the message I get:

    #Create branching nodes
    mleft = m
    mright = m
    
    # Create new constraints for each node based on the non-integer decision variable value and re-solve
    mleftLHS = LinExpr('x' + str(i + 1))
    mleftRHS = LinExpr(DecisionVariableValues[i])
    mleftConstraintID = LinExpr('c' + str(ConstraintCount))
    print mleftLHS
    print mleftRHS
    print mleftConstraintID
    mleft.addConstr(mleftLHS, GRB.LESS_EQUAL, mleftRHS, mleftConstraintID)

Error:


  File "C:/Users/Dave Lanier/Documents/IE 7521/Project 1/HW1v2.py", line 58, in <module>
    mleftLHS = LinExpr('x' + str(2))

  File "linexpr.pxi", line 43, in gurobipy.LinExpr.__init__ (../../src/python/gurobipy.c:27292)

 IndexError: string index out of range

Any suggestions on how to overcome this or a better option for creating the new constraints? Full script is attached
HW1v2.py

Greg Glockner

unread,
Mar 28, 2018, 2:13:11 PM3/28/18
to Gurobi Optimization
Check the constructor for the LinExpr object - it does not use a string.

Reply all
Reply to author
Forward
0 new messages