Conway's Game of Life:如何按细胞年龄而非邻居数着色?
数据小陈
结论
如果想让细胞按“年龄”着色,就得另外维护一个和 universe 形状相同的 age 矩阵。传给 imshow 和 set_data 的数据应当是年龄矩阵,不能还是只含 0/1 的 universe。邻居数是每代临时算出来的,年龄记录的则是一个活细胞连续活了多少代。
为什么当前代码只能整块着色
当前绘制用的是 imshow(universe, cmap=discrete_cmap, vmin=0, vmax=1),数据里只有 0 和 1。ListedColormap(['white', 'green', 'red']) 虽然定义了三种颜色,但在 vmin=0, vmax=1 下只有两个有效取值会真正参与映射;img.set_data(universe) 也没有带上年龄信息。因此背景和活细胞只能按 0/1 分成两块显示。
实现步骤
- 初始化
age:活细胞记 1,死细胞记 0。 - 每代先用 GOL 规则算出
next_universe。 - 更新年龄:新生细胞为
age = 1;上一代活着且这一代仍活着的细胞age += 1;死掉的细胞age = 0。 - 绘制时用
np.ma.masked_where(universe == 0, age)把死细胞遮掉,让活细胞按年龄取色。 - 设置
ListedColormap和BoundaryNorm,或者固定vmin/vmax,免得年龄越界后颜色映射失效。
示例代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.colors import ListedColormap, BoundaryNorm
N = 50
P = 0.5
MAX_AGE = 8
def create_universe(N=50, p=0.5):
return np.random.choice([0, 1], size=(N, N), p=[1-p, p])
universe = create_universe(N, P)
age = universe.astype(int).copy()
colors = ['#2ca02c', '#ff7f0e', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22']
cmap = ListedColormap(colors)
cmap.set_bad('white')
norm = BoundaryNorm(np.arange(0.5, MAX_AGE + 1.5), cmap.N, clip=True)
fig, ax = plt.subplots(figsize=(5, 5))
ax.set_xticks([])
ax.set_yticks([])
img = ax.imshow(np.ma.masked_where(universe == 0, age),
interpolation='nearest', cmap=cmap, norm=norm)
gen = 0
def neighbor_count(u):
padded = np.pad(u, 1, mode='constant')
return (padded[:-2, :-2] + padded[:-2, 1:-1] + padded[:-2, 2:] +
padded[1:-1, :-2] + padded[1:-1, 2:] +
padded[2:, :-2] + padded[2:, 1:-1] + padded[2:, 2:])
def animate(frame):
global universe, age, gen
counts = neighbor_count(universe)
birth = (universe == 0) & (counts == 3)
survive = (universe == 1) & ((counts == 2) | (counts == 3))
next_universe = (birth | survive).astype(int)
new_age = np.zeros_like(age)
new_age[next_universe == 1] = 1
alive_and_old = (next_universe == 1) & (universe == 1)
new_age[alive_and_old] = age[alive_and_old] + 1
universe = next_universe
age = new_age
gen += 1
img.set_data(np.ma.masked_where(universe == 0, age))
ax.set_xlabel(f'generations = {gen}, population = {universe.sum()}')
return img,
ani = FuncAnimation(fig, animate, frames=200, interval=200, blit=False)
plt.show()
如果仍想按邻居数着色
把绘制数据改成 counts 就行,比如 img.set_data(np.ma.masked_where(universe == 0, counts)),再用 BoundaryNorm 把 0 到 8 映射到颜色。这里要分清:邻居数是每代重算的临时值,不是细胞连续存活的年龄;死细胞的邻居数一般也不应该拿来上色。
注意事项
set_data只替换图像数据,不会自动改norm或vmin/vmax。年龄范围变了,要么调用set_clim,要么像示例那样固定MAX_AGE并截断超出部分。- 用 masked array 时,
cmap.set_bad('white')可以指定死亡细胞或背景的颜色。 - 计算邻居前别直接把
universe的边界清零;用np.pad补零更稳妥,不会把边界上的活细胞弄掉。 ListedColormap的颜色数量和BoundaryNorm的边界数量要对应上,通常边界数比颜色数多 1。- 年龄会一直增长。实际项目里最好设置最大年龄分桶,或者用循环 colormap;否则颜色映射会越来越难解释。
备注:内容仅供参考。
