Skip to main content

Flow conservation constraint in gurobipy-pandas

Answered

Comments

3 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    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.
  • Riley Clement
    • Gurobi Staff

    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
  • Koen Timmermans
    • Gurobi-versary
    • Conversationalist
    • Curious

    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

Post is closed for comments.