Flow conservation constraint in gurobipy-pandas
AnsweredHi!
I have a binary decision variable \(x_{ijk}\) and I want to implement the following flow conservation constraint:
\[ \sum_{j \in A} x_{ijk} = \sum_{j \in A} x_{jik} \quad \forall i \in A, k \in K \]
I am working with \(\texttt{gurobipy-pandas}\), so I have defined \(x_{ijk}\) using:
x = gppd.add_vars(model, index_x, vtype=GRB.BINARY, name="x")
But how do I swap the \(i\) and \(j\) in the constraint?
con1 = gppd.add_constrs(model, x.groupby(["i", "k"]).sum(), "=", x.groupby(["i", "k"]).sum(), name="con1")
Hopefully someone can help me out here. Thank you in advance!
Best regards,
Koen Timmermans
-
Hi Koen,
LHS = x.groupby(["i", "k"]).sum()
will give you a Series where the values are expressions for the LHS of the constraints.
RHS = x.groupby(["j", "k"]).sum()
will give you a Series where the values are expressions for the RHS of the constraints.
Confusion may arise because these Series will be indexed by (i,k) and (j,k) respectively and here the value of i and j are the same. We could rename index levels to alleviate confusion:
x2 = x.copy()
x2.index = x2.index.rename(["j","i","k"])
cons = gppd.add_constrs(model, x.groupby(["i", "k"]).sum(), "=", x2.groupby(["i", "k"]).sum(), name="con1")cons will be a pandas.Series with values of gurobi.Constr, indexed by (i,k).
Alternatively we could rename the Series index levels after the groupby so that i and j align:
LHS = x.groupby(["i", "k"]).sum()
RHS = x.groupby(["j", "k"]).sum()
RHS.index = RHS.index.rename(["i","k"])
cons = gppd.add_constrs(model, LHS, "=", RHS, name="con1")cons will be a pandas.Series with values of gurobi.Constr, indexed by (i,k).
Note that the last code block still seems to work without the 3rd line, but this is risky. The result is indexed by an unnamed column (in addition to k) and it's not clear how it has come about - it is highly likely it is just comparing the order of values in the two Series, which is not a reliable approach.
- Riley
0 -
Hi Riley,
Thank you for your quick response!
I hadn't thought about "reindexing" in this way yet. I will try to implement it!
Best regards,
Koen Timmermans
0
Please sign in to leave a comment.
Comments
2 comments