简体   繁体   中英

Pythong PuLP Constraints: How to build a recursive constraint

I am building a simple model in PuLp that requires me to build a recursive function as a constraint based on the following equation . In PuLp the constraint is written as: model += lpSum([y[j] + x[j] -z[j]]) == x[j+1]

However I get Keyerror when running this model. I've tried a few things including creating a blank dictionary, or creating an additional variable to contain the x[j+1] list.

How do I write this recursive equation in PulP? Or is there another library which can handle this equation better?

The model was initialized with the following dictionaries and objective function

from pulp import *

period = ['Q1', 'Q2', 'Q3', 'Q4']
z = [200, 0, 0, 500]
x = [50, 100, 100, 300]
cap = [1000, 1000, 1000, 1000]
z_dict = dict(zip(period, z))
x_dict = dict(zip(period, x))
cap_dict = dict(zip(period, cap))
model = LpProblem("Simple Model", LpMinimize)

y = LpVariable.dicts("decision",  period, lowBound=0, cat='Continuous')
b = LpVariable.dicts("binary", period, cat='Binary')

model += (lpSum([15*b[j] for j in period]) + lpSum([y[j]*10 for j in period])) # Objective Function`

for j in period:
    model += lpSum([x[j]]) + y[j] >= z[j]
    model += lpSum([y[j]]) <= lpSum([cap_dict[j]*b[j]])
    model += lpSum([y[j] + x[j] -z[j]]) == x[j+1] # The constraint in question

I think your basic problem is that x[j+1] causes an out of bounds problem.

With the following changes a result is produced:

period = [0, 1, 2, 3]

and

for j in period:
    model += lpSum([x[j]]) + y[j] >= z[j]
    model += lpSum([y[j]]) <= lpSum([cap_dict[j]*b[j]])
    if j < max(period):
        model += lpSum([y[j] + x[j] -z[j]]) == x[j+1] # The constraint in question

Additionally added the following to show the result:

model.solve()
print("Status : ", pulp.LpStatus[model.status])
print("Result : ", pulp.value(model.objective))
for v in model.variables():
    print(v.name, "=", v.varValue)

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