How to get value from decision matrix after optimization?
AnsweredSuppose I have a matrix defined as follows:
MM = model.addVars(I, J, vtype=GRB.BINARY, name='MM')
...
model.optimize()
After Solution was found I want to save matrix MM as a 2D numpy array Result to use later in the code. Smth like: Result = [[1, 0, 0], [0, 1, 0], [0,1,0]] (where MM[1][1]=1 for example)
How can I do this in python?
0
-
Official comment
This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support. -
You can get the optimal solution value by accessing the X attribute of a given variable.
The following code snippet shows an example of how to construct such a numpy array. Please note that it is probably not the most Pythonic way to achieve it. Maybe someone could provide a more Pythonic way.
import gurobipy as gp
from gurobipy import GRB
import numpy as np
m = gp.Model()
I = 3
J = 2
MM = m.addVars(I,J,vtype=GRB.BINARY, name="MM")
m.addConstr(MM[1,1] == 1)
m.setObjective(gp.quicksum(MM))
m.optimize()
array = np.array(0)
if m.SolCount > 0:
# get tupledict holding solution values
L = []
for i in range(I):
K = []
for j in range(J):
K.append(MM[i,j].X)
L.append(K)
array = np.array(L)
print(array)0
Post is closed for comments.
Comments
2 comments