Callback function not working
AnsweredHello,
I'm trying to use a callback function to apply an heuristic for each solution. I am not able to do it. I write here a simplified version of the code. In my case, there may be hundreds of solutions with the same objective function so I want to use the heuristic inside the callback to select the best one. I don't know where the error is and why I get an empty list, so I can not treat the solution.
def mycallback(model, where):
if where == GRB.Callback.MIPSOL:
print(model.cbGetSolution(model._vars))
solution = model.cbGetSolution(model._vars)
model._solutions[model._solution_count] = solution
... #Things I'd do if I had something in the variable "solution"
model._solution_count += 1
m = Model() # Gurobi model
# Parameters
# Gurobi variables
P = m.addVars(I,I,vtype=GRB.BINARY, name="Prio_")
# constraints
...
# objective function
m.setObjective( quicksum(P[i,j] for i in I for j in I), GRB.MAXIMIZE )
m.Params.Threads = 1
# With or without the following 2 lines, the result is the same
m.setParam('PoolSearchMode',2)
m.setParam('PoolSolutions',10) #
m._solution_count = 0
m._solutions = {}
m._solutions_quality = {}
m._vars = m.getVars()
m.optimize(mycallback)
This is the output:
Set parameter Username
Academic license - for non-commercial use only - expires 2023-09-24
Set parameter Threads to value 1
Set parameter TimeLimit to value 500
Gurobi Optimizer version 9.5.1 build v9.5.1rc2 (linux64)
Thread count: 6 physical cores, 6 logical processors, using up to 1 threads
Optimize a model with 199 rows, 81 columns and 493 nonzeros
Model fingerprint: 0x665c8cbc
Variable types: 0 continuous, 81 integer (81 binary)
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [1e+00, 1e+00]
Bounds range [1e+00, 1e+00]
RHS range [1e+00, 1e+01]
[ ] (this is the result of print(model.cbGetSolution(model._vars)))
Found heuristic solution: objective 16.0000000
Presolve removed 179 rows and 71 columns
Presolve time: 0.00s
Presolved: 20 rows, 10 columns, 60 nonzeros
Variable types: 0 continuous, 10 integer (10 binary)
Explored 0 nodes (0 simplex iterations) in 0.00 seconds (0.00 work units)
Thread count was 1 (of 6 available processors)
Solution count 1: 16
Optimal solution found (tolerance 1.00e-04)
Best objective 1.600000000000e+01, best bound 1.600000000000e+01, gap 0.0000%
User-callback calls 209, time in user-callback 0.00 sec
-
Hi Ana,
I think your problem will be resolved if you call m.update() prior to calling m.getVars().
To understand why, see the Lazy Updates section in the Python API Overview. You could also alternatively use m.cbGetSolution(P) to obtain the values of the variables in the solution (assuming the P variables are the only variables).
If you'd like any clarification let me know!
- Riley
1
Please sign in to leave a comment.
Comments
1 comment