简介
在本实验中,你将学习如何使用 Matplotlib 创建电偶极子的梯度图。你将学习如何创建三角剖分、细化数据以及计算电场。最后,你将绘制三角剖分、等势线和矢量场。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
创建点的 x 和 y 坐标
n_angles = 30
n_radii = 10
min_radius = 0.2
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
解释:
n_angles是圆中角度的数量。n_radii是圆的数量。min_radius是圆的最小半径。radii是半径数组。angles是角度数组。x是 x 坐标数组。y是 y 坐标数组。
计算偶极子的电势
def dipole_potential(x, y):
"""The electric dipole potential V, at position *x*, *y*."""
r_sq = x**2 + y**2
theta = np.arctan2(y, x)
z = np.cos(theta)/r_sq
return (np.max(z) - z) / (np.max(z) - np.min(z))
V = dipole_potential(x, y)
解释:
dipole_potential是一个计算电偶极子电势的函数。V是电偶极子电势的数组。
创建三角剖分
triang = Triangulation(x, y)
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
解释:
Triangulation是一个从一组点创建德劳内三角剖分的类。triang是Triangulation类的一个实例。triang.set_mask会屏蔽掉不需要的三角形。
细化数据
refiner = UniformTriRefiner(triang)
tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)
解释:
UniformTriRefiner是一个用于细化三角剖分以创建更精确绘图的类。refiner是UniformTriRefiner类的一个实例。tri_refi和z_test_refi分别是细化后的三角剖分和电势值。
计算电场
tci = CubicTriInterpolator(triang, -V)
(Ex, Ey) = tci.gradient(triang.x, triang.y)
E_norm = np.sqrt(Ex**2 + Ey**2)
解释:
CubicTriInterpolator是一个使用三次多项式进行数据插值的类。tci是CubicTriInterpolator类的一个实例。(Ex, Ey)是电场。E_norm是归一化电场。
绘制三角剖分、电势等值线和矢量场
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.use_sticky_edges = False
ax.margins(0.07)
ax.triplot(triang, color='0.8')
levels = np.arange(0., 1., 0.01)
ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap='hot',
linewidths=[2.0, 1.0, 1.0, 1.0])
ax.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
units='xy', scale=10., zorder=3, color='blue',
width=0.007, headwidth=3., headlength=4.)
ax.set_title('Gradient Plot: Electrical Dipole')
plt.show()
解释:
fig和ax分别是图形和坐标轴对象。ax.set_aspect设置坐标轴的纵横比。ax.use_sticky_edges和ax.margins设置坐标轴的边距。ax.triplot绘制三角剖分。ax.tricontour绘制电势等值线。ax.quiver绘制矢量场。ax.set_title设置图形的标题。
总结
在本实验中,你学习了如何使用 Matplotlib 创建电偶极子的梯度图。你学习了如何创建三角剖分、细化数据以及计算电场。最后,你绘制了三角剖分、电势等值线和矢量场。