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

Adding conditions to quicksum

回答済み

コメント

5件のコメント

  • 正式なコメント
    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.
  • Xinyi Xie
    • Gurobi-versary
    • First Comment
    • First Question

    another question, because I previously attempted to write this way by:

    model.addConstrs((N[k]>=F[k]-F[k-1] for i in range(k-1,k) for k in I),name="Constr2") 

    and error is 

    name 'k' is not defined

    Are there other possible ways of writing this?

    0
  • Jaromił Najman
    • Gurobi Staff

    Could you please provide a complete minimal reproducible example where you also define N, I, F, and the show error you see?

    0
  • Xinyi Xie
    • Gurobi-versary
    • First Comment
    • First Question

    I seem to have solved this problem

    for example: 

    I_1 = [1,2,3,4,5]
    I = [2,3,4,5]
    N = model.addVars(I, vtype=GRB.BINARY, name="N")
    F = model.addVars(I_1, vtype=GRB.BINARY, name="F")

    model.addConstrs(N[i]>=F[i]-F[i-1] for i in I)
    model.addConstrs(N[i]>=F[i-1]-F[i] for i in I)
    model.addConstrs(N[i]<=F[i-1]+F[i] for i in I)
    model.addConstrs(N[i]<=2-F[i-1]-F[i] for i in I)

    I don't know why before I came across this error(name 'k' is not defined) anyway, thanks.

    and the first question, I have solved with for-loops:

    for i0 in I:
      model.addConstrs(gp.quicksum(N[i] for i in range(1,i0+1))<=10)

    maybe you have other better way to write this in one sentence?

    0
  • Jaromił Najman
    • Gurobi Staff

    There are two issues with your for-loop

    for i0 in I:
      model.addConstrs(gp.quicksum(N[i] for i in range(1,i0+1))<=10)

    You define \(N\) over \(I = \{2,3,4,5\}\), but in the \(\texttt{quicksum}\), you iterate over \(\texttt{range(1,i0+1)}\) which holds the index \(1\). For example, when \(i_0 = 2\), then \(i\) iterates over the list \([1,2]\). However, \(N_1\) is not available, only \(N_2, N_3,N_4,N_5\). You could define \(N\) over \(I_1\) to avoid this issue

    N = model.addVars(I_1, vtype=GRB.BINARY, name="N")

    Moreover, you use the addConstrs method, which takes a list of constraints as input. However, you are already adding your constraints via the for-loop. Thus, you should use the addConstr method

    for i0 in I:
      model.addConstr(gp.quicksum(N[i] for i in range(1,i0+1))<=10)

    Alternatively, you can use the addConstrs method and move the for-loop into constraint construction

    model.addConstrs( (gp.quicksum(N[i] for i in range(1,i0+1))<=10) for i0 in I)

    Best regards, 
    Jaromił

    1

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