Select some, but not all, variables in getVars()

425 views
Skip to first unread message

alel...@gmail.com

unread,
Aug 15, 2018, 8:18:44 AM8/15/18
to Gurobi Optimization
Hi,

I am trying to select some of the variables returned by the solver, but I keep getting errors.

As shown below, the model returns 2 w variables (w_0 and w_1), 6 Z variables (Z_0,...,Z_5), and an intercept 'b'.
(In red, the values I would like to retrieve).
  
print(model.getVars()) 
 
Optimal objective 1.127659574e+01
[<gurobi.Var w_0 (value 0.19148936170212763)>, <gurobi.Var w_1 (value -0.148936170212766)>, <gurobi.Var Z_0 (value 5.787234042553191)>, <gurobi.Var Z_1 (value 0.0)>, <gurobi.Var Z_2 (value 0.0)>, <gurobi.Var Z_3 (value 2.723404255319149)>, <gurobi.Var Z_4 (value 0.0)>, <gurobi.Var Z_5 (value 2.76595744680851)>, <gurobi.Var b (value 3.4255319148936176)>]

 In order to retrieve the intercept, I type: 
b = b.X 
 print(b)
And I successfully get the value 3.4255319148936176

But I haven't managed to get the coefficients w[0] and w[1] ("w" being a list and n = 2).

I have tried: 
for i in range(n):
     w = [x for x in model.getVars() if x.VarName.find('w_%d' %i)]
 
for i in range(n):
     w = [v.x for v in m.getVars()] 

and other countless things, but none of them print 0.19148936170212763 and -0.148936170212766. The second one prints me the values of all the variables in getVars(), even if the range is only n=2.

Any hint on how to do it?

Thank you!

Daniel Espinoza

unread,
Aug 15, 2018, 9:55:06 AM8/15/18
to Gurobi Optimization
You can keep a reference to your variables when you create them, and then query directly on them the X attribute (rather than `finding them` by strings)

Best,
Daniel

Alex Laval

unread,
Aug 15, 2018, 12:04:24 PM8/15/18
to gur...@googlegroups.com
This is how they are created. In the example above, I created an example with n=2 for the w variables, but n could be as large as 100. In that case, I fear that querying the X attribute on each 100 references would be far less efficient. Isn't there any other way?

w = []
    for i in range(n):
        w.append(m.addVar(lb = -GRB.INFINITY, ub = GRB.INFINITY, name = 'w_{}'.format(i)))
    m.update()
    
    z = []
    for j in range (N):
        z.append(m.addVar(lb = -GRB.INFINITY, vtype=GRB.CONTINUOUS, name = 'Z_{}'.format(j), obj = 1))
    m.update()

Thanks! 

--

---
You received this message because you are subscribed to the Google Groups "Gurobi Optimization" group.
To unsubscribe from this group and stop receiving emails from it, send an email to gurobi+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Alex Laval

unread,
Aug 15, 2018, 12:13:37 PM8/15/18
to gur...@googlegroups.com
Nevermind! Got it!

It worked with this simple thing:
for i in range(n):
        w[i]=w[i].X

Thanks though!
Reply all
Reply to author
Forward
0 new messages