How to save (pickle) a model instance in pyomo

后端 未结 2 1327
后悔当初
后悔当初 2020-12-11 12:08

I want to create a model instance and then save it so I can load and solve at a later time (the initialization takes quite long compared to the solving). When I tried this i

相关标签:
2条回答
  • 2020-12-11 12:47

    The solution is the cloudpickle module, regular pickle has problems pickling functions. An example:

    import cloudpickle
    
    with open('test.pkl', mode='wb') as file:
       cloudpickle.dump(instance, file)
    
    
    with open('test.pkl', mode='rb') as file:
       instance = cloudpickle.load(file)
    
    0 讨论(0)
  • 2020-12-11 13:09

    It looks like pickle (and also cloudpickle) will not work when DerivativeVar is used.

    from pyomo.environ import *
    from pyomo.dae import *
    import pickle
    import dill
    model = ConcreteModel()
    model.x = ContinuousSet(initialize=(0., 1.))
    model.y = Var(model.x, initialize=1.)
    with open('model1.pickle', 'wb') as f:
        pickle.dump(model, f)
    
    model.dydx = DerivativeVar(model.y, wrt=model.x)
    with open('model2.pickle', 'wb') as f:
        try:
            pickle.dump(model, f)
        except TypeError:
            dill.dump(model, f)
    

    dill appears to work instead for pickling a weakref: Pickling weakref in Python

    0 讨论(0)
提交回复
热议问题