0
votes

I'm doing a linear programming model with Pulp library. I have the following input which is a dataframe (df):

Zone Plant
Zone_1 Plant_1
Zone_1 Plant_2
Zone_1 Plant_3
Zone_2 Plant_4
Zone_2 Plant_5

With this input I have to write the constraints and they should look like:

Plant_1 + Plant_2 + Plant_3 == Zone_1
Plant_4 + Plant_5 == Zone_2

I want to automate this without writing equation per equation. What I'm doing is: Define the Zone and Plant variables doing:

list_zone = df['Zone'].unique().tolist()
zone_variables = [LpVariables(df[list_zone][i], lowBound = 0) for i in range(len(list_zone))]

list_Plant = df['Plant'].unique().tolist()
plant_variables = [LpVariables(df[list_Plant][i], lowBound = 0) for i in range(len(list_Plant))]

Then I would like to define the equations like the above using the lpSum oject but I don't know how to sum only the Plant variables asociated to each zone.

I was thinking doing:

for j in range(len(zone_variables)):
    model += lpSum(plant_variables[i] for i in range(len(plant_variables))]) == zone_variables[j]

But with that equation I'm not able to assign the plant variables to each zone.

Can anyone help me? Regards

1

1 Answers

0
votes

assuming these are all Lpvariables you can use a group by to do something like (check the syntax)

df = pd.DataFrame(
    [
        ['zone_1', 'plant_1'],
        ['zone_1', 'plant_2'],
        ['zone_1', 'plant_3'],
        ['zone_2', 'plant_4'],
        ['zone_2', 'plant_5']        
    ],
    columns=['zone','plant']
)

df['plant_lpvar'] = df['plant'].apply(lambda x: LpVariable(x))

zone_lpvar = LpVariable.dict('zone_lpvar',df['zone'].unique())

groups = df.groupby('zone')
for zone, group in groups:
    model += lpSum(group['plant_lpvar']) == zone_lpvar[zone]