【问题标题】:Is there a way to serialize a sympy ufuncify-ied function?有没有办法序列化一个 sympy ufuncify-ied 函数?
【发布时间】:2017-11-16 14:14:03
【问题描述】:

有没有办法序列化或保存使用 SymPy 自动包装模块中的 ufuncify 工具二进制化的函数?

这里有一个使用dill:How to serialize sympy lambdified function? 的解决方案,但这仅适用于lambdified 函数。

这是一个最小的工作示例来说明:

>>> import pickle
>>> import dill
>>> import numpy
>>> from sympy import *
>>> from sympy.utilities.autowrap import ufuncify

>>> x, y, z = symbols('x y z')
>>> fx = ufuncify([x], sin(x))

>>> dill.settings['recurse'] = True
>>> dill.detect.errors(fx)
pickle.PicklingError("Can't pickle <ufunc 'wrapper_module_0'>: it's not found as __main__.wrapper_module_0")

动机:我有几个 5000 万字符长的 SymPy 表达式我想加快速度; ufuncify 工作得非常好(仅比 lambidfy 提高了三个数量级),但 ufuncify 每个表达式需要 3 小时。我希望能够不时利用ufuncify-ied 表达式(无需等待一天重新处理它们)。 更新:为了说明,计算机进入睡眠状态杀死了我的 python 内核,现在我需要等待大约 10 小时才能恢复二进制化函数

【问题讨论】:

    标签: python serialization sympy numpy-ufunc


    【解决方案1】:

    知道了。这实际上比使用dill/pickle 更简单,因为autowrap 模块生成和编译C 代码(默认情况下),可以作为C 扩展模块[1] [2] 导入。

    保存生成代码的一种方法是简单地为autowrap[3] 指定临时目录,例如:

    Python环境1:

    import numpy
    from sympy import *
    from sympy.utilities.autowrap import ufuncify
    
    x, y, z = symbols('x y z')
    fx = ufuncify([x], sin(x), tempdir='tmp')
    

    Python环境2(同根目录):

    import sys
    sys.path.append('tmp')
    import wrapper_module_0
    
    wrapper_module_0.wrapped_8859643136(1)
    

    可能有更好的方法(例如,有没有一种简单的方法来命名模块及其嵌入的函数?),但现在可以使用。

    [1]http://www.scipy-lectures.org/advanced/interfacing_with_c/interfacing_with_c.html

    [2]https://docs.python.org/2/extending/extending.html

    [3]http://docs.sympy.org/latest/modules/utilities/autowrap.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 2021-08-15
      • 2011-02-10
      • 2018-05-27
      相关资源
      最近更新 更多