python - 使用 python 类的元胞自动机

标签 python python-3.x class cellular-automata

我创建了一个启动和更新 CA 数据的类,并且创建了一个函数“Simulate”,该函数根据火灾在树木上蔓延并留下空白空间的规则来更新单元格。根据给定的概率用树替换空白空间。

有一个问题,我的函数似乎正在将规则应用于当前时间数据持有者,而不是先前的时间数据持有者。我已将 prevstate = self.state 设置为上一次迭代的临时数据持有者,但运行小型测试时我发现它给出的结果与我根本不包含此行一样。我做错了什么?

import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, colorConverter
from matplotlib.animation import FuncAnimation

#dimentions:
x = 10
y = 10

lighting = 0  #set to 0 for testing
grow = 0.3


#parameter values
empty = 0
tree = 1
fire = 2

random.seed(1)

#CA Rule definition
def update(mat, i, j, lighting, grow, prob):
    if mat[i, j] == empty:
        if prob < grow:
            return tree
        else:
            return empty
    elif mat[i, j] == tree:
        if max(mat[i-1, j], mat[i+1, j], mat[i, j-1], mat[i, j+1]) == fire:
            return fire
        elif prob < lighting:
            return fire
        else:
            return tree
    else:
        return empty


########## Data Holder
class Simulation:
    def __init__(self):
        self.frame = 0
        #self.state = np.random.randint(2, size=(x, y)) commented out for testing
        self.state = np.ones((x, y))
        self.state[5, 5] = 2  #initial fire started at this location for testing

    def updateS(self):
        prevstate = self.state    #line of code i think should be passing previous iteration through rule

        for i in range(1, y-1):
            for j in range(1, x-1):
                prob = random.random()
                self.state[i, j] = update(prevstate, i, j, lighting, grow, prob)

    def step(self):
        self.updateS()
        self.frame += 1


simulation = Simulation()
figure = plt.figure()

ca_plot = plt.imshow(simulation.state, cmap='seismic', interpolation='bilinear', vmin=empty, vmax=fire)
plt.colorbar(ca_plot)
transparent = colorConverter.to_rgba('black', alpha=0)
#wall_colormap = LinearSegmentedColormap.from_list('my_colormap', [transparent, 'green'], 2)


def animation_func(i):
    simulation.step()
    ca_plot.set_data(simulation.state)
    return ca_plot

animation = FuncAnimation(figure, animation_func, interval=1000)
mng = plt.get_current_fig_manager()
mng.window.showMaximized()
plt.show()

非常欢迎任何有关实现 CA 的更好方法的意见!

最佳答案

Python 赋值是指针...所以当你更新 self.state 时,prevstate 也会更新。

我希望您设置为:

prevstate = copy.copy(self.state)

这应该可以解决您的问题。

Copy docs

关于python - 使用 python 类的元胞自动机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186542/

相关文章:

python - 无法使用 Python 的 mock.patch 模拟 urllib2.urlopen

python - MechanicalSoup 证书验证失败

java - 如何扩展类数组/扩展类后调用类数组属性?

java - 为什么我们在 Java 中实例化一个新对象时必须键入两次类名?

python - BeautifulSoup.get_text() 忽略换行符 <br>

python - super(type(self), self) 的快捷方式

python - 我的程序正确执行所有操作,但它以随机顺序打印输入 [Python 3,初学者]

python - 如何将 timedelta 转换为分钟?

c++ - Item - Inventory - 关系,哪一个应该知道另一个?

python - 如何在openerp 7模块中创建动态字段?