初级版元胞自动机
2021-11-17
1 原因:
- 最近接触了群体智能,想起了元胞自动机
- 之前玩过一个游戏,类似生命游戏,但找不到了
2 实现:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
Xround = [-1,-1,-1,0,0,1,1,1]
Yround = [-1,0,1,-1,1,-1,0,1]
def count_cells(CellM):
rnum = len(CellM)
cnum = len(CellM[0])
cellnum = 0
for i in range(rnum):
for j in range(cnum):
if(CellM[i,j] == 1):
cellnum += 1
return cellnum
def count_round_cell(CellM,i,j,Xround=Xround,Yround=Yround):
'''
count the cells' number around the (i,j) grid
Parameters
----------
CellM : 2-D array
the description of the cells grids.
i : x-position
j : y-position
Xround : list, optional
DESCRIPTION. The default is Xround.
Yround : list, optional
DESCRIPTION. The default is Yround.
Returns
-------
round_cellnum.
'''
rnum = len(CellM)
cnum = len(CellM[0])
round_cellnum = 0
for x in Xround:
xi = i + x
if(xi < 0 or xi >= rnum):
continue
for y in Yround:
yi = j + y
if(yi < 0 or yi >= cnum):
continue
if(CellM[xi,yi] == 1):
round_cellnum += 1
return round_cellnum
def one_mod(CellM):
rnum = len(CellM)
cnum = len(CellM[0])
for i in range(rnum):
for j in range(cnum):
cellstate = CellM[i,j]
round_cellnum = count_round_cell(CellM, i, j)
if(cellstate == 0 and round_cellnum <= 3):
CellM[i,j] = 1
elif(cellstate == 1 and round_cellnum >= 4):
CellM[i,j] = 0
def plot_cellm(CellM):
sns.set()
ax = sns.heatmap(CellM)
plt.show()
CellM = np.zeros((50,50))
CellM[3,3] = 1
CellM[3,4] = 1
CellM[4,3] = 1
CellM[4,4] = 1
print(CellM)
print('number of cells: ',count_cells(CellM))
n = 100
cellnum_list = []
for k in range(n):
one_mod(CellM)
cellnum_list.append(count_cells(CellM))
plot_cellm(CellM)
plt.plot(range(n),cellnum_list)
细胞数目变化结果可视化:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)