Gurobi Cookbook - Bulk Values (2/5)
written by Abremod, LLC on 2019-06-28
Getting values in bulk for a large number of variables or constraints
See previous blog post for the basics of Gurobi.
var_names = m.getAttr('VarName', m.getVars())
constr_names = m.getAttr('ConstrName', m.getConstrs())
commentary
For users of the compute server, this method is almost mantatory. The alternative [v.varName for v in m.getVars()]
, for example, will be orders of magnitude slower.
Getting nonzero values of the solution
In many models, only a small portion of the variables have nonzero values. In that case, it is usually more convenient to get a list of only the variables that have nonzero values.
epsilon = 1e-6
var_names = m.getAttr('VarName', dvars)
var_values = m.getAttr('X', dvars)
[(name, value) for name, value in zip(var_names, var_values)
if abs(value) >= epsilon]
[('x0', 1.0),
('x7', 1.0),
('x18', 1.0),
('x27', 1.0),
('x33', 1.0),
('x40', 1.0),
('x46', 1.0),
('x50', 1.0),
('x60', 1.0),
('x66', 1.0),
('x73', 1.0),
('x81', 1.0),
('x88', 1.0),
('x94', 1.0),
('x101', 1.0),
('x109', 1.0),
('x112', 1.0),
('x116', 1.0),
('x117', 1.0),
('x119', 1.0)]
Commentary
This solution uses the builk query mechanism m.getAttr to get the values, then test each value for nonzeroness. It is not sufficient to test for 0 exactly, as Gurobi will treat very small numbers as zero. To avoid this, we check that the absolute value of a solution is greater than some small epsilon.
Getting the contributions to the objective function
An interesting subset of variables are the ones that wind up affecting the objective function directly. To contribute to an objective, a variable must be nonzero and have a nonzero coeficient in the objective function.
obj_coeffs = m.getAttr('Obj', dvars)
[(name, obj_coeff * value)
for name, value, obj_coeff in zip(var_names, var_values, obj_coeffs)
if abs(obj_coeff * value) > epsilon]
[('x0', 1.0),
('x7', 1.0),
('x18', 1.0),
('x27', 1.0),
('x33', 1.0),
('x40', 1.0),
('x46', 1.0),
('x50', 1.0),
('x60', 1.0),
('x66', 1.0),
('x73', 1.0),
('x81', 1.0),
('x88', 1.0),
('x94', 1.0),
('x101', 1.0),
('x109', 1.0),
('x112', 1.0),
('x116', 1.0),
('x117', 1.0),
('x119', 1.0)]