Code not working
Awaiting user inputHi, we are trying to work with this code, but not able to get the output. Not sure if the problem is with the objective function. Could you please help us out? We are able to print the values from the excel sheet but not able to get the results. As you can see we are getting all zeros. Here is the code and the excel sheet.
import gurobipy as gp
from openpyxl import load_workbook
if __name__ == '__main__':
# Input excel files with arcs data(sheet 1) and commodities data (sheet2)
# Generate lists to store 'objects'
Arcs = []
Vertex = []
Commodities = []
# Open input file(excel) that is in the current folder
#loc1=("/Users/fer/PycharmProjects/project/Input_lecct.xlsx")
loc1 = (r"C:\Users\rithi\Downloads\Input_lecct.xlsx")
wb = load_workbook(filename=loc1, read_only=True)
ws = wb['Arcs']
for row in ws.rows:
for cell in row:
print(cell.value)
# Close the workbook after reading
#wb = openpyxl.load_workbook(loc1, read_only=True)
#sheet=wb.active
#wb.close()
List_arcs = tuple(wb["Arcs"].iter_rows())
List_commo = tuple(wb["Commodities"].iter_rows())
print(List_commo)
#play_data = wb['Arcs']
#print(play_data)
#wb.close()
# Objective function
model = gp.Model("MCF")
x = {}
for m in range(len(Arcs)):
for k in range(len(Commodities)):
x[k, Arcs[m].To, Arcs[m].From] = model.addVar(obj = Arcs[m].Cost, vtype = "C",
name = "x(%d, %d, %d)" % (k, Arcs[m].To, Arcs[m].From))
model.update()
# constraints
# capacity
Capacity = {}
for m in range(len(Arcs)):
Capacity[Arcs[m].From, Arcs[m].To] = model.addConstrs(gp.quicksum(x[k.Arcs[m].To.Arcs[m].From]
for k in range(len(Commodities))),
'<=', Arcs[m].Capac, name = 'Capacity(%d)' % (m))
# conservation constraint
Continuity = {}
for k in range(len(Commodities)):
for j in range(len(Nodes)):
if j == Commodities[k].From:
Continuity[k, j] = model.addConstr(gp.quicksum(x[k, j, p] for p in Nodes[j].OutLinks
- gp.quicksum(x[k, p, j] for p in Nodes[j].InLinks)),
'=', Commodities[k].Quant, name = 'Continuity(%d, %d)' % (k, j))
elif j == Commodities[k].To:
Continuity[k, j] = model.addConstr(gp.quicksum(x[k, j, p] for p in Nodes[j].OutLinks)
- gp.quicksum(x[k, p, j] for p in Nodes[j].InLinks),
'=', -Commodities[k].Quant, name = 'Continuity(%d, %d)' % (k, j))
else:
Continuity[k, j] = model.addConstr(gp.quicksum(x[k, j, p] for p in Nodes[j].OutLinks)
- gp.quicksum( x[k, p, j] for p in Nodes[j].InLinks),
'=', 0, name = 'Continuity(%d, %d)' % (k, j))
model.update()
model.optimize()
status = model.status
if status != gp.GRB.Status.OPTIMAL:
if status == gp.GRB.Status.UNBOUNDED:
print("The model cannot be solved because it is unbounded")
elif status == gp.GRB.Status.INFEASIBLE:
print('The model is infeasible; compute IIS')
model.computeIIS()
print('\n The following constraints cannot be satisfied:')
for c in model.getConstrs():
if c.IISConstrs():
print('%s' % c.constrName)
elif status != gp.GRB.Status.INF_OR_UNBD:
print('Optimization was stopped with status %d' % status)
exit(0)
print(MCF)
-
Official comment
This post is more than three 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 why not try our AI Gurobot?. -
Hi Rithika, it's great to hear you are able to print the values from Excel. Now you need to define the variables you are looping over later in the code.
# Input excel files with arcs data(sheet 1) and commodities data (sheet2)
# Generate lists to store 'objects'
Arcs = []
Nodes = [] # I assume you mean Nodes
Commodities = []
[...]
""" You need to give values to the variables Arcs, Commodities, and Nodes."""
""" When you use them in the loops below they have a length of 0, """
""" so the loop never populates anything in the model """
[...]
for m in range(len(Arcs)): # Arcs has length of 0
for k in range(len(Commodities)): # Commodities has a length of 0
[...]
Capacity = {}
for m in range(len(Arcs)): # Arcs has length of 0
[...]
# conservation constraint
Continuity = {}
for k in range(len(Commodities)): # Commodities has a length of 0
for j in range(len(Nodes)): # Nodes has a length of 0
[...]Also, please see Can't get the results – Gurobi Support Portal for the remainder of this conversation.
0 -
Hello Alison, thank you for helping me out, I'm kind of confused by
You need to give values to the variables Arcs, Commodities, and Nodes."""
cause we have the values from the sheet. Could you please explain??
0 -
Hi Rithika,
Toward the top of your code, you create empty lists for these variables. For example, \(\texttt{Arcs=[]}\). At this point, there are no Arcs in your list. Later, you loop over \(\texttt{range(len(Arcs))}\). However, \(\texttt{len(Arcs) = 0}\) because \(\texttt{Arcs}\) is still an empty list. At some point between creating the empty \(\texttt{Arcs}\) and using it to define your loop, you should populate \(\texttt{Arcs}\). And you are right, you have the values from the sheet. Now, you need to set \(\texttt{Arcs}\) equal to those values.
0 -
Hi Alison, thank you. I'll work on it and also I have another question, if you can help:
In our objective function we are not able to get other commodities, it's printing only Instagram. Not sure where the problem is
0 -
The first post looks like you are using are defining the coefficient when you are adding the variables. Is this still the case? Can you show me how you are defining your objective in your latest code?
0 -
This is the objective function:
0 -
Thank you for providing this. When you call \(\texttt{m.addVars(..., obj=cost,...)}\) you are setting the coefficients in the objective function based on the values in \(\texttt{cost}\). A variable appears in your objective function if it has a non-zero coefficient. The variable does not appear in the objective if the coefficient is zero.
Is it possible that the variables with the missing commodities all have an objective function coefficient of zero? To check this,
- Find a variable that you would expect to appear in the objective function. Specifically, this should be a variable you would expect to see with an objective coefficient that is non-zero.
- Check to see if the objective function coefficient is non-zero. To do this, look at the variable.Obj attribute of this variable. For examples on how to query variable attributes see Python Attribute Examples.
If \(\texttt{variable.Obj}\) is zero for a variable you would expect to see in the objective, this is why it is missing. In this case, I recommend checking the corresponding value in your \(\texttt{cost}\) variable. You have used this to define your objective function coefficient when you used model.addVars(). If the corresponding value in \(\texttt{cost}\) is also zero, then I would not expect it to appear in the objective.
0
Post is closed for comments.
Comments
8 comments