model.NumVars doesn't work before solving model (in Gurobipy)?
AnsweredHere is one of the example problems built in Gurobipy, with some print statements added:
import gurobipy as gp
from gurobipy import GRB
# Create a new model
m = gp.Model("mip1")
# Create variables
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")
# Set objective
m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
# Add constraint: x + 2 y + 3 z <= 4
m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
# Add constraint: x + y >= 1
m.addConstr(x + y >= 1, "c1")
# Count number of variables
print("NumVars:", m.NumVars)
# Optimize model
m.optimize()
# Count number of variables again
print("NumVars:", m.NumVars)The output is:
<license blah blah>
NumVars: 0
<solver output blah blah>
NumVars: 3Is this the expected behaviour? I did not see anything in the docs for NumVars about this. And for my use case I really want to know things about the variables in the model *before* I solve it. Can this be achieved? It seems to work fine when I do a similar thing via the ortools API, but perhaps ortools is doing the counting there?
0
-
Hi Ben,
This is expected. The relevant docs are here:
https://docs.gurobi.com/projects/optimizer/en/current/reference/python/overview.html#lazy-updates
You can use m.update() before calling m.NumVars in order to get the correct value.
- Riley
0 -
Ah, amazing, thanks very much!
0
Please sign in to leave a comment.
Comments
2 comments