1
$\begingroup$

I am looking to set variables in my Pyomo model by using a loop, so that they can be created automatically. However, each variable also contains bounds.

I was hoping that it can loop through a dictionary to assign the bounds to each variable.

Current code

coeffs = [120, 600, 800, 200]
y_target = 165120

rangeStore = []

for index in range(4):
    # Define model and variables
    model = ConcreteModel()
    model.b = Var(bounds=(0,15))
    model.c = Var(bounds=(15,60))
    model.d = Var(bounds=(60,150))
    model.e = Var(bounds=(150,300))
    model_x = [model.b,model.c, model.d, model.e]

    # Model Constraint
    def weight_rule(model):
        return sum(coeffs[i] * model_x[i] for i in range(len(coeffs))) == y_target 
    model.weight = Constraint( rule=weight_rule )

    # Model Objective
    obj = model_x[index]
    model.objective = Objective(expr=obj, sense=minimize)

    # Solve the model
    solver = SolverFactory('glpk')
    solver.solve(model)
    
    # Store value
    rangeStore.append([value(model_x[i]) for i in range(len(coeffs))])

Part I want to be created in loop

    model.b = Var(bounds=(0,15))
    model.c = Var(bounds=(15,60))
    model.d = Var(bounds=(60,150))
    model.e = Var(bounds=(150,300))
$\endgroup$
1
  • 1
    $\begingroup$ You don't need a loop for that, see my answer... $\endgroup$ Feb 16, 2021 at 15:31

2 Answers 2

2
$\begingroup$
coeffs = [120, 600, 800, 200]
y_target = 165120

rangeStore = []

bound_dic = {0:[0,15],1:[15,60],2:[60,150],3:[150,300]}
model = ConcreteModel()
model.ind = set(bound_dic.keys())

def b_rule(model, i):
    return (bound_dic[i][0], bound_dic[i][1])

model.x = Var(model.ind, bounds = b_rule)

model.weight = Constraint(expr = sum(coeffs[i] * model.x[i] for i in range(len(coeffs))) == y_target)

# Model Objective
obj = model.x[index]
model.objective = Objective(expr=obj, sense=minimize)

# Solve the model
solver = SolverFactory('glpk')
solver.solve(model)

# Store value
rangeStore.append([value(model.x[i]) for i in range(len(coeffs))])
$\endgroup$
1
  • 1
    $\begingroup$ Thank you @Oguz, this is perfect! $\endgroup$
    – Jwem93
    Feb 16, 2021 at 21:58
1
$\begingroup$

probably not the solution of you problem, but best fitting to you question in header:

model.add_component('abc', Var(idx, domain=pmo.Boolean))
model.component('abc').pprint()
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.