How to extract solution values to separate matrices/dataframes in Python?
AnsweredHi,
I am new to Gurobi and Python. I have a Python code that in the end gives me the solution:
for v in my_model.getVars():
print(v.varName, v.x)
However, this is a long vector where I have several variables, and they are two-dimensional:
lambda[0,0]
lambda[0,2]
lambda[0,3]
lambda[1,0]
...
lambda[50,3]
group[0,0]
group[0,1]
group[0,2]
group[1,0]
...
group[50,2]
Is there a way to save the output in two matrices/dataframes: lambda and group which will then be 2 dimensional (each will be a matrix or dataframe with 50 rows and 3 columns)? In general, there is not necessarily 50 rows and 3 columns - these numbers can vary. Also, there may be other variables than lambda and group.
Thank you!
-
Hi Aleksandrs,
You can use numpy.reshape and Model.getAttr to do this concisely. For example:
# setup
import gurobipy as gp
import numpy as np
m = gp.Model()
x = m.addVars(range(5), range(3), vtype="B", obj=np.random.random(size=(5,3)), name="v")
m.addConstr(gp.quicksum(x.values())==7)
m.optimize()
# print variable names in numpy matrix to verify the result of reshape
print(np.reshape(m.getAttr("VarName", m.getVars()), (5,3)))
# print variable values in solution in numpy matrix
print(np.reshape(m.getAttr("X", m.getVars()), (5,3)))The print statements give
array([['v[0,0]', 'v[0,1]', 'v[0,2]'],
['v[1,0]', 'v[1,1]', 'v[1,2]'],
['v[2,0]', 'v[2,1]', 'v[2,2]'],
['v[3,0]', 'v[3,1]', 'v[3,2]'],
['v[4,0]', 'v[4,1]', 'v[4,2]']], dtype='<U6')and
array([[1., 0., 1.],
[0., 0., 0.],
[1., 0., 0.],
[0., 0., 1.],
[1., 1., 1.]])respectively.
- Riley
2
Please sign in to leave a comment.
Comments
1 comment