简体   繁体   中英

How to add 'For' loop using Gurobi Python API

The variables are defined as list:

    var_week = [1,2,3,4,5]
    var_pool = ['ALBANY','ROCHESTER']
    var_zone = ['NEW YORK','FLORIDA']
    var_cg = ['PREMIUM','CONVERTIBLE','MIDSIZE']
    var_bu = ['AP','OAP']
    var_pi = [0,1,2,3,4,5]

The demand variable is defined at demand(w,p,bu,cg,pi) level as shown below.

    demand = {(1, 'ALBANY', 'OAP', 'PREMIUM',1): -0.0863039944029772,
     (1, 'ALBANY', 'OAP', 'CONVERTIBLE',1): -0.0538715896861709,
     (1, 'ALBANY', 'OAP', 'REGULAR SUV',2): 0.0203727503604571,
     (2, 'ALBANY', 'OAP', 'SMALL SUV',3): 1.66739983969337}

#Decision variables

    dec_move = m.addVars(var_week, var_cg, var_pool, var_bu, var_pool, var_bu, name="Dec_Move")
    dec_upgrade = m.addVars(var_week, var_pool, var_bu, var_cg, var_cg, name="Dec_Upgrade")
    dec_endfleet = m.addVars(var_week, var_pool, var_bu, var_cg, name="Dec_Endfleet")
    dec_accepted_demand = m.addVars(var_week, var_pool, var_bu, var_cg, var_pi, 
    name="Dec_Accepted_Demand")
    dec_delete = m.addVars(var_vin_group, var_week, var_pool, var_bu, var_cg, name="Dec_Delete")
    dec_addition_adds = m.addVars(var_week, var_pool, var_bu, var_cg, name="Dec_Addition_Adds")

The constraint is supposed to check if pi <>0 and demand(w,p,bu,cg,pi)>0, then create constraint:

for w in var_week:
   for p in var_pool:
       for bu in var_bu:
           for cg in var_cg:
              for pi in var_pi:
                  dec_accepted_demand(w,p,bu,cg,pi) <= demand(w,p,bu,cg,pi)     .

I wrote it as:

    m.addConstrs((dec_accepted_demand(w,p,bu,cg,pi) if pi <>0 and demand(w,p,bu,cg,pi)>0) <= 
    demand(w,p,bu,cg,pi) for w in var_week for p in var_pool for bu in var_bu for cg in var_cg for pi in 
    var_pi,"Accepted_demand")

I receive invalid Syntax error. What is the right way to frame this constraint?

In the generator expression , the if-filter needs to go at the end. Taken literally, your code should be:

m.addConstrs(
  ( dec_accepted_demand[w,p,bu,cg,pi] <= demand[w,p,bu,cg,pi]
    for w in var_week
    for p in var_pool
    for bu in var_bu 
    for cg in var_cg
    for pi in var_pi
    if pi != 0 and demand[w,p,bu,cg,pi]>0 ), "Accepted_demand")

However, I prefer to iterate just over the demand values, like:

m.addConstrs(
  ( dec_accepted_demand[w,p,bu,cg,pi] <= demand[w,p,bu,cg,pi]
    for w,p,bu,cg,pi in demand
    if pi != 0 and demand[w,p,bu,cg,pi]>0 ), "Accepted_demand")

I'm assuming your sample data is incomplete; you will need to ensure the real data includes the correct combinations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM