how to access variable of previous calculation in pyomo optimization mode

Viewed 35

how do I have to write this equivalent from gurobi in pyomo?

--> I want build the model in a loop and need to access a variable/result of the previous step:

variables = {'A_0': 1, 'B_0':2, 'C_0':3}
for ix in range(1,77):
    variables[f'A_{ix}'] = model.addVar(vtype=GRB.CONTINUOUS, name=f'A_{ix}', lb=0.0)
    variables[f'B_{ix}'] = model.addVar(vtype=GRB.CONTINUOUS, name=f'B_{ix}', lb=0.0, ub=77)
    variables[f'C_{ix}'] = model.addVar(vtype=GRB.CONTINUOUS, name=f'C_{ix}', lb=0.0)

    model.addConstr(variables[f'C_{ix}'] <= variables[f'A_{ix}'] * variables[f'B_{ix-1}'])
1 Answers

Sure. You can pull the value after the solve and do anything you want with it...

You can reincorporate it into a constraint (shown), put it in a bound on the variable, or fix() the variable with that value, etc. etc.

import pyomo.environ as pyo

def model_runner(prior_value : float=None):
    m = pyo.ConcreteModel()

    m.X = pyo.Var()

    constraint_lim = prior_value if prior_value else 10

    m.c = pyo.Constraint(expr=m.X <= constraint_lim)

    m.obj = pyo.Objective(expr=m.X*5, sense=pyo.maximize)

    res = pyo.SolverFactory('glpk').solve(m)

    return pyo.value(m.obj), pyo.value(m.X)

x_lim = None
for i in range(5):
    obj, x_lim = model_runner(x_lim)
    print(f'current objective {obj} with x_lim: {x_lim}')
    x_lim -= 1

Output:

current objective 50.0 with x_lim: 10.0
current objective 45.0 with x_lim: 9.0
current objective 40.0 with x_lim: 8.0
current objective 35.0 with x_lim: 7.0
current objective 30.0 with x_lim: 6.0
Related