有没有一种方法可以序列化一个sympy-ufunched函数?

2024-09-28 22:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有方法可以序列化或保存使用SymPy的autowrap模块中的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小时来恢复二进制函数


Tags: 函数fromimport表达式二进制wrapperpicklemodule
1条回答
网友
1楼 · 发布于 2024-09-28 22:34:19

明白了。这实际上比使用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(同一根目录):

^{pr2}$

可能还有更好的方法(例如,有没有一种简单的方法来命名模块及其嵌入函数?),但这暂时有效。在

[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

相关问题 更多 >