メインコンテンツへスキップ

Skipping non-existing decision variables in for loop

回答済み

コメント

2件のコメント

  • 正式なコメント
    Simranjit Kaur
    • Gurobi Staff
    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.
  • Jaromił Najman
    • Gurobi Staff

    You could define a list or a dictionary of indices that are not present and add an \(\texttt{if}\)-clause to your quicksum call.

    import gurobipy as gp

    m = gp.Model()

    xI = 1
    xJ = 2
    x  = m.addVars(xI, xJ, name="x")
    yI = 3
    yJ = 4
    y  = m.addVars(yI, yJ, name="y")

    present = {}
    # loop over the bigger set yI x yJ
    for i in range(yI):
      for j in range(yJ):
        if i < xI and j < xJ:
          present[i,j] = True
        else:
          present[i,j] = False

    m.setObjective(
      gp.quicksum(x[i,j]*y[i,j] 
                  for i in range(yI)
                  for j in range(yI) 
                  if present[i,j]))

    Note that the above snippet works only if \(x_I \times x_J\) is a subset of \(y_I \times y_J\) and might require more work if you are using other indices.

    0

投稿コメントは受け付けていません。