save and load solution of a model

619 views
Skip to first unread message

Federico Lozano Santamaria

unread,
Jan 19, 2017, 9:16:30 AM1/19/17
to Pyomo Forum
Hello,

Is there a way to save the whole solution of a problem, for example in a .sol file or any other format, and then load it as a starting point for the same problem or for another similar one? What I have in mind is something similar to the gdx files of gams.

Federico

Gabriel Hackebeil

unread,
Jan 19, 2017, 12:00:38 PM1/19/17
to pyomo...@googlegroups.com
Python has many modules for taking an object like a dictionary and easily saving / loading that object to / from a file (e.g., json, yaml, pickle).

What you need to do on the Pyomo side is create special component names that Pyomo can use to efficiently find an object on a model when you want to reload the solution. Here is an example (that you can customize):

from pyomo.environ import *
from pyomo.core.base.block import generate_cuid_names

model = ConcreteModel()
model.x = Var()
model.X = Var([1,2])

model.x.value = 2
model.X[1].value = 3
model.X[2].value = 4

# generate cuid names efficiently in bulk                                                                                 
labels = generate_cuid_names(model)

# store the variable values into a dictionary                                                                             
solution = {}
for var in model.component_data_objects(Var):
    solution[labels[var]] = var.value

# save the solution                                                                                                       
import json
with open("junk.json", "w") as f:
    json.dump(solution, f)
del solution

model.x.value = None
model.X[1].value = None
model.X[2].value = None

# load the solution                                                                                                       
with open("junk.json") as f:
    solution = json.load(f)

# store the solution into the variables                                                                                   
for cuid, val in solution.items():
    model.find_component(cuid).value = val

Note that you can modify this to store other properties of a “solution”, such as whether or not a variable has been fixed, constraint duals, etc.

Gabe

--
You received this message because you are subscribed to the Google Groups "Pyomo Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyomo-forum...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Federico Lozano Santamaria

unread,
Jan 19, 2017, 12:10:10 PM1/19/17
to Pyomo Forum
Thanks for your response Gabe
Reply all
Reply to author
Forward
0 new messages