滑块实时更改波包动画Matplotlib

2024-05-23 19:52:55 发布

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

我的动画速度较慢,因为更新功能会不断计算矩阵,而矩阵仅在我移动滑块时才会更改:

def evolve(psi0, height, width):
    global psi
    potential = potentialBarrier(height, width)
    tM = timeMatrix(hamiltonian(potential))
    psi = tM.dot(psi0)
    presenceProbability = abs(psi) ** 2
    norm = sum(presenceProbability)
    presenceProbability /= norm
    psi /= norm ** 0.5
    return presenceProbability


def update(frame):
    line.set_ydata(evolve(psi, potentialSlider.val*10, widthSlider.val))
    line2.set_ydata(potentialBarrier(potentialSlider.val, widthSlider.val))
    return

wavePacketAnimation = animation.FuncAnimation(fig, update, interval=5, blit=False)

当我移动滑块值时,如何使更新函数仅计算矩阵的新结果,而当我不移动滑块时,如何使用以前的结果

我试图定义我的矩阵全局,但没有成功。到目前为止我已经知道了

sliderHasChanged = True
tM = timeMatrix(hamiltonian(potentialBarrierInit))


def evolve(psi0, height, width):
    global tM
    global sliderHasChanged
    if sliderHasChanged:
        potential = potentialBarrier(height * 10, width)
        tM = timeMatrix(hamiltonian(potential))
        sliderHasChanged = False
    global psi 
    psi = tM.dot(psi0)
    presenceProbability = abs(psi) ** 2
    norm = sum(presenceProbability)
    presenceProbability /= norm
    psi /= norm ** 0.5
    return presenceProbability


potentialSlider_ax = fig.add_axes([0.25, 0.15, 0.65, 0.03])
potentialSlider = Slider(potentialSlider_ax, '$V_0$', 0, 1, valinit=0.1)
potentialSlider.label.set_size(15)

widthSlider_ax = fig.add_axes([0.25, 0.1, 0.65, 0.03])
widthSlider = Slider(widthSlider_ax, '$a$', 0, 20, valinit=10.0)
widthSlider.label.set_size(15)


def sliderChange():
    global sliderHasChanged
    sliderHasChanged = True
    return


potentialSlider.on_changed(sliderChange())
widthSlider.on_changed(sliderChange())


def update(frame):
    line.set_ydata(evolve(psi, potentialSlider.val, widthSlider.val))
    line2.set_ydata(potentialBarrier(potentialSlider.val, widthSlider.val))
    return


wavePacketAnimation = animation.FuncAnimation(fig, update, interval=5, blit=False)
wavePacketAnimation.running = True

动画使用初始矩阵值运行良好,但滑块中的更改不会影响动画


Tags: normreturndef矩阵valglobaltm滑块