how to getVar of MVar s?
AnsweredHi, I'm using gurobi in python to solve an optimization problem.
I got two array variables, val1 and val2, initialized as follows:
val1 = m.addMVar(n, lb=0.0, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name='val1')
val2 = m.addMVar((n,m), lb=0.0, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name='val2')
After the optimization, my first attempt to retrieve the values of val1 and val2 was:
res1 = m.getVarByName('val1').x
res2 = m.getVarByNamw('val2').x
but I got the error:
"NoneType' object has no attribute 'x' ".
Indeed, res1 and res2's type is NoneType.
Any idea how to sort this out?
-
Hi Viviana,
The getVarByName method only returns a variable if the variable name exactly fits to a model variable. This means that it is not enough for a variable to only have a substring \(\texttt{'val1'}\).
When you create the variables, you can see that the variable names are expanded through the dimensions of the matrix variables.
N = 2
M = 3
val1 = m.addMVar(N, lb=0.0, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name='val1')
val2 = m.addMVar((N,M), lb=0.0, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name='val2')
m.update()
print(val1)
print(val2)
=======================
> <MVar (2,)>
> array([<gurobi.Var val1[0]>, <gurobi.Var val1[1]>])
> <MVar (2, 3)>
> array([[<gurobi.Var val2[0,0]>, <gurobi.Var val2[0,1]>,
<gurobi.Var val2[0,2]>],
[<gurobi.Var val2[1,0]>, <gurobi.Var val2[1,1]>,
<gurobi.Var val2[1,2]>]])To get all these variables by name you have to also provide the indices which are now part of the respective variable names
res1 = {}
res2 = {}
for i in range(N):
res1[i] = m.getVarByName('val1[%d]'%(i)).X
for j in range(M):
res2[i,j] = m.getVarByName('val2[%d,%d]'%(i,j)).XIf you still have access to the \(\texttt{val1,val2}\) objects after the optimization is complete, you can just use these MVar objects to access the values.
m.optimize()
if m.SolCount > 0: # avoid attribute error if no feasible point is available
res1 = val1.X
res2 = val2.XOn a side note, you are using \(\texttt{m}\) for the Model object and as an index when adding MVars
val2 = m.addMVar((n,m), ...)
This can lead to any sort of issues and should definitely be avoided.
Note that there is an upcoming webinar on the Matrix friendly API where we will discuss all changing and improvements to the Matrix API.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment