【发布时间】:2015-06-15 01:33:04
【问题描述】:
这是Biot-Savart law 的简单近似值。
我已经在函数calc()中实现了积分(sum),
如果空间点的数量很大,比如 10^7 或 10^8 -ish,是否可以编写 calc 以更有效地使用 NumPy 数组?感谢您的建议!
def calc(points, x_seg, idl_seg):
r = points[:, None, :] - x_seg[None, :, :] # START CALCULATION
bottom = ((r**2).sum(axis=-1)**1.5)[...,None] # 1/|r|**3 add axis for vector
top = np.cross(idl_seg[None,:,:], r) # np.cross defaults to last axis
db = (mu0 / four_pi) * top / bottom
b = db.sum(axis=-2) # sum over the segments of the current loop
return b
编辑:例如,我可以这样做。现在只有两个大小为nx * ny * nz * nseg * 3 的数组(r 和hold)。也许我应该一次传递较小的points 块,这样它就可以一次全部放入缓存中?
def calc_alt(points, x_seg, idl_seg):
r = points[:, None, :] - x_seg[None, :, :]
hold = np.ones_like(r)*((r**2).sum(axis=-1)**-1.5)[...,None] # note **-1.5 neg
b = (hold * np.cross(idl_seg[None,:,:], r)).sum(axis=-2)
return b * (mu0 / four_pi)
发布其余代码以显示如何使用calc。
import numpy as np
import matplotlib.pyplot as plt
pi, four_pi = np.pi, 4. * np.pi
mu0 = four_pi * 1E-07 # Tesla m/A exact, defined
r0 = 0.05 # meters
I0 = 100.0 # amps
nx, ny, nz = 48, 49, 50
x,y,z = np.linspace(0,2*r0,nx), np.linspace(0,2*r0,ny), np.linspace(0,2*r0,nz)
xg = np.zeros((nx, ny, nz, 3)) # 3D grid of position vectors
xg[...,0] = x[:, None, None] # fill up the positions
xg[...,1] = y[None, :, None]
xg[...,2] = z[None, None, :]
xgv = xg.reshape(nx*ny*nz, 3) # flattened view of spatial points
nseg = 32 # approximate the current loop as a set of discrete points I*dl
theta = np.linspace(0, 2.*pi, nseg+1)[:-1] # get rid of the repeat
xdl = np.zeros((nseg, 3)) # these are the position vectors
idl = np.zeros((nseg, 3)) # these are the current vectors
xdl[:,0], xdl[:,1] = r0 * np.cos(theta), r0 * np.sin(theta)
idl[:,0], idl[:,1] = I0 * -np.sin(theta), I0 * np.cos(theta)
b = calc(xgv, xdl, idl) # HERE IS THE CALCULATION
bv = b.reshape(nx, ny, nz, 3) # make a "3D view" again to use for plotting
bx, by, bz = bv[...,0], bv[...,1], bv[...,2] # make component views
bperp = np.sqrt(bx**2 + by**2) # new array for perp field
zround = np.round(z, 4)
iz = 5 # choose a transverse plane for a plot
fields = [ bz, bperp, bx, by]
names = ['Bz', 'Bperp', 'Bx', 'By']
titles = ["approx " + name + " at z = " + str(zround[iz])
for name in names]
plt.figure()
for i, field in enumerate(fields):
print i
plt.subplot(2, 2, i+1)
plt.imshow(field[..., iz], origin='lower') # fields at iz don't use Jet !!!
plt.title(titles[i])
plt.colorbar()
plt.show()
最后的绘图只是为了看看它似乎正在工作。实际上,永远不要使用默认颜色图。糟糕,可怕,顽皮的杰特!在这种情况下,具有对称 vmin = -vmax 的发散 cmap 可能会很好。 (请参阅 Jake VanderPlas 的 post 和 matplotlib documentation,下面还有一些可爱的演示 here。
【问题讨论】:
-
也许这个问题更适合Code Review?
-
您可能需要考虑在codereview.stackexchange.com 上发布此问题。请注意,总有一种方法可以“更快地做到这一点”,例如不使用 Python。
-
我已经编辑了这个问题,以阐明我想更好地理解如何有效地使用 NumPy 数组和方法。
-
我认为建议
codereview是不公平的,除非您积极参与该交流并遵循这些相同的标签。 -
@hpaulj let's move this conversation to chat.
标签: python-2.7 numpy physics