用python绘制密度图,用Bessel积分绘制衍射图案,但它不会停止运行

2024-10-03 06:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个圆形衍射图, 有一个中心点被一系列的环包围着。 它涉及到一个贝塞尔积分来做,这是在代码中定义的。在

我的问题是,我花了太长时间等待代码运行,但没有得到任何显示。我理解这是因为我的贝塞尔积分每点有1000次迭代,谁能帮上忙?在

我走对了吗?在

我试图通过马克·纽曼的书《计算物理》自学python和计算物理学练习是计算的5.4物理。这里是本章的链接。在第9页。 http://www-personal.umich.edu/~mejn/cp/chapters/int.pdf

这是我要做的形象。在

concentric rings。在

我的代码:

import numpy as np
import pylab as plt
import math as mathy

#N = number of slicices 
#h = b-a/N 

def J(m,x): #Bessel Integral
    def f(theta):
        return (1/mathy.pi)*mathy.cos(m*theta - x*mathy.sin(theta)) #I replaced np. with mathy. for this line

    N = 1000
    A = 0
    a=0
    b=mathy.pi
    h = ((b-a)/N)

    for k in range(1,N,2):

        A +=  4*f(a + h*k)

    for k in range(2,N,2):

        A +=  2*f(a + h*k)

    Idx =  (h/3)*(A + f(a)+f(b))

    return Idx

def I(lmda,r): #Intensity
    k = (mathy.pi/lmda)    
    return ((J(1,k*r))/(k*r))**2

wavelength = .5        # microm meters
I0 = 1
points = 500           
sepration = 0.2  

Intensity = np.empty([points,points],np.float)

for i in range(points):
    y = sepration*i
    for j in range(points):
        x = sepration*j
        r = np.sqrt((x)**2+(y)**2)

        if r < 0.000000000001:
            Intensity[i,j]= 0.5 #this is the lim as r  -> 0, I -> 0.5
        else: 
            Intensity[i,j] = I0*I(wavelength,r)

plt.imshow(Intensity,vmax=0.01,cmap='hot')
plt.gray()
plt.show()

Tags: inimportforreturndefasnppi
1条回答
网友
1楼 · 发布于 2024-10-03 06:23:40

如果我将N减少到100(从1000)并将图像大小(points)减少到50(从500)的话,您的代码似乎运行得很好。在执行大约4s之后,我得到了以下图像:

enter image description here

以下是使用cProfile分析代码时得到的结果:

$ python -m cProfile -s time bessel.py | head -n 10
         361598 function calls (359660 primitive calls) in 3.470 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   252399    2.250    0.000    2.250    0.000 bessel.py:24(f)
     2499    0.821    0.000    3.079    0.001 bessel.py:23(J)
        1    0.027    0.027    3.472    3.472 bessel.py:15(<module>)
     2499    0.015    0.000    3.093    0.001 bessel.py:45(I)
        1    0.013    0.013    0.013    0.013 backend_macosx.py:1(<module>)

因此,您的大部分执行时间似乎都花在f中。您可以优化此函数,或者尝试使用PyPy运行代码。PyPy在优化这类事情上很在行。您需要安装他们的numpy版本(请参见http://pypy.readthedocs.org/en/latest/getting-started.html#)。但是PyPy在我的机器上用40秒就完成了你的原始代码(去掉了绘图的东西)。在

编辑

我的系统上没有在PyPy中安装plotlib,所以最后我用

^{pr2}$

并创建了一个我用普通Python执行的单独程序,其中包含:

import numpy as np
import pylab as plt

Intensity = np.loadtxt('bessel.txt')

plt.imshow(Intensity,vmax=0.01,cmap='hot')
plt.gray()
plt.show()

这将生成下面的图像,并对代码进行以下修改:

sepration = 0.008 # decrease separation

Intensity = np.empty([points,points],np.float)

for i in range(points):
    y = sepration*(i - points/2) # centre on image
    for j in range(points):
        x = sepration*(j - points/2)

enter image description here

相关问题 更多 >