如何解决加快 Sympy 的自动换行
我正在尝试使用 autowrap
函数转换大量 Sympy 表达式。然而,这是一个缓慢的过程。
我试过与一些 Python 包并行化,但我不断收到错误。
我的问题是,是否可以加快自动包装过程?喜欢并行化还是什么?
如果有必要,我可以发布我的部分脚本来展示如何解决我的特殊情况,但我想尝试更通用的方法。
编辑:我的代码的工作方式是(可能不是最好的方式)它从一般表达式及其导数(感兴趣的人的欧拉-拉格朗日方程)创建一些表达式。然后将所述表达式存储在一个数组(列表列表)中,从那里调用它们以进行自动包装。完成后,它们将保存在另一个数组中。
这我可以用一个简单的 for 循环来完成。当我有这样的表达式时,它非常非常慢,比如说 400(也就是 20^2)个表达式。
我已经尝试使用 ProcesspoolExecutor
中的 concurrent.futures
,因为我已经在代码的另一部分使用了它。但这会引发 brokenProcesspool: A process in the process pool was terminated abruptly while the future was running or pending.
错误,除非我尝试仅包装一个函数。然后它工作正常。
ThreadPoolExecutor
做同样的事情(或者它抱怨 wrapper_module_#
丢失,有时在我指出的临时目录中)。
从 multiprocessing.Pool
我只得到 Exception in thread Thread-#:
然后它会一直运行,除非我停止它。然后它说ModuleNotFoundError: No module named 'wrapper_module_#'
。
所以我不确定为什么这些模块实际上没有丢失。
我会尽量缩短我的代码,我会在几个小时内发布。
# This is the setup (declaring equations and such)
import sympy as sp
from sympy.utilities.autowrap import autowrap
import itertools
import os # <- To change directories because it appears that it changes automatically when using Process and ThreadPoolExecutor
from concurrent.futures import ProcesspoolExecutor,ThreadPoolExecutor
cwd = os.getcwd()
x,y,dx,dy = sp.var('x y dx dy')
eq = list()
eq.append(sp.cos(x)*dx + y*dy) # <- Some random equations
eq.append(3*x*dx + dy) # equations as examples.
coeff1 = [eq[0].coeff(dx),eq[0].coeff(dy)] # <- Coefficients of eq[0]
coeff2 = [eq[1].coeff(dx),eq[1].coeff(dy)] # <- Coefficients of eq[1]
coeff = [coeff1,coeff2] # <- This is my list of lists of coefficients
# (currently Sympy expressions)
arguments = [x,y] # <- Arguments for my equations.
有趣的部分来了:
- 使用列表理解为
autowrap
数组的每个条目调用coeff
工作正常。
coeffComp = [[autowrap( coeff[i][j],backend='cython',tempdir=cwd+'/CoefficientsComprehension',args=arguments) for j in range(2)] for i in range(2)]
# To visualize:
print(coeff)
# returns [[cos(x),y],[3*x,1]]
# If I evaluate in (x=1,y=0)
print([[coeffComp[i][j](1,0) for j in range(2)] for i in range(2)])
# returns [[0.5403023058681398,0.0],[3.0,1]],which is correct.
- 但是,尝试使用
ProcesspoolExecutor
或ThreadPoolExecutor
def AutoWrapCoefficients(Index): # <- Function to map
i,j = Index
return autowrap( coeff[i][j],tempdir='./CoefficientsPoolExecutor',args=arguments)
def ToPyOfArray(): # <- Mapping function
TempArr = list()
with ThreadPoolExecutor() as executor:
results = executor.map(AutoWrapCoefficients,itertools.product(range(2),repeat=2))
for res in results:
os.chdir(cwd)
TempArr.append(res)
return TempArr
if __name__ == '__main__':
coeffFunctions = ToPyOfArray() # <- Throws described errors
- 还有
multiprocessing
:
from multiprocessing import Pool
if __name__ == '__main__':
with Pool() as p:
p.map( AutoWrapCoefficients,repeat=2)) # <- Throws described errors
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。