Indexing
Answeredm.addConstrs((x[i] + y[i-1] + z[i+1] == demands[i] + y[i] + z[i] for i in range(num_periods)), name="sdsd")
how should I fix my indexing problem in the addConstrs function
-
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 try Gurobot, our chatbot interface offering instant, expert-level support. -
What exactly is the issue? Could you please post a minimal reproducible example together with the error message you see?
0 -
So this is my code below I am trying to fix the indexing in the addContrs. How should I go about doing my list to generate such constraints with different indices.
import gurobipy as gp
# parameters for the model
# number of time periods
num_periods = 10
# demands for the periods
demands = [1, 3, 5, 2, 7, 8, 8, 2, 9, 4]
# unit production costs for the periods
c_t = [2, 3, 4, 1, 5, 7, 4, 9, 1, 4]
# unit holding costs at the end of each period
h_t = [3, 8, 7, 4, 3, 8, 2, 2, 1, 2]
# backlogging costs
b_t = [4, 1, 3, 8, 7, 9, 6, 3, 9, 2]# define a new model
m = gp.Model("production plan")# decision variables
x = m.addVars(num_periods, lb=0, ub=gp.GRB.INFINITY, name="production")
y = m.addVars(num_periods, lb=0, ub=gp.GRB.INFINITY, name="inventory")
z = m.addVars(num_periods, lb=0, ub=gp.GRB.INFINITY, name="backlogging")# constraints
m.addConstrs((x[i] + y[i-1] + z[i+1] == demands[i] + y[i] + z[i] for i in range(num_periods)), name="")
# Set objective function to minimize the total cost
m.setObjective(gp.quicksum(c_t[i]*x[i] + h_t[i]*y[i] + b_t[i]*z[i] for i in range(num_periods)),
gp.GRB.MINIMIZE)# optimize the model
m.optimize()# Print the optimal objective value
print("The optimal value is", m.objval)0 -
You get the KeyError
m.addConstrs((x[i] + y[i-1] + z[i+1] == demands[i] + y[i] + z[i] for i in range(num_periods)), name="")
KeyError: -1because you are trying to access \(\texttt{y[-1]}\) but you defined your \(\texttt{y}\) variables over \(\{0,\dots,9\}\). You are constructing the constraints over \(i \in \{0,\dots,9\}\) and this results in
x[0] + y[0-1] + z[0+1] == demands[0] + y[0] + z[0]
I guess that you have to implement the first and last constraint by hand to avoid key errors with \(\texttt{y[-1]}\) and \(\texttt{z[10]}\).
Best regards,
Jaromił0
Post is closed for comments.
Comments
4 comments