简体   繁体   中英

Nested loop inside add.Constrs Gurobi

I'm trying to add some temporal contraints between pickup nodes and delivery nodes, and I want to model the fact that the time of the delivery node is higher than the time at the pickup nodes associated with it.

This is my code:

for i in df_d.id:
m.addConstrs((B[i] >= B[j] for j in df_d.loc[df_d.id == i,"associati"]), name="temporal")

I get this error: 在此处输入图像描述

The result of:

for i in df_d.id:
    for j in df_d.loc[df_d.id == i,"associati"]:
         print(j)

is something like:

在此处输入图像描述

So the problem is that when I pass j to B[j] it is a list and not an int, I need to iterate through that list.

The idea of Model.addConstrs() is to incorporate the generator expressions (loops) inside the expression, so I would rewrite this as:

m.addConstrs((B[i] >= B[j] for i in df_d.id
                           for j in df_d.loc[df_d.id == i,"associati"]),
             name="temporal")

If that fails, then investigate your data frame df_d.

This seems to work:

m.addConstrs((B[j] >= B[i]  for index_i,i in df_p.id.items()          
                            for j in df_p.loc[index_i,"associati"]),name="temporal")

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