Мое анимационное изображение не меняется с помощью анимации matplotlib imshow - PullRequest
0 голосов
/ 06 февраля 2019

Я хочу анимировать прохождение каждого цикла Монте-Карло в моем коде.Тем не менее, изображение не обновляется и остается тем же, что и началось с.

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

1 Ответ

0 голосов
/ 06 февраля 2019

Мы не можем знать, что происходит внутри функции 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()

animated image

...