|
楼主 |
发表于 2013-12-11 05:37
|
显示全部楼层
本帖最后由 Rainyboy 于 2013-12-10 22:54 编辑
#4,2D,梯度、旋度和散度的计算和展示
[code=Python width=600px]def getGrade2D(Field,dx,dy):
Ny,Nx = Field.shape
Gx = np.zeros_like(Field)
Gy = np.zeros_like(Field)
for i in range(0,Ny):
Gx[i,:] = DDiff5(Field[i,:],dx,Nx)
for j in range(0,Nx):
Gy[:,j] = DDiff5(Field[:,j],dy,Ny)
return Gx,Gy
def getDiv2D(Gx,Gy,dx,dy):
Ny,Nx = Gx.shape
Tx = np.zeros_like(Gx)
Ty = np.zeros_like(Gx)
for i in range(0,Ny):
Tx[i,:] = DDiff5(Gx[i,:],dx,Nx)
for j in range(0,Nx):
Ty[:,j] = DDiff5(Gy[:,j],dy,Ny)
return Tx+Ty
def getRot2D(Gx,Gy,dx,dy):
Ny,Nx = Gx.shape
GXy = np.zeros_like(Gx)
GYx = np.zeros_like(Gx)
for i in range(0,Ny):
GYx[i,:] = DDiff5(Gy[i,:],dx,Nx)
for j in range(0,Nx):
GXy[:,j] = DDiff5(Gx[:,j],dy,Ny)
return GYx-GXy[/code]
[code=Python width=600px]def ARRAY_CONT(X,Y,U,V,
labels=('X','Y','2D_VELOCITY_FIELD'),
copt='speed',
wopt='vary',
dst = 1):
speed = np.sqrt(U*U + V*V)
if wopt == 'constant':
wset = 0.5
elif wopt == 'vary':
wset = 1.5*speed/np.max(speed)+0.5
if copt == 'speed':
plt.streamplot(X, Y, U, V, color=speed, cmap=plt.cm.cool,density=dst, linewidth = wset)
plt.colorbar()
else:
plt.streamplot(X, Y, U, V, color=copt,density=dst, linewidth = wset)
plt.xlabel(labels[0])
plt.ylabel(labels[1])
plt.title(labels[2])[/code]
###例子####
###例一:绘出给定矢量场,计算其散度和旋度###
[code=Python width=600px]def test_5():
dx = dy = 40.0/200
Y, X = np.mgrid[-20:20:200j, -20:20:200j]
U = X*np.sin(X)-Y
V = X +Y*np.cos(Y)
plt.figure(3)
ARRAY_CONT(X,Y,U,V,dst=2)
plt.axis('equal')
Div = getDiv2D(U,V,dx,dy)
plt.figure()
plt.contourf(X,Y,Div,15)
plt.colorbar()
Rot = getRot2D(U,V,dx,dy)
plt.figure()
plt.contourf(X,Y,Rot,15)
plt.colorbar()
[/code]
散度:
旋度:
###例二:计算标量场的梯度(五个点电荷构成的电场)###
[code=Python width=600px]def FI3(x,y):
k = 1e-5
qlist = [3.5,-1,+1,-1,-1]
xlist = [0,0,0,-1,1]
ylist = [0,1,-1,0,0]
f = np.zeros_like(x)
for i in range(0,5):
f += qlist/(np.power(x-xlist,2)+np.power(y-ylist,2))
return f*k
def test_3():
Nx,Ny = (200,200)
Xmin,Xmax = -3.0,3.0
Ymin,Ymax = -3.0,3.0
dx = (Xmax-Xmin)/Nx
dy = (Ymax-Ymin)/Ny
Y, X = np.mgrid[Ymin:Ymax:Ny*1j,Xmin:Xmax:Nx*1j]
Field = FI3(X,Y)
plt.figure()
plt.contour(X,Y,Field,15)
plt.colorbar()
Gx,Gy = getGrade2D(Field,dx,dy)
ARRAY_CONT(X,Y,Gx,Gy,labels=('X','Y',''),copt='k',wopt='constant',dst = 3)[/code]
|
|