I am struggling on making multiple constraints using for loop in Python Pyomo. My code concept is the following
T = 504
model.times = RangeSet(0, T-1)
model.Machines = Set(initialize = Machines_parameters.keys())
Then I've divided model.times in 3 sets of the same length and now I want to write specific constraints for each of this part of the set. The following is an equivalent but simplified version of the code:
for k in range(3): #number of parts in which I've divided the set [(0,167),(168,335),(336,503)]
for j in range(cluster_index[k][0], cluster_index[k][1]): #respectively first and last number of the subset
def logic_constr(model,i):
if j >= const1[k] and j < const2[k]:
return model.z[i, j + 1] - model.z[i, j] == model.dsu[i, j + 1] - model.dsd[i, j + 1]
else j==const2[k]:
return model.z[i,const2[k]] - model.z[i,j] == model.dsu[i,const1[k]] - model.dsd[i,const1[k]]
model.logic_constr = Constraint(model.Machines, rule = logic_constr)
What I would like to do is to iterativelly create 504 different constraints, each one with its own rule. Do you have any suggestion on how to do it?
The way you have formulated the constraint right now, you will only end up with having one constraint at the end, since after every loop, the constraint will be overwritten.
Since, as you say and according to your for loops, you also want one constraint per time step, this is much simpler.
First, you need to define the constraint as:
model.logic_constr = Constraint(model.Machines, model.times, rule = logic_constr)
This means that the constraint will be applied for each member of the set model.times
i.e. there will be 504 constraints for each element of the set model.Machines.
Then all your ifs and the for loops can go into your definition of the logic_constr
function.