python - 加速元胞自动机的绘图
问题描述
我正在实施 Biham-Middleton-Levine 交通模型进行测试,但在实施速度方面遇到了问题。
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
import random
data = np.random.rand(10, 10) * 20
# create discrete colormap
cmap = colors.ListedColormap(['white','red', 'blue'])
bounds = [-0.5,0.5,1.5,2.5]
norm = colors.BoundaryNorm(bounds, cmap.N)
p = 0.5
iter = 1000
sizex = 10
sizey = 10
road = np.zeros((sizex,sizey))
for posx in range(np.shape(road)[0]):
for posy in range(np.shape(road)[1]):
if random.uniform(0,1)<p:
if random.uniform(0,1)<0.5:
road[posx][posy] = 1
else:
road[posx][posy] = 2
road[1][1]=1
road[1,2]=2
print(road)
def check(posx, posy, surf):
type = surf[posx][posy]
if type == 1:
posx, posy = posy, posx
surf = np.transpose(surf)
if posx+1<np.shape(surf)[0]:
if surf[posx+1][posy] == 0:
surf[posx][posy] = 0
surf[posx+1][posy] = type
elif posx+1 == np.shape(surf)[0]:
if surf[0][posy] == 0:
surf[0][posy] = type
surf[posx][posy] = 0
fig, ax = plt.subplots()
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=1)
ax.set_xticks(np.arange(-.5, sizex, 1));
ax.set_yticks(np.arange(-.5, sizey, 1));
ax.set_xticklabels([])
ax.set_yticklabels([])
for iteration in range(iter):
checklist_x = []
checklist_y = []
for posx in range(np.shape(road)[0]):
for posy in range(np.shape(road)[1]):
if road[posx][posy] == 1:
checklist_x.append((posx,posy))
for posx in range(np.shape(road)[0]):
for posy in range(np.shape(road)[1]):
if road[posx][posy] == 2:
checklist_y.append((posx,posy))
for car in checklist_x:
check(car[0],car[1],road)
for car in checklist_y:
check(car[0],car[1],road)
ax.imshow(road, cmap=cmap, norm=norm)
plt.show()
print('done')
我的实现运行非常缓慢,虽然这主要是由于我绘制单元格网格的方式,
fig, ax = plt.subplots()
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=1)
ax.set_xticks(np.arange(-.5, sizex, 1));
ax.set_yticks(np.arange(-.5, sizey, 1));
ax.set_xticklabels([])
ax.set_yticklabels([])
for iteration in range(iter):
checklist_x = []
checklist_y = []
for posx in range(np.shape(road)[0]):
for posy in range(np.shape(road)[1]):
if road[posx][posy] == 1:
checklist_x.append((posx,posy))
for posx in range(np.shape(road)[0]):
for posy in range(np.shape(road)[1]):
if road[posx][posy] == 2:
checklist_y.append((posx,posy))
for car in checklist_x:
check(car[0],car[1],road)
for car in checklist_y:
check(car[0],car[1],road)
ax.imshow(road, cmap=cmap, norm=norm)
plt.show()
print('done')
每次迭代都会重新绘制单元格网格,这是非常密集的,并且大大超过了以数组形式计算下一次迭代应该是什么的计算时间。有没有办法缓存或避免每一步都重绘整个东西?
解决方案
推荐阅读
- firebase - 如何按当前日期从 Cloud Firestore 获取数据?
- angular - 服务和构建命令的 Angular CLI 问题
- php - 用年份 php 对数组进行排序
- .net-core - 与连接到现有总线的消费者一起阅读消息
- xaml - 如何将这三个按钮放在底部的中心?
- python - 为什么我不断收到错误 root 无法找到由“1cccee45d6e7”标识的修订版?
- ios - 尝试使用 Xcode 构建应用程序时出现 React-native 错误
- python - 使用 keras 时,BN 层如何在 DCGAN 中工作?
- javascript - 如何使用 JSON 数据创建所需的 UI
- testcomplete - TC 到 TE 的命令提示符转换