我正在尝试并行化下面的python函数,该函数涉及有限元分析。特别是,我试图使函数中的for循环并行运行。我已经使用parfor在Matlab中完成了此操作,并且我尝试在python中执行相同的操作。
def assemble(u):
K=np.zeros((ndof,ndof)) # initializing global stiffness matrix
Fint=np.zeros(ndof)
Fext=np.zeros(ndof)
for iel in range(tne):
elnodes=elems[iel,:] # nodes of the local elements
xcel=nodes[elnodes,0] # x-coordinates for the local elements
ycel=nodes[elnodes,1] # y-coordinates for the local elements
zcel=nodes[elnodes,2] # z-coordinates for the local elements
dof=np.array([3*elnodes[0],3*elnodes[0]+1,3*elnodes[0]+2,3*elnodes[1],\
3*elnodes[1]+1,3*elnodes[1]+2,3*elnodes[2],3*elnodes[2]+1,\
3*elnodes[2]+2,3*elnodes[3],3*elnodes[3]+1,3*elnodes[3]+2,\
3*elnodes[4],3*elnodes[4]+1,3*elnodes[4]+2,3*elnodes[5],\
3*elnodes[5]+1,3*elnodes[5]+2,3*elnodes[6],3*elnodes[6]+1,\
3*elnodes[6]+2,3*elnodes[7],3*elnodes[7]+1,3*elnodes[7]+2]).flatten()
u_el=u[dof]
strain,stress=SS(xcel,ycel,zcel,u_el)
ESM,Fint_e,Fext_e=Elem_KF(xcel,ycel,zcel,strain,stress)
K[np.ix_(dof,dof)]+=ESM
Fint[dof]+=Fint_e
Fext[dof]+=Fext_e
R=Fext-Fint
return K,Fint,Fext,R
任何帮助将不胜感激。谢谢!
您可以使用Pools,同时使用多个进程。
from multiprocessing import Pool
p = Pool(n_threads)
for iel in range(tne):
#function will calculate all the parameters you have inside the loop
results = p.apply(function,args=(x,y,z,etc,))
#wait for all threads to return their value
p.close()
p.join()