jonathf / chaospy

Chaospy - Toolbox for performing uncertainty quantification.
https://chaospy.readthedocs.io/
MIT License
443 stars 87 forks source link

Saving Chaospy Objects to File #69

Closed pvaezi closed 6 years ago

pvaezi commented 6 years ago

Hi,

Is there anyway I can save the Chaospy objects to the file? I couldn't pickle them.

Thanks, Payam

jonathf commented 6 years ago

The chaospy objects should be picklable, so if it is failing it is a bug.

Do you mind providing OS, Python version, Chaospy version, and a minimal code example that replicates the behavior?

pvaezi commented 6 years ago

Thanks for your quick response. The system specs I'm running on:

Example of simple code and error I get:

>>> import chaospy
>>> tmp = chaospy.Normal(mu=0.,sigma=1.)
>>> import pickle
>>> pickle.dumps(tmp)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 1380, in dumps
    Pickler(file, protocol).dump(obj)
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 425, in save_reduce
    save(state)
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 655, in save_dict
    self._batch_setitems(obj.iteritems())
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 669, in _batch_setitems
    save(v)
  File "/opt/python/2.7.11/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/opt/python/2.7.11/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
flo2k commented 6 years ago

I also have this problems when pickling distributions. For loading/saving I moved to the dill library. With dill it works perfectly for me.

jonathf commented 6 years ago

Thank you @flo2k. That is a good suggestion.

I will also note that this problem is not reproducible in Python3. So if you end up having to upgrade your code to the newest python, pickling choaspy distributions will work out of the box.

pvaezi commented 6 years ago

Thanks for the comments, using dill library solved my problem.