【问题标题】:My animation image is not changing using matplotlib imshow animation我的动画图像没有使用 matplotlib imshow 动画改变
【发布时间】:2019-02-06 16:06:50
【问题描述】:

我想在我的代码中对每个蒙特卡罗循环进行动画处理。但是,图像没有更新,并且与开始时的图像保持一致。

ground_state 是一个二维数组,在每次调用模拟后都会发生变化。我已经检查过它确实在更新中发生了变化

fig = pyplot.figure()
im = pyplot.imshow(ground_state, animated = True)

def update_fig(*args):
    global ground_state
    simulate(ground_state, 100000, 2.4)
    im.set_data(ground_state)
    return im

ani = animation.FuncAnimation(fig, update_fig, interval = 50)

pyplot.show()

这是模拟功能:-

def simulate(state, n, T):
    """
    Simulates at temperature T for N iterations.
    """
    def acceptance_ratio(del_E):
        """
        Calculates the acceptance ratio.
        """
        # value of beta = 1 / (boltzmann constant * T)
        beta = 1 / T
        if (del_E) < 0:
            return 1
        else:
            return e ** (-beta * (del_E))

    step = 0
    cycle = 0
    # Single flipping
    for dummy in range(n):
        switch = (random.choice(range(len(state))), 
random.choice(range(len(state))))
        neighbours = nearest_neighbours(switch[0], switch[1], len(state))
        change_E = 0
        for pos in neighbours:
            change_E += 2 * J * state[pos[0]][pos[1]] * state[switch[0][switch[1]]
    p = acceptance_ratio(change_E)
    step += 1
    if step == 100 * 100:
        cycle += 1
    rand_num = random.random()
    if rand_num <= p:
        state[switch[0]][switch[1]] *= -1
    return state

【问题讨论】:

    标签: python matplotlib animation imshow


    【解决方案1】:

    我们不知道simulate 函数内部发生了什么,但似乎这就是问题的根源,因为否则,代码运行良好并具有动画效果,

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import animation
    
    def simulate(*args):
        global ground_state
        ground_state = np.random.randn(5,5)
    
    simulate()
    
    fig = plt.figure()
    im = plt.imshow(ground_state, animated = True)
    
    def update_fig(*args):
        global ground_state
        simulate(ground_state, 100000, 2.4)
        im.set_data(ground_state)
        return im
    
    ani = animation.FuncAnimation(fig, update_fig, interval = 50)
    
    plt.show()
    

    【讨论】:

    • 我添加了模拟功能的代码。它似乎更新了数组。无论如何,问题是二维数组得到了更新。我已经检查过这件事。我不明白。函数调用所花费的时间是否可能超过动画时间?
    • 这是可能的。在 python 中运行超过 100000 个索引的循环非常慢。
    • 我发现了一个非常奇怪的异常。如果我的初始网格由两个值组成,它运行得很好。但是,当我的初始状态是由单一颜色组成的统一时,它不会。似乎动画在运行时不允许引入新颜色。
    • 您想在每个循环步骤中标准化颜色还是使用单一标准化?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多