ken_a ken_a - 4 months ago 49
Python Question

Pyomo: Access Solution From Python Code

I have a linear integer programme I want to solve. I installed solver glpk (thanks to this answer) and pyomo. I wrote code like this:

from pyomo.environ import *
from pyomo.opt import SolverFactory

a = 370
b = 420
c = 2

model = ConcreteModel()
model.x = Var([1,2], domain=NonNegativeIntegers)
model.Objective = Objective(expr = a * model.x[1] + b * model.x[2], sense=minimize)
model.Constraint1 = Constraint(expr = model.x[1] + model.x[2] == c)
# ... more constraints

opt = SolverFactory('glpk')

results = opt.solve(model)


This produces solution to file
results.yaml
.

I have many problems I want to solve using the same model but with different
a
,
b
, and
c
values. I want to assign different values to
a
,
b
, and
c
, solve the model, obtain solution of
model.x[1]
and
model.x[2]
, and have a listing of
a
,
b
,
c
,
model.x[1]
and
model.x[2]
. I read documentation but examples only write solutions to file such as
results.yaml
.

Is there any way I can access to solution values from code?

Thanks,

Answer

I'm not sure if this is what you are looking for, but this is a way that I have some variables being printed in one of my scripts.

from pyomo.environ import *
from pyomo.opt import SolverFactory
from pyomo.core import Var

M = AbstractModel()
opt = SolverFactory('glpk')

# Vars, Params, Objective, Constraints....

instance = M.create_instance('input.dat') # reading in a datafile
results = opt.solve(instance, tee=True)
results.write()
instance.solutions.load_from(results)

for v in instance.component_objects(Var, active=True):
    print ("Variable",v)
    varobject = getattr(instance, str(v))
    for index in varobject:
        print ("   ",index, varobject[index].value)
Comments