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

Gurobi Python: fail to call the decision variable outside ".addConstr" function

回答済み

コメント

2件のコメント

  • Jaromił Najman
    • Gurobi Staff Gurobi Staff

    There are 2 issues with your code.

    1. You are not creating a 20x3 variable called x_vars but rather you are creating 2 variables x[20] and x[8] accessible via \(\texttt{x[20]}\) and \(\texttt{x[8]}\). Thus, you get the KeyError. Constructing your x variables via

    x_vars = m.addVars(S,N, vtype=GRB.BINARY, name = 'X')

    solves this issue.

    2. You are taking the max value of a LinExpr object. This is not defined. Gurobi has its own max function to handle this. You can use the addGenConstrMax method to formulate the expressions you need. For this, you will have to introduce auxiliary variables for each term \(1-x_{s,n}\) because the addGenConstrMax method accepts only single optimization variables. Moreover, you will have to define \(\texttt{R_c}\) as optimization variables.

    The best thing is that you don't even need the max expression because your x variables are Binary. This means that

    \[R_c = \max {1-x,0} = 1-x.\]

    I don't fully understand why you need \(\texttt{R_c}\) and \(\texttt{R_e}\), since both equal the same value.

    So what should work for you is

    x_vars = m.addVars(S, N, vtype=GRB.BINARY, name='X')
    R_c = m.addVars(S, N, vtype=GRB.BINARY, name='R_c')
    for s in range(S):
    for n in range(N):
    m.addConstr(R_c[s,n] == 1 - x_vars[s,n], name="max_%d%d"%(s,n))
    [...]

    Best regards, 
    Jaromił

    0
  • Han Han
    • Gurobi-versary
    • First Comment
    • First Question

    Dear Jaromił,

    Thank you so much for your warm and professional answer, It does help a lot!

    To answer your question: In fact, R_c and R_e are different functions with respect to x. This program is a simplified version, and I'm sorry to confuse you by writing R_c and R_e in the same form due to our negligence. But I believe this did not affect the accuracy of your reply, you answered the question we wanted to ask, thank you very much!

    We will modify our Python program according to your suggestions. If we encounter a new problem, we will try to solve it ourselves first. If it does not work, we will continue to follow up under this problem.

    Finally, this forum is really awesome! Thank you for providing such a platform!

     

    Best,

    Han

     

    0

サインインしてコメントを残してください。