Search code examples
pythonfunctionoptimizationmodelpyomo

Put in a loop an optimization model


I would like to put in a loop an optimization model in order to do some reoptimization with a persistent solver. I have writen all the code to extract the data and the model. Now I need to put the different parts in functions in order to call them.

The goal is to do something like that:

for file in files:
    data = extract_data(file)
    model = construct_model(data)
    model.solve()
    for iter in ...:
        # resolve model
        # save results

Basically I have only used conditional statement to extract my data and never used function, so what I did is copy past all the code into a function like that: (I have a more than 1000 lines):

def extract_data():    
    Nurse_DayoffID_D = {}
    UDay_ID = []
    for k,v in ID_Dayoff.items():
        for x,d in enumerate(v):
            Nurse_DayoffID_D[(k,x+10)]=d
            UDay_ID.append(x+10)
            
    [...]
    return

Now if I do the same with the concrete model:

def model():
    model.N = Set(initialize = N)
    [...]
    def obj_function(model):
         return(
             sum(Penalty_Sigma * model.w[n,d1,d2] + Penalty_Tau * model.r[n,d1,d2] for (d1,d2) in P)
             [...]
         )
    model.ObjFunction = Objective(rule=obj_function, sense=minimize)
    def constraint_1(model, s, d):
        return sum(model.x[n, s, d] for n in model.N) == R[d,s]

    model.C1 = Constraint(model.S, model.D, rule=constraint_1)
    
    [...]
    
    return


for file in files:
        data = extract_data(file)
        model = construct_model(data)
        model.solve()
        for iter in ...:
            # resolve model
            # save results

Do you think its gone work ?


Solution

    1. It will work.
    2. I recommend you do not use the word iter as it is a Python built-in function.

    For a given number of iterations, you could do:

    # Run it 3 times
    for _ in range(3):
        results = process_model()
        save_results(results)