Monday, 15 June 2015

Python matplotlib - updating data during animation in Conway's Game of Life -


Code below creates an animation for the life of Conway using Python and matplotlib.

I'm not sure why I have to: grid = newGrid.copy () mat.set_data (grid) < P> Instead of just: > mat.set_data (newGrid)

How can I update the array associated with the plot without the above copy?

  Import numpy like NP import matplotlib.pyplot plt import as matplotlib.animation animation N = 100 ON = 255 OFF = 0 vals = [ON, OFF] # on the grid at random Resize (n, n) def update (data): global grid newGrid = grid.copy () for the range (/) - off grid = np.random.choice (n, p = [0.2, 0.8]) In N: In the range for G (N): total = (grid [i, (j-1)% n] + grid [i, (j + 1)% n] + grid [(i-1)% N, j] + grid [(i + 1)% N, J] + grid [(i-1)% N, (j-1)% N] + grid [(i-1)% n, (j + 1)% N grid [(i +1)% N, (j-1)% N] + grid [(i + 1)% n, (j + 1)% n]) / 255 if c Grid [i, j] == current: if (total; Lt; 2) or (total & gt; 3): new grid [i, j] = off second: if total == 3: new grid [i, j ] = Grid = new grid. Mat.set_data (grid) mat mat back, ax = plt.subplots () Mat = ax.matshow (grid) ani = animation.function animation (fig, update, interval = 50, save_count = 50) plt.show ()   

Output looks correct - I can see gliders and other expected patterns:

 Conway's life game using Python / Mapplibil

There is no specific reason mat.set_data () to newGrid - The important thing is that the gl Global grid gets updated to run with recurrence:

  def update (data): global grid newGrid = grid.pt () "" "to your updates It should be done on a copy of the 'grid' because you are updating the element-by-element, and updates in the previous rows / columns will affect the grid [i] results, which if you have a copy If you do not use # you need u pad to global grid Otherwise the simulation # will not progress, but the copy is not required () mat.set_data (newGrid) grid = newGrid # # There is no reason why you can not do it in the opposite order # grid = NewGrid # mat.set_data (grid) # At least in my version of matplotlib (1.2.1), the animation function was invented artists such as' mat 'or' [mat] ', # no' matte return [mat]   

In addition, in the Function Animation I recommend passing blit = true so that you do not repeat Teams background in every frame.

No comments:

Post a Comment