我正在尝试设置细胞自动机的动画。 PyCharm不会提出任何错误或警告(经过一些打斗);但是,我不能强迫程序进行多次仿真。
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation as anim
s = np.array([[1,1,1], [1,10,1], [1,1,1]], dtype=np.int8) #Matrix of wages
e = np.zeros((19,), dtype=np.int8) # Vector of rules
e[3]=1
e[12]=1
e[13]=1
ma = np.array([[1, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 0, 1], [1, 0, 0], [0, 0, 0]], dtype=np.int8) #The matrix to be tested
def cnt(num): #Enables counting - equal to frames
if num < 2:
return num
else:
return num + cnt(num-1)
def simulation(frame): #Simulation on a given matrix
count = cnt(8) - frame
n, m = ma.shape
p = np.zeros((n+2, m+2), dtype=np.int8) #Creates an extended matrix, avoiding conflicts at the edges of the initial matrix. Here I construct a torus
p[1:-1, 1:-1] = ma #middle
p[0, 1:-1] = ma[n-1] #the first row of p, the last of ma
p[-1, 1:-1] = ma[0] #the last row of p, the first of ma
p[1:-1, 0] = ma[0:, -1] #left col p, right of ma
p[1:-1, -1] = ma[0:, 0] #right col of p, left of ma
p[-1, 0] = ma[0, -1] #left bottom corner
p[-1, -1] = ma[0, 0] #right bottom corner
p[0, 0] = ma[-1, -1] #left upper corner
p[0, -1] = ma[-1, 0] #right upper corner
new = np.zeros(ma.shape, dtype=np.int8) #matrix to be updated
v, c = p.shape #verses and columns
if count:
for i in range(1, v):
for j in range(1, c):
if p[i-1:i+2, j-1:j+2].shape == (3, 3):
new[i-1, j-1] = e[np.sum(p[i-1:i+2,j-1:j+2]*s)]
plot.set_data(new)
#plt.axes().imshow(new)#.set_array(new) #I have given up this solution - it required adding axes
plt.title("Cellular automaton")
return plot
fig = plt.figure()
plot = plt.imshow(ma)
def init():
plot.set_data(ma)
plt.title("Cellular automaton")
return plot
#fig, ax = plt.subplots() # I have given up this, too
ani = anim.FuncAnimation(fig, simulation, frames = 8, init_func = init, interval = 500, repeat = False)
plt.show()
它仅显示init
和第一个模拟。据推测,我在显示部分(plot.set_data(new)
等)时有些混乱,但我不知道需要更正哪个部分。
第一个解决方案和问题
我已将new
更改为ma
,目前似乎可以使用。但是,矩阵的状态取决于已更改的行。如何强制程序基于初始矩阵运行计算?