Skip to content

Instantly share code, notes, and snippets.

@RNDcpp
Last active October 13, 2019 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RNDcpp/a4e9a50f47da6c7b9bd8335c6eed5786 to your computer and use it in GitHub Desktop.
Save RNDcpp/a4e9a50f47da6c7b9bd8335c6eed5786 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 初期値の定義
# 初期配置
x=[
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
]
HEIGHT = len(x)
WIDTH = len(x[0])
x = np.array(x).flatten()
N = len(x) # セルの総数 N
E = np.eye(N) # N×Nの単位行列
# 自分自身を含む隣接9セルを1, それ以外を0とした行列
W=[[ 1 if (abs(int(i/WIDTH)-int(j/WIDTH)) <= 1 and abs((i%WIDTH) - (j%WIDTH)) <= 1) else 0 for j in range(N)] for i in range(N) ]
W=np.array(W)
W_up = W - E # W - E は定数なので先に計算しておく
b = 100
T = 60 # シミュレーションの長さ
y=[None]*T # 結果を格納する配列
#=======================
# ライフゲーム本体
#=======================
def f(x): # ライフゲーム関数
return (np.tanh(b*(2.5-W.dot(x)))*np.tanh(b*(W_up.dot(x)-3.5))+1)/2
# シミュレーション
for t in range(T):
y[t] = x
x = f(x)
#=======================
# 結果の出力
#=======================
for t,j in enumerate(y):
for i in np.array_split(j, HEIGHT):
print(np.array(i).round().astype(int))
print("\n")
#=======================
# matplotlibでのアニメーション出力
#=======================
fig = plt.figure()
def animate(i):
plt.cla()
X,Y = np.meshgrid(range(WIDTH), range(HEIGHT))
Z = np.array_split(y[i],HEIGHT)
plt.pcolormesh(X,Y,Z, edgecolors='b')
anim = animation.FuncAnimation(fig,animate,frames=T,interval=200,blit=False)
#anim.save('life.gif', writer='imagemagick') # gif画像として出力する場合
#anim.save('life.mp4') # mp4の動画として出力する場合
plt.show() # 画面に出力する場合
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment