Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

python - How to save (pickle) a model instance in pyomo

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 it gave me the following error.

with open('model.pickle', 'w') as f:
    pickle.dump(instance, f)

AttributeError: Can't pickle local object 'Euphemia.init..obj_expression

The objective function is this:

    def obj_expression(model):
        curve = sum(model.x[area, hour, Type, index] * model.Q[area, hour, Type, index] * 
                    ( model.P1[area, hour, Type, index] + model.P0[area, hour, Type, index] ) / 2  
                        for (area, hour, Type, index) in model.Curve )
        bids = sum(model.y[area, index] * model.PB[area, index] * 
                       sum( model.QB[area, index, hour] for (hour) in model.Hours ) 
                               for (area, index) in model.Bids  )
        return curve + bids
    self.model.OBJ = pe.Objective(rule = obj_expression, sense = pe.maximize)

does anybody know how to save a concrete model?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...