Skip to main content

Copying Model

Answered

Comments

3 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?.
  • Eli Towle
    • Gurobi Staff

    Yes, you can use Model.copy() for this purpose. However, as you noticed, copying a model doesn't give you local Python variables for the new model's Var/Constr objects. You can construct these data structures yourself using Model.getVarByName() and Model.getConstrByName().

    Another (probably easier) approach is to only create one model, then use Model.remove() to remove the extra constraints once your loop completes. E.g.:

    import gurobipy as gp

    # Model: min{x : x >= 0}
    m = gp.Model()
    x = m.addVar(obj=1, name='x')

    # Optimal objective is 0
    m.optimize()

    # Add constraints in loop
    cons = []
    for i in range(10):
    # Add each Constr object to cons list
    cons.append(m.addConstr(x >= i + 1))
    # Optimal objective is i+1
    m.optimize()

    # Remove constraints added in loop above
    for c in cons:
    m.remove(c)

    # Optimal objective is 0 again
    m.optimize()

     

    0
  • huan liu
    • Gurobi-versary
    • First Comment

    Hello,

    when I use the method of Model.getVarByName(), I have the following problems:

    subproblem1 = Model('branch1')
    model.update()    #have defined
    subproblem1 = model.copy()
    X = subproblem1.getVarByName('x_' + str(i) + '_' + str(j))  #name
    print(X)
    subproblem1.addConstr(X[index[0],index[1]] <= 0)

    TypeError: 'NoneType' object is not subscriptable

    (and the X is None)

    How can I solve this problem? Looking forward to your reply.

    0

Post is closed for comments.