import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.animation as animation
import random
# 定义森林的大小
forest_size = 100
# 定义火焰的初始位置
fire_start = (forest_size // 2, forest_size // 2)
# 定义森林的状态
forest = np.zeros((forest_size, forest_size)).astype("int")
forest[fire_start] = 1#1是着火
# 定义火焰的传播规则
def spread_fire(forest):
new_forest = np.copy(forest)
for i in range(forest_size):
for j in range(forest_size):
if forest[i, j] == 1:
# 火焰蔓延到相邻的元胞
if i > 0 and forest[i-1, j] == 0:
new_forest[i-1, j] = 1
if i < forest_size-1 and forest[i+1, j] == 0:
new_forest[i+1, j] = 1
if j > 0 and forest[i, j-1] == 0:
new_forest[i, j-1] = 1
if j < forest_size-1 and forest[i, j+1] == 0:
new_forest[i, j+1] = 1
# 火焰熄灭
new_forest[i, j] = 2
return new_forest
#定义树生长
def tree_grow(forest,g):
new_forest=np.copy(forest)
for i in range(forest_size):
for j in range(forest_size):
if forest[i][j]==2 and random.random()<g:
new_forest[i][j]=0
return new_forest
# 迭代模拟火焰传播
iterations = 50
heatmap = np.zeros((forest_size, forest_size, iterations))#这是一个有50个100*100的矩阵
heatmap[:, :, 0] = forest
#准备折线图数据
y_fire=[]
fire_sum=0
y_grow=[]
grow_sum=0
y_tree=[]
tree_sum=0
x=range(1,iterations)
for i in range(1, iterations):
forest=tree_grow(forest=forest,g=0.4)
forest = spread_fire(forest)
for m in range(forest_size):
for n in range(forest_size):
if(forest[m][n]==0):
fire_sum+=1
if(forest[m][n]==1):
tree_sum+=1
if(forest[m][n]==2):
grow_sum+=1
y_fire.append(fire_sum)
y_tree.append(tree_sum)
y_grow.append(grow_sum)
fire_sum=0
tree_sum=0
grow_sum=0
heatmap[:, :, i] = forest
# 绘制每次迭代的热力图
fig, ax = plt.subplots(figsize=(8, 8))
cmap = colors.ListedColormap(['green', 'red', 'black'])
bounds = [0, 1, 2, 3]
norm = colors.BoundaryNorm(bounds, cmap.N)
im = ax.imshow(heatmap[:, :, 0], cmap=cmap, norm=norm)
# 添加颜色条
# 添加颜色条
cbar = ax.figure.colorbar(im, ax=ax, ticks=[0, 1, 2], orientation='vertical')
cbar.ax.set_yticklabels(['Unburned', 'Burning', 'Burned'])
# 设置图像标题和标签
ax.set_title('Forest Fire Simulation')
ax.set_xlabel('X')
ax.set_ylabel('Y')
# 更新每次迭代的热力图
def update(i):
im.set_array(heatmap[:, :, i])
return [im]
# 动画显示每次迭代的热力图
ani = animation.FuncAnimation(fig, update, frames=iterations, interval=200, blit=True)
#绘制折线图
print(y_fire)
a,b=plt.subplots(figsize=(8,8))
b.plot(x,y_fire,label="fire",color="red")
b.plot(x,y_grow,label="grow",color="black")
b.plot(x,y_tree,label="tree",color="green")
plt.legend()
plt.show()
直接上代码,元胞自动机的概念可以去网上搜