Adding constraint in gurobipy-pandas with arrays of different lengths
AnsweredHi,
Using \(\texttt{gurobipy-pandas}\), I want to create the following constraint:
\[ z_{k} \geq y_{ik} \quad \forall i \in A, k \in K \]
I have created y like this (ik_values_y as a multi index):
y = gppd.add_vars(model, ik_values_y, vtype=GRB.BINARY, name="y")
>>>
i k
5 0 <gurobi.Var y[5,0]>
1 <gurobi.Var y[5,1]>
2 <gurobi.Var y[5,2]>
3 <gurobi.Var y[5,3]>
4 <gurobi.Var y[5,4]>
...
25 0 <gurobi.Var y[25,0]>
1 <gurobi.Var y[25,1]>
2 <gurobi.Var y[25,2]>
3 <gurobi.Var y[25,3]>
4 <gurobi.Var y[25,4]>
Name: y, Length: 105, dtype: object
And z looks like:
z = gppd.add_vars(model, k_values, vtype=GRB.BINARY, name="z")
>>>
k
0 <gurobi.Var z[0]>
1 <gurobi.Var z[1]>
2 <gurobi.Var z[2]>
3 <gurobi.Var z[3]>
4 <gurobi.Var z[4]>
Name: z, dtype: object
Currently, I'm trying to add the constraints with
gppd.add_constrs(model, z.groupby("k"), ">=", y.groupby(["i", "k"]))
This returns the following error message: \(\texttt{All arrays must be of the same length}\).
In the previous version of my code (without gurobipy-pandas), I added the constraint like this:
for i in A:
for k in K:
model.addLConstr(z[k] >= y[i,k], name=f"G1-{i},{k}")
Hopefully someone can help me out here. Thank you in advance!
Best regards,
Koen Timmermans
-
Hello,
this is not perfect but you don't need two loops.
for i in A:
model.addLConstr(z >= y[i,:], name=f"G1-{k}")0 -
Hi Koen,
We need the indices on the series to align to use gurobipy-pandas. One option is to use pandas.DataFrame.merge to get the alignment although this will drop the "i" index from the resulting dataframe which is not ideal. There are workarounds to keep the "i" index but it gets clunky.
A better approach is to align the index of z with y using pandas.Series.reindex
G1_cons = gppd.add_constrs(
model, z.reindex(y.index, level=0), GRB.GREATER_EQUAL, y, name="G1-",
)- Riley
0
Please sign in to leave a comment.
Comments
2 comments