我想计算具有形状(Nmesh,Nmesh,Nmesh)的3D笛卡尔网格的一阶偏导数,例如。Nmesh=512通过四阶精度方案,即
f ′(n)= 2*(f(n+1)-f(n-1))/(3dh)-(f(n+2)-f(n-2))/(12dh)。
为此,我写了一个Python函数,如下所示。但是,我看到不同条件分支之间的某些行非常相似。我可以进一步简化这个函数吗?
import numpy as np
def partial( arr, Nmesh, dh, axis=0 ):
'''
The partial derivative of the 3D Cartesian mesh with periodic
boundary conditions, computed by the fourth-order accuracy scheme.
'''
dh1 = 2/(3*dh)
dh2 = -1/(12*dh)
if (axis==0):
arr_ = np.pad(arr, [(2,2), (0,0), (0,0)], mode='wrap')
diff1 = arr_[3:Nmesh+3,:,:] - arr_[1:Nmesh+1,:,:]
diff2 = arr_[4:Nmesh+4,:,:] - arr_[0:Nmesh,:,:]
return dh1*diff1 + dh2*diff2
elif (axis==1):
arr_ = np.pad(arr, [(0,0), (2,2), (0,0)], mode='wrap')
diff1 = arr_[:,3:Nmesh+3,:] - arr_[:,1:Nmesh+1,:]
diff2 = arr_[:,4:Nmesh+4,:] - arr_[:,0:Nmesh,:]
return dh1*diff1 + dh2*diff2
elif (axis==2):
arr_ = np.pad(arr, [(0,0), (0,0), (2,2)], mode='wrap')
diff1 = arr_[:,:,3:Nmesh+3] - arr_[:,:,1:Nmesh+1]
diff2 = arr_[:,:,4:Nmesh+4] - arr_[:,:,0:Nmesh]
return dh1*diff1 + dh2*diff2
1条答案
按热度按时间8zzbczxx1#
正如mozway的评论,你可以使用
swapaxes
函数来做类似的事情: