脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python实现的matplotlib动画演示之细胞自动机

Python实现的matplotlib动画演示之细胞自动机

2022-12-04 15:14小小明-代码实体 Python

这篇文章主要介绍了Python实现的matplotlib动画演示之细胞自动机,用python来模拟,首先尝试表示Beacon,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下

维基百科上有个有意思的话题叫细胞自动机:https://en.wikipedia.org/wiki/Cellular_automaton

在20世纪70年代,一种名为生命游戏的二维细胞自动机变得广为人知,特别是在早期的计算机界。由约翰 康威发明,马丁 加德纳在《科学美国人》的一篇文章中推广,其规则如下:

  1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

总结就是:任何活细胞在有两到三个活邻居时能活到下一代,否则死亡。任何有三个活邻居的死细胞会变成活细胞,表示繁殖。

在Conway’s Game of Life中,展示了几种初始状态:

Python实现的matplotlib动画演示之细胞自动机

下面我们用python来模拟,首先尝试表示Beacon:

import numpy as np
import matplotlib.pyplot as plt
universe = np.zeros((6, 6), "byte")
# Beacon
universe[1:3, 1:3] = 1
universe[3:5, 3:5] = 1
print(universe)
im = plt.imshow(universe, cmap="binary")
[[0 0 0 0 0 0]
[0 1 1 0 0 0]
[0 1 1 0 0 0]
[0 0 0 1 1 0]
[0 0 0 1 1 0]
[0 0 0 0 0 0]]

Python实现的matplotlib动画演示之细胞自动机

可以看到已经成功的打印出了Beacon的形状,下面我们继续编写细胞自动机的演化规则:

def cellular_auto(universe):
  universe_new = universe.copy()
  h, w = universe.shape
  for y in range(h):
      for x in range(w):
          neighbor_num = universe[x-1:x+2, y-1:y+2].sum()-universe[x, y]
          # 任何有三个活邻居的死细胞都变成了活细胞,繁殖一样。
          if universe[x, y] == 0 and neighbor_num == 3:
              universe_new[x, y] = 1
          # 任何有两到三个活邻居的活细胞都能活到下一代,否则就会死亡。
          if universe[x, y] == 1 and neighbor_num not in (2, 3):
              universe_new[x, y] = 0
  return universe_new
universe = cellular_auto(universe)
print(universe)
plt.axis("off")
im = plt.imshow(universe, cmap="binary")
[[0 0 0 0 0 0]
[0 1 1 0 0 0]
[0 1 0 0 0 0]
[0 0 0 0 1 0]
[0 0 0 1 1 0]
[0 0 0 0 0 0]]

Python实现的matplotlib动画演示之细胞自动机

 

ArtistAnimation动画

基于此我们可以制作matplotlib的动画,下面直接将Blinker、Toad、Beacon都放上去:

from matplotlib import animation
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook

def cellular_auto(universe):
  universe_new = universe.copy()
  h, w = universe.shape
  for y in range(h):
      for x in range(w):
          neighbor_num = universe[x-1:x+2, y-1:y+2].sum()-universe[x, y]
          # 任何有三个活邻居的死细胞都变成了活细胞,繁殖一样。
          if universe[x, y] == 0 and neighbor_num == 3:
              universe_new[x, y] = 1
          # 任何有两到三个活邻居的活细胞都能活到下一代,否则就会死亡。
          if universe[x, y] == 1 and neighbor_num not in (2, 3):
              universe_new[x, y] = 0
  return universe_new
universe = np.zeros((12, 12), "byte")
# Blinker
universe[2, 1:4] = 1
# Beacon
universe[4:6, 5:7] = 1
universe[6:8, 7:9] = 1
# Toad
universe[8, 2:5] = 1
universe[9, 1:4] = 1
fig = plt.figure()
plt.axis("off")
im = plt.imshow(universe, cmap="binary")
frame = []
for _ in range(2):
  frame.append((plt.imshow(universe, cmap="binary"),))
  universe = cellular_auto(universe)
animation.ArtistAnimation(fig, frame, interval=500, blit=True)

Python实现的matplotlib动画演示之细胞自动机

然后我们画一下Pulsar:

# Pulsar
universe = np.zeros((17, 17), "byte")
universe[[2, 7, 9, 14], 4:7] = 1
universe[[2, 7, 9, 14], 10:13] = 1
universe[4:7, [2, 7, 9, 14]] = 1
universe[10:13, [2, 7, 9, 14]] = 1
fig = plt.figure()
plt.axis("off")
im = plt.imshow(universe, cmap="binary")
frame = []
for _ in range(3):
  frame.append((plt.imshow(universe, cmap="binary"),))
  universe = cellular_auto(universe)
animation.ArtistAnimation(fig, frame, interval=500, blit=True)

Python实现的matplotlib动画演示之细胞自动机

 

FuncAnimation动画

另一种创建matplotlib动画的方法是使用FuncAnimation,完整代码:

from matplotlib import animation
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import HTML
# %matplotlib notebook

def cellular_auto(universe):
  universe_new = universe.copy()
  h, w = universe.shape
  for y in range(h):
      for x in range(w):
          neighbor_num = universe[x-1:x+2, y-1:y+2].sum()-universe[x, y]
          # 任何有三个活邻居的死细胞都变成了活细胞,繁殖一样。
          if universe[x, y] == 0 and neighbor_num == 3:
              universe_new[x, y] = 1
          # 任何有两到三个活邻居的活细胞都能活到下一代,否则就会死亡。
          if universe[x, y] == 1 and neighbor_num not in (2, 3):
              universe_new[x, y] = 0
  return universe_new
def update(i=0):
  global universe
  im.set_data(universe)
  universe = cellular_auto(universe)
  return im,
# Pulsar
universe = np.zeros((17, 17), "byte")
universe[[2, 7, 9, 14], 4:7] = 1
universe[[2, 7, 9, 14], 10:13] = 1
universe[4:7, [2, 7, 9, 14]] = 1
universe[10:13, [2, 7, 9, 14]] = 1
fig = plt.figure()
plt.axis("off")
im = plt.imshow(universe, cmap="binary")
plt.show()
anim = animation.FuncAnimation(
  fig, update, frames=3, interval=500, blit=True)
HTML(anim.to_jshtml())

Python实现的matplotlib动画演示之细胞自动机

这种动画生成速度较慢,好处是可以导出html文件:

with open("out.html", "w") as f:
  f.write(anim.to_jshtml())

还可以保存MP4视频:

anim.save("out.mp4")

或gif动画:

anim.save("out.gif")

注意:保存MP4视频或GIF动画,需要事先将ffmpeg配置到环境变量中

ffmpeg下载地址:

链接: https://pan.baidu.com/s/1aioB_BwpKb6LxJs26HbbiQ?pwd=ciui
提取码: ciui

 

随机生命游戏

接下来,我们创建一个50*50的二维生命棋盘,并选取其中1500个位置作为初始活细胞点,我们看看最终生成的动画如何。

完整代码如下:

from matplotlib import animation
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook

def cellular_auto(universe):
  universe_new = universe.copy()
  h, w = universe.shape
  for y in range(1, h-1):
      for x in range(1, w-1):
          neighbor_num = universe[x-1:x+2, y-1:y+2].sum()-universe[x, y]
          # 任何有三个活邻居的死细胞都变成了活细胞,繁殖一样。
          if universe[x, y] == 0 and neighbor_num == 3:
              universe_new[x, y] = 1
          # 任何有两到三个活邻居的活细胞都能活到下一代,否则就会死亡。
          if universe[x, y] == 1 and neighbor_num not in (2, 3):
              universe_new[x, y] = 0
  # 边缘置零
  universe[[0, -1]] = 0
  universe[:, [0, -1]] = 0
  return universe_new
boardsize, pad = 50, 2
universe = np.zeros((boardsize+pad, boardsize+pad), "byte")
# 随机选取1500个点作为初始活细胞
for i in range(1500):
  x, y = np.random.randint(1, boardsize+1, 2)
  universe[y, x] = 1
  
fig = plt.figure()
plt.axis("off")
im = plt.imshow(universe, cmap="binary")
frame = []
for _ in range(200):
  frame.append((plt.imshow(universe, cmap="binary"),))
  universe = cellular_auto(universe)
animation.ArtistAnimation(fig, frame, interval=50, blit=True)

Python实现的matplotlib动画演示之细胞自动机

到此这篇关于Python实现的matplotlib动画演示之细胞自动机的文章就介绍到这了,更多相关python  matplotlib动画内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/as604049322/article/details/124309635

延伸 · 阅读

精彩推荐
  • PythonPython 如何将integer转化为罗马数(3999以内)

    Python 如何将integer转化为罗马数(3999以内)

    这篇文章主要介绍了Python 将integer转化为罗马数(3999以内)的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    Jlinkk6382021-11-23
  • PythonPython函数的周期性执行实现方法

    Python函数的周期性执行实现方法

    这篇文章主要介绍了Python函数的周期性执行实现方法,涉及Python使用sched模块实现函数周期性调度触发的相关技巧,需要的朋友可以参考下...

    intergret9112020-09-04
  • Pythonpandas 颠倒列顺序的两种解决方案

    pandas 颠倒列顺序的两种解决方案

    这篇文章主要介绍了pandas 颠倒列顺序的两种解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    勤劳的大乐乐13952021-09-29
  • Pythonpycharm 解除默认unittest模式的方法

    pycharm 解除默认unittest模式的方法

    今天小编就为大家分享一篇pycharm 解除默认unittest模式的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    weixin_369762188652021-04-23
  • Python使用50行Python代码从零开始实现一个AI平衡小游戏

    使用50行Python代码从零开始实现一个AI平衡小游戏

    本文会为大家展示机器学习专家 Mike Shi 如何用 50 行 Python 代码创建一个 AI,使用增强学习技术,玩耍一个保持杆子平衡的小游戏。本文给大家带来实现思路...

    景略集智7882021-04-21
  • PythonPython Behave框架学习

    Python Behave框架学习

    behave是python语言的行为驱动开发,全称:Behavior-driven development,简称BDD,它是一种敏捷软件开发技术,它鼓励软件项目中的开发人员、QA和非技术或业务参...

    jasonj333332022-07-13
  • PythonPython模糊查询本地文件夹去除文件后缀的实例(7行代码)

    Python模糊查询本地文件夹去除文件后缀的实例(7行代码)

    下面小编就为大家带来一篇Python模糊查询本地文件夹去除文件后缀的实例(7行代码) 。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随...

    xsan5212020-12-16
  • PythonPython实现笑脸检测+人脸口罩检测功能

    Python实现笑脸检测+人脸口罩检测功能

    这篇文章主要介绍了Python实现笑脸检测+人脸口罩检测,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...

    白码王子小张8372021-12-18