optimizationmathematical-optimizationgurobilinear-optimization

model.update performance in the model


I have a question about performance of the model.update in the gurobipy library.

Let's say I have a list of objects which I want to add as a variable to the model, also I want to add a constraint to each of this object, to do that I have a for loop in which I do the following

for object in list:
    some_parameter=object.parameter
    model.addVar(name=object.name)
    model.update()
    model.addConstr(
                model.getVarByName(object_name) >= some_parameter
            )

Of course my loop is more complex, this is just a simple example. I am getting this message in the log:

INFO : Warning: excessive time spent in model updates. INFO : Consider calling update less frequently.

My question is now: is the right solution to this is to make two loops instead of one like this:

for object in list:
    model.addVar(name=object.name)

then call

    model.update()

and then run the loop with adding the constraints?

for object in list:
    some_parameter=object.parameter
    model.addConstr(
                model.getVarByName(object_name) >= some_parameter
            )

Which one is the usual way, or maybe I should do it completely different?


Solution

  • Yes, it's the usual way to add all the variables first. Note that the model.addVar() method already returns the variable which can directly be used without calling model.update(). Therefore, you don't need the model.getVarByName() method to obtain access to the variable. Instead, you can do something like this:

    # add the variables
    y = {}
    for ob in object_list:
        y[ob.name] = model.addVar(name=ob.name)
    
    # add the constraints
    for ob in object_list:
        model.addConstr(y[ob.name] >= ob.parameter)
    
    model.update()
    model.optimize()
    

    After the model has been solved, you can then easily access the variable values through the .X attribute, i.e. y[ob.name].X gives you the variable value where ob is an element of your object_list.