我一直在为研究磁场建模。下面的代码使我可以计算任意给定点(x,y,z)的正确字段值;但是,当我通过代码传递一个np.meshgrid
对象时,结果开始变得不灵通。
这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
def normal_vector(u):
return u/np.linalg.norm(u)
class Path:
"""
This defines the Path class which allows for the calculations of the magnetic field.
"""
def __init__(self, xs, ys, zs):
self.points = zip(*[xs, ys, zs]) # defines the points
self.x = xs
self.y = ys
self.z = zs
self.path_vectors = [(self.points[i + 1][0] - self.points[i][0],
self.points[i + 1][1] - self.points[i][1],
self.points[i + 1][2] - self.points[i][2]) for i in range(len(self.x) - 1)]
def get_length(self):
"""
Calculates the path length
:return: returns float length
"""
return sum([np.sqrt(((self.x[i + 1] - self.x[i]) ** 2) + ((self.y[i + 1] - self.y[i]) ** 2) + (
(self.z[i + 1] - self.z[i]) ** 2)) for i in
range(len(self.x) - 1)])
def get_magnetlic_function(self,axes,current=1.0,magnetic_constant = 1.25663706212e-6):
magnetic_parameter = (current*magnetic_constant)/(4*np.pi)
field_function = lambda x,y,z: sum([magnetic_parameter*np.cross(self.path_vectors[j],normal_vector(np.stack([x-self.x[j],y-self.y[j],z-self.z[j]],axis=-1)))/(np.linalg.norm(np.stack([x-self.x[j],y-self.y[j],z-self.z[j]],axis=-1))**2) for j in range(len(self.x)-1)]).swapaxes(0,-1)
return field_function
n = 200
r = 1
h = 5
grid_x,grid_y,grid_z = np.meshgrid(np.linspace(-10,10,5),
np.linspace(-10,10,5),
np.linspace(-10,10,5))
c = h / (2 * n * np.pi)
t = np.linspace(0,2*np.pi, 5000)
xp = 3*np.cos(t)
yp = 3*np.sin(t)
zp = 0*t
p = Path(list(xp), list(yp), list(zp))
func = p.get_magnetlic_function([grid_x,grid_y,grid_z])
u,v,w = func(grid_x,grid_y,grid_z)
r = np.sqrt(u**2+v**2+w**2)
print func(-10.0,00.0,0.0)
ax1 = plt.subplot(111,projection='3d')
ax1.plot(xp,yp,zp,'r-')
ax1.plot([-10],[0],[0],'ro')
ax1.quiver(grid_x,grid_y,grid_z,u/r,v/r,w/r,length=1)
plt.show()
很明显,在底部附近,如果运行代码,则矢量在-10.0,00.0,0.0处的方向与所打印的值不同。为什么? 从代码中,我在这里收到颤动图:
答案 0 :(得分:1)
当尝试查找由电流分布引起的磁场时,我发现考虑成对相互作用通常更为清楚(尽管lambda
函数的作用更强。考虑这种方法
class Path:
# ...
def mag_func(self, x, y, z, current = 1.0, mag_const = 1.25663706212e-6):
mag_param = current * mag_const / (4 * np.pi)
s = x.shape
res = np.zeros((s[0],s[1],s[2],3))
for i in range(s[0]):
for j in range(s[1]):
for k in range(s[2]):
for idx, (xc, yc, zc) in enumerate(zip(self.x, self.y, self.z)):
res[i,j,k,:] += mag_param * \
np.cross(self.path_vectors[idx], [x[i,j,k] - xc,
y[i,j,k] - yc, z[i,j,k] - zc]) / \
np.linalg.norm([x[i,j,k] - xc, y[i,j,k] - yc,
z[i,j,k] - zc])**2
return res[:,:,:,0], res[:,:,:,1], res[:,:,:,2]
#...
u, v, w = p.mag_func(grid_x, grid_y, grid_z)
r = np.sqrt(u**2+v**2+w**2)
ax1 = plt.subplot(111,projection='3d')
ax1.plot(xp, yp, zp, 'r-')
ax1.quiver(grid_x, grid_y, grid_z, u/r, v/r, w/r,length=1)
plt.show()
哪个会给
这是载流导线周围磁场的正确表示。
至于为什么lambda
首先不起作用的问题,我认为这是由于通过np.meshgrid
创建了网格,使得外部sum
总和超过了应有的分数。以上述方式进行迭代可解决该问题。可以使用该lambda
函数,但是我认为您仍然必须按照所示的方式遍历grid_x
,grid_y
和grid_z
。>